openpgp.js

    1(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.openpgp = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
    2(function (global){
    3"use strict";
    4
    5!function (e, t) {
    6  "object" == typeof exports && "undefined" != typeof module ? t(exports) : "function" == typeof define && define.amd ? define(["exports"], t) : t((e = e || self).WebStreamsPolyfill = {});
    7}(undefined, function (e) {
    8  "use strict";
    9  const t = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? Symbol : e => `Symbol(${e})`;const r = "undefined" != typeof self ? self : "undefined" != typeof window ? window : "undefined" != typeof global ? global : void 0,
   10        o = Number.isNaN || function (e) {
   11    return e != e;
   12  };function n(e) {
   13    return "object" == typeof e && null !== e || "function" == typeof e;
   14  }function i(e, t, r) {
   15    Object.defineProperty(e, t, { value: r, writable: !0, enumerable: !0, configurable: !0 });
   16  }function a(e) {
   17    return e.slice();
   18  }function s(e, t, r, o, n) {
   19    new Uint8Array(e).set(new Uint8Array(r, o, n), t);
   20  }function l(e) {
   21    return !1 !== function (e) {
   22      if ("number" != typeof e) return !1;if (o(e)) return !1;if (e < 0) return !1;return !0;
   23    }(e) && e !== 1 / 0;
   24  }function c(e, t, r) {
   25    if ("function" != typeof e) throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e, t, r);
   26  }function u(e, t, r, o) {
   27    const n = e[t];if (void 0 !== n) {
   28      if ("function" != typeof n) throw new TypeError(`${n} is not a method`);switch (r) {case 0:
   29          return () => f(n, e, o);case 1:
   30          return t => {
   31            const r = [t].concat(o);return f(n, e, r);
   32          };}
   33    }return () => Promise.resolve();
   34  }function d(e, t, r) {
   35    const o = e[t];if (void 0 !== o) return c(o, e, r);
   36  }function f(e, t, r) {
   37    try {
   38      return Promise.resolve(c(e, t, r));
   39    } catch (e) {
   40      return Promise.reject(e);
   41    }
   42  }function _(e) {
   43    return e;
   44  }function h(e) {
   45    if (e = Number(e), o(e) || e < 0) throw new RangeError("highWaterMark property of a queuing strategy must be non-negative and non-NaN");return e;
   46  }function b(e) {
   47    if (void 0 === e) return () => 1;if ("function" != typeof e) throw new TypeError("size property of a queuing strategy must be a function");return t => e(t);
   48  }function m(e, t, r) {
   49    return Promise.prototype.then.call(e, t, r);
   50  }function y(e, t, r) {
   51    let o, n;const i = new Promise((e, t) => {
   52      o = e, n = t;
   53    });void 0 === r && (r = e => {
   54      throw e;
   55    });return function (e, t, r) {
   56      let o = !1;const n = e => {
   57        !1 === o && (o = !0, r(e));
   58      };let i = 0,
   59          a = 0;const s = e.length,
   60            l = new Array(s);for (const r of e) {
   61        const e = i;m(r, r => {
   62          l[e] = r, ++a === s && t(l);
   63        }, n), ++i;
   64      }
   65    }(e, e => {
   66      try {
   67        const r = t(e);o(r);
   68      } catch (e) {
   69        n(e);
   70      }
   71    }, e => {
   72      try {
   73        const t = r(e);o(t);
   74      } catch (e) {
   75        n(e);
   76      }
   77    }), i;
   78  }function p(e) {}function w(e) {
   79    e && e instanceof p.AssertionError && setTimeout(() => {
   80      throw e;
   81    }, 0);
   82  }function g(e) {
   83    const t = e._queue.shift();return e._queueTotalSize -= t.size, e._queueTotalSize < 0 && (e._queueTotalSize = 0), t.value;
   84  }function S(e, t, r) {
   85    if (!l(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;
   86  }function v(e) {
   87    e._queue = [], e._queueTotalSize = 0;
   88  }p.AssertionError = function () {};const R = t("[[AbortSteps]]"),
   89        P = t("[[ErrorSteps]]");class WritableStream {
   90    constructor(e = {}, t = {}) {
   91      q(this);const r = t.size;let o = t.highWaterMark;if (void 0 !== e.type) throw new RangeError("Invalid type is specified");const n = b(r);void 0 === o && (o = 1), function (e, t, r, o) {
   92        const n = Object.create(WritableStreamDefaultController.prototype);const i = u(t, "write", 1, [n]),
   93              a = u(t, "close", 0, []),
   94              s = u(t, "abort", 1, []);$(e, n, function () {
   95          return d(t, "start", [n]);
   96        }, i, a, s, r, o);
   97      }(this, e, o = h(o), n);
   98    }get locked() {
   99      if (!1 === E(this)) throw G("locked");return C(this);
  100    }abort(e) {
  101      return !1 === E(this) ? Promise.reject(G("abort")) : !0 === C(this) ? Promise.reject(new TypeError("Cannot abort a stream that already has a writer")) : j(this, e);
  102    }getWriter() {
  103      if (!1 === E(this)) throw G("getWriter");return T(this);
  104    }
  105  }function T(e) {
  106    return new WritableStreamDefaultWriter(e);
  107  }function q(e) {
  108    e._state = "writable", e._storedError = void 0, e._writer = void 0, e._writableStreamController = void 0, e._writeRequests = [], e._inFlightWriteRequest = void 0, e._closeRequest = void 0, e._inFlightCloseRequest = void 0, e._pendingAbortRequest = void 0, e._backpressure = !1;
  109  }function E(e) {
  110    return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_writableStreamController");
  111  }function C(e) {
  112    return void 0 !== e._writer;
  113  }function j(e, t) {
  114    const r = e._state;if ("closed" === r || "errored" === r) return Promise.resolve(void 0);if (void 0 !== e._pendingAbortRequest) return e._pendingAbortRequest._promise;let o = !1;"erroring" === r && (o = !0, t = void 0);const n = new Promise((r, n) => {
  115      e._pendingAbortRequest = { _promise: void 0, _resolve: r, _reject: n, _reason: t, _wasAlreadyErroring: o };
  116    });return e._pendingAbortRequest._promise = n, !1 === o && W(e, t), n;
  117  }function A(e, t) {
  118    "writable" !== e._state ? B(e) : W(e, t);
  119  }function W(e, t) {
  120    const r = e._writableStreamController;e._state = "erroring", e._storedError = t;const o = e._writer;void 0 !== o && D(o, t), !1 === function (e) {
  121      if (void 0 === e._inFlightWriteRequest && void 0 === e._inFlightCloseRequest) return !1;return !0;
  122    }(e) && !0 === r._started && B(e);
  123  }function B(e) {
  124    e._state = "errored", e._writableStreamController[P]();const t = e._storedError;for (const r of e._writeRequests) r._reject(t);if (e._writeRequests = [], void 0 === e._pendingAbortRequest) return void z(e);const r = e._pendingAbortRequest;if (e._pendingAbortRequest = void 0, !0 === r._wasAlreadyErroring) return r._reject(t), void z(e);e._writableStreamController[R](r._reason).then(() => {
  125      r._resolve(), z(e);
  126    }, t => {
  127      r._reject(t), z(e);
  128    });
  129  }function O(e) {
  130    return void 0 !== e._closeRequest || void 0 !== e._inFlightCloseRequest;
  131  }function z(e) {
  132    void 0 !== e._closeRequest && (e._closeRequest._reject(e._storedError), e._closeRequest = void 0);const t = e._writer;void 0 !== t && ee(t, e._storedError);
  133  }function k(e, t) {
  134    const r = e._writer;void 0 !== r && t !== e._backpressure && (!0 === t ? function (e) {
  135      re(e);
  136    }(r) : ae(r)), e._backpressure = t;
  137  }class WritableStreamDefaultWriter {
  138    constructor(e) {
  139      if (!1 === E(e)) throw new TypeError("WritableStreamDefaultWriter can only be constructed with a WritableStream instance");if (!0 === C(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) !1 === O(e) && !0 === e._backpressure ? re(this) : ne(this), X(this);else if ("erroring" === t) oe(this, e._storedError), X(this);else if ("closed" === t) ne(this), function (e) {
  140        X(e), te(e);
  141      }(this);else {
  142        const t = e._storedError;oe(this, t), Z(this, t);
  143      }
  144    }get closed() {
  145      return !1 === F(this) ? Promise.reject(J("closed")) : this._closedPromise;
  146    }get desiredSize() {
  147      if (!1 === F(this)) throw J("desiredSize");if (void 0 === this._ownerWritableStream) throw K("desiredSize");return function (e) {
  148        const t = e._ownerWritableStream,
  149              r = t._state;if ("errored" === r || "erroring" === r) return null;if ("closed" === r) return 0;return Q(t._writableStreamController);
  150      }(this);
  151    }get ready() {
  152      return !1 === F(this) ? Promise.reject(J("ready")) : this._readyPromise;
  153    }abort(e) {
  154      return !1 === F(this) ? Promise.reject(J("abort")) : void 0 === this._ownerWritableStream ? Promise.reject(K("abort")) : function (e, t) {
  155        return j(e._ownerWritableStream, t);
  156      }(this, e);
  157    }close() {
  158      if (!1 === F(this)) return Promise.reject(J("close"));const e = this._ownerWritableStream;return void 0 === e ? Promise.reject(K("close")) : !0 === O(e) ? Promise.reject(new TypeError("cannot close an already-closing stream")) : L(this);
  159    }releaseLock() {
  160      if (!1 === F(this)) throw J("releaseLock");void 0 !== this._ownerWritableStream && M(this);
  161    }write(e) {
  162      return !1 === F(this) ? Promise.reject(J("write")) : void 0 === this._ownerWritableStream ? Promise.reject(K("write to")) : Y(this, e);
  163    }
  164  }function F(e) {
  165    return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_ownerWritableStream");
  166  }function L(e) {
  167    const t = e._ownerWritableStream,
  168          r = t._state;if ("closed" === r || "errored" === r) return Promise.reject(new TypeError(`The stream (in ${r} state) is not in the writable state and cannot be closed`));const o = new Promise((e, r) => {
  169      const o = { _resolve: e, _reject: r };t._closeRequest = o;
  170    });return !0 === t._backpressure && "writable" === r && ae(e), function (e) {
  171      S(e, "close", 0), x(e);
  172    }(t._writableStreamController), o;
  173  }function I(e, t) {
  174    "pending" === e._closedPromiseState ? ee(e, t) : function (e, t) {
  175      Z(e, t);
  176    }(e, t);
  177  }function D(e, t) {
  178    "pending" === e._readyPromiseState ? ie(e, t) : function (e, t) {
  179      oe(e, t);
  180    }(e, t);
  181  }function M(e) {
  182    const t = e._ownerWritableStream,
  183          r = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");D(e, r), I(e, r), t._writer = void 0, e._ownerWritableStream = void 0;
  184  }function Y(e, t) {
  185    const r = e._ownerWritableStream,
  186          o = r._writableStreamController,
  187          n = function (e, t) {
  188      try {
  189        return e._strategySizeAlgorithm(t);
  190      } catch (t) {
  191        return H(e, t), 1;
  192      }
  193    }(o, t);if (r !== e._ownerWritableStream) return Promise.reject(K("write to"));const i = r._state;if ("errored" === i) return Promise.reject(r._storedError);if (!0 === O(r) || "closed" === i) return Promise.reject(new TypeError("The stream is closing or closed and cannot be written to"));if ("erroring" === i) return Promise.reject(r._storedError);const a = function (e) {
  194      return new Promise((t, r) => {
  195        const o = { _resolve: t, _reject: r };e._writeRequests.push(o);
  196      });
  197    }(r);return function (e, t, r) {
  198      const o = { chunk: t };try {
  199        S(e, o, r);
  200      } catch (t) {
  201        return void H(e, t);
  202      }const n = e._controlledWritableStream;if (!1 === O(n) && "writable" === n._state) {
  203        const t = U(e);k(n, t);
  204      }x(e);
  205    }(o, t, n), a;
  206  }class WritableStreamDefaultController {
  207    constructor() {
  208      throw new TypeError("WritableStreamDefaultController cannot be constructed explicitly");
  209    }error(e) {
  210      if (!1 === function (e) {
  211        if (!n(e)) return !1;if (!Object.prototype.hasOwnProperty.call(e, "_controlledWritableStream")) return !1;return !0;
  212      }(this)) throw new TypeError("WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController");"writable" === this._controlledWritableStream._state && V(this, e);
  213    }[R](e) {
  214      const t = this._abortAlgorithm(e);return N(this), t;
  215    }[P]() {
  216      v(this);
  217    }
  218  }function $(e, t, r, o, n, i, a, s) {
  219    t._controlledWritableStream = e, e._writableStreamController = t, t._queue = void 0, t._queueTotalSize = void 0, v(t), t._started = !1, t._strategySizeAlgorithm = s, t._strategyHWM = a, t._writeAlgorithm = o, t._closeAlgorithm = n, t._abortAlgorithm = i;const l = U(t);k(e, l);const c = r();Promise.resolve(c).then(() => {
  220      t._started = !0, x(t);
  221    }, r => {
  222      t._started = !0, A(e, r);
  223    }).catch(w);
  224  }function N(e) {
  225    e._writeAlgorithm = void 0, e._closeAlgorithm = void 0, e._abortAlgorithm = void 0, e._strategySizeAlgorithm = void 0;
  226  }function Q(e) {
  227    return e._strategyHWM - e._queueTotalSize;
  228  }function x(e) {
  229    const t = e._controlledWritableStream;if (!1 === e._started) return;if (void 0 !== t._inFlightWriteRequest) return;const r = t._state;if ("closed" === r || "errored" === r) return;if ("erroring" === r) return void B(t);if (0 === e._queue.length) return;const o = function (e) {
  230      return e._queue[0].value;
  231    }(e);"close" === o ? function (e) {
  232      const t = e._controlledWritableStream;(function (e) {
  233        e._inFlightCloseRequest = e._closeRequest, e._closeRequest = void 0;
  234      })(t), g(e);const r = e._closeAlgorithm();N(e), r.then(() => {
  235        !function (e) {
  236          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 && te(t);
  237        }(t);
  238      }, e => {
  239        !function (e, t) {
  240          e._inFlightCloseRequest._reject(t), e._inFlightCloseRequest = void 0, void 0 !== e._pendingAbortRequest && (e._pendingAbortRequest._reject(t), e._pendingAbortRequest = void 0), A(e, t);
  241        }(t, e);
  242      }).catch(w);
  243    }(e) : function (e, t) {
  244      const r = e._controlledWritableStream;(function (e) {
  245        e._inFlightWriteRequest = e._writeRequests.shift();
  246      })(r), e._writeAlgorithm(t).then(() => {
  247        !function (e) {
  248          e._inFlightWriteRequest._resolve(void 0), e._inFlightWriteRequest = void 0;
  249        }(r);const t = r._state;if (g(e), !1 === O(r) && "writable" === t) {
  250          const t = U(e);k(r, t);
  251        }x(e);
  252      }, t => {
  253        "writable" === r._state && N(e), function (e, t) {
  254          e._inFlightWriteRequest._reject(t), e._inFlightWriteRequest = void 0, A(e, t);
  255        }(r, t);
  256      }).catch(w);
  257    }(e, o.chunk);
  258  }function H(e, t) {
  259    "writable" === e._controlledWritableStream._state && V(e, t);
  260  }function U(e) {
  261    return Q(e) <= 0;
  262  }function V(e, t) {
  263    const r = e._controlledWritableStream;N(e), W(r, t);
  264  }function G(e) {
  265    return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`);
  266  }function J(e) {
  267    return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`);
  268  }function K(e) {
  269    return new TypeError("Cannot " + e + " a stream using a released writer");
  270  }function X(e) {
  271    e._closedPromise = new Promise((t, r) => {
  272      e._closedPromise_resolve = t, e._closedPromise_reject = r, e._closedPromiseState = "pending";
  273    });
  274  }function Z(e, t) {
  275    X(e), ee(e, t);
  276  }function ee(e, t) {
  277    e._closedPromise.catch(() => {}), e._closedPromise_reject(t), e._closedPromise_resolve = void 0, e._closedPromise_reject = void 0, e._closedPromiseState = "rejected";
  278  }function te(e) {
  279    e._closedPromise_resolve(void 0), e._closedPromise_resolve = void 0, e._closedPromise_reject = void 0, e._closedPromiseState = "resolved";
  280  }function re(e) {
  281    e._readyPromise = new Promise((t, r) => {
  282      e._readyPromise_resolve = t, e._readyPromise_reject = r;
  283    }), e._readyPromiseState = "pending";
  284  }function oe(e, t) {
  285    re(e), ie(e, t);
  286  }function ne(e) {
  287    re(e), ae(e);
  288  }function ie(e, t) {
  289    e._readyPromise.catch(() => {}), e._readyPromise_reject(t), e._readyPromise_resolve = void 0, e._readyPromise_reject = void 0, e._readyPromiseState = "rejected";
  290  }function ae(e) {
  291    e._readyPromise_resolve(void 0), e._readyPromise_resolve = void 0, e._readyPromise_reject = void 0, e._readyPromiseState = "fulfilled";
  292  }const se = Number.isInteger || function (e) {
  293    return "number" == typeof e && isFinite(e) && Math.floor(e) === e;
  294  },
  295        le = t("[[CancelSteps]]"),
  296        ce = t("[[PullSteps]]");class ReadableStream {
  297    constructor(e = {}, t = {}) {
  298      fe(this);const r = t.size;let o = t.highWaterMark;const n = e.type;if ("bytes" === String(n)) {
  299        if (void 0 !== r) throw new RangeError("The strategy for a byte stream cannot have a size function");void 0 === o && (o = 0), function (e, t, r) {
  300          const o = Object.create(ReadableByteStreamController.prototype);const n = u(t, "pull", 0, [o]),
  301                i = u(t, "cancel", 1, []);let a = t.autoAllocateChunkSize;if (void 0 !== a && (a = Number(a), !1 === se(a) || a <= 0)) throw new RangeError("autoAllocateChunkSize must be a positive integer");!function (e, t, r, o, n, i, a) {
  302            t._controlledReadableByteStream = e, t._pullAgain = !1, t._pulling = !1, He(t), t._queue = t._queueTotalSize = void 0, v(t), t._closeRequested = !1, t._started = !1, t._strategyHWM = h(i), t._pullAlgorithm = o, t._cancelAlgorithm = n, t._autoAllocateChunkSize = a, t._pendingPullIntos = [], e._readableStreamController = t;const s = r();Promise.resolve(s).then(() => {
  303              t._started = !0, xe(t);
  304            }, e => {
  305              nt(t, e);
  306            }).catch(w);
  307          }(e, o, function () {
  308            return d(t, "start", [o]);
  309          }, n, i, r, a);
  310        }(this, e, o = h(o));
  311      } else {
  312        if (void 0 !== n) throw new RangeError("Invalid type is specified");{
  313          const t = b(r);void 0 === o && (o = 1), function (e, t, r, o) {
  314            const n = Object.create(ReadableStreamDefaultController.prototype);const i = u(t, "pull", 0, [n]),
  315                  a = u(t, "cancel", 1, []);$e(e, n, function () {
  316              return d(t, "start", [n]);
  317            }, i, a, r, o);
  318          }(this, e, o = h(o), t);
  319        }
  320      }
  321    }get locked() {
  322      if (!1 === _e(this)) throw st("locked");return he(this);
  323    }cancel(e) {
  324      return !1 === _e(this) ? Promise.reject(st("cancel")) : !0 === he(this) ? Promise.reject(new TypeError("Cannot cancel a stream that already has a reader")) : pe(this, e);
  325    }getReader({ mode: e } = {}) {
  326      if (!1 === _e(this)) throw st("getReader");if (void 0 === e) return ue(this);if ("byob" === (e = String(e))) return function (e) {
  327        return new ReadableStreamBYOBReader(e);
  328      }(this);throw new RangeError("Invalid mode is specified");
  329    }pipeThrough({ writable: e, readable: t }, { preventClose: r, preventAbort: o, preventCancel: n, signal: i } = {}) {
  330      if (!1 === _e(this)) throw st("pipeThrough");if (!1 === E(e)) throw new TypeError("writable argument to pipeThrough must be a WritableStream");if (!1 === _e(t)) throw new TypeError("readable argument to pipeThrough must be a ReadableStream");if (r = Boolean(r), o = Boolean(o), n = Boolean(n), void 0 !== i && !at(i)) throw new TypeError("ReadableStream.prototype.pipeThrough's signal option must be an AbortSignal");if (!0 === he(this)) throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if (!0 === C(e)) throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return be(this, e, r, o, n, i).catch(() => {}), t;
  331    }pipeTo(e, { preventClose: t, preventAbort: r, preventCancel: o, signal: n } = {}) {
  332      return !1 === _e(this) ? Promise.reject(st("pipeTo")) : !1 === E(e) ? Promise.reject(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")) : (t = Boolean(t), r = Boolean(r), o = Boolean(o), void 0 === n || at(n) ? !0 === he(this) ? Promise.reject(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")) : !0 === C(e) ? Promise.reject(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")) : be(this, e, t, r, o, n) : Promise.reject(new TypeError("ReadableStream.prototype.pipeTo's signal option must be an AbortSignal")));
  333    }tee() {
  334      if (!1 === _e(this)) throw st("tee");const e = function (e, t) {
  335        const r = ue(e);let o,
  336            n,
  337            i,
  338            s,
  339            l,
  340            c = !1,
  341            u = !1,
  342            d = !1;const f = new Promise(e => {
  343          l = e;
  344        });function _() {
  345          return Be(r).then(e => {
  346            const t = e.value,
  347                  r = e.done;if (!0 === r && !1 === c && (!1 === u && Le(i._readableStreamController), !1 === d && Le(s._readableStreamController), c = !0), !0 === c) return;const o = t,
  348                  n = t;!1 === u && Ie(i._readableStreamController, o), !1 === d && Ie(s._readableStreamController, n);
  349          });
  350        }function h() {}return i = de(h, _, function (t) {
  351          if (u = !0, o = t, !0 === d) {
  352            const t = a([o, n]),
  353                  r = pe(e, t);l(r);
  354          }return f;
  355        }), s = de(h, _, function (t) {
  356          if (d = !0, n = t, !0 === u) {
  357            const t = a([o, n]),
  358                  r = pe(e, t);l(r);
  359          }return f;
  360        }), r._closedPromise.catch(e => {
  361          !0 !== c && (De(i._readableStreamController, e), De(s._readableStreamController, e), c = !0);
  362        }), [i, s];
  363      }(this);return a(e);
  364    }
  365  }function ue(e) {
  366    return new ReadableStreamDefaultReader(e);
  367  }function de(e, t, r, o = 1, n = () => 1) {
  368    const i = Object.create(ReadableStream.prototype);return fe(i), $e(i, Object.create(ReadableStreamDefaultController.prototype), e, t, r, o, n), i;
  369  }function fe(e) {
  370    e._state = "readable", e._reader = void 0, e._storedError = void 0, e._disturbed = !1;
  371  }function _e(e) {
  372    return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_readableStreamController");
  373  }function he(e) {
  374    return void 0 !== e._reader;
  375  }function be(e, t, r, o, n, i) {
  376    const a = ue(e),
  377          s = T(t);let l = !1,
  378        c = Promise.resolve();return new Promise((u, d) => {
  379      let f;if (void 0 !== i) {
  380        if (f = () => {
  381          const r = new DOMException("Aborted", "AbortError"),
  382                i = [];!1 === o && i.push(() => "writable" === t._state ? j(t, r) : Promise.resolve()), !1 === n && i.push(() => "readable" === e._state ? pe(e, r) : Promise.resolve()), b(() => y(i.map(e => e()), e => e), !0, r);
  383        }, !0 === i.aborted) return void f();i.addEventListener("abort", f);
  384      }if (h(e, a._closedPromise, e => {
  385        !1 === o ? b(() => j(t, e), !0, e) : m(!0, e);
  386      }), h(t, s._closedPromise, t => {
  387        !1 === n ? b(() => pe(e, t), !0, t) : m(!0, t);
  388      }), function (e, t, r) {
  389        "closed" === e._state ? r() : t.then(r).catch(w);
  390      }(e, a._closedPromise, () => {
  391        !1 === r ? b(() => function (e) {
  392          const t = e._ownerWritableStream,
  393                r = t._state;return !0 === O(t) || "closed" === r ? Promise.resolve() : "errored" === r ? Promise.reject(t._storedError) : L(e);
  394        }(s)) : m();
  395      }), !0 === O(t) || "closed" === t._state) {
  396        const t = new TypeError("the destination writable stream closed before all data could be piped to it");!1 === n ? b(() => pe(e, t), !0, t) : m(!0, t);
  397      }function _() {
  398        const e = c;return c.then(() => e !== c ? _() : void 0);
  399      }function h(e, t, r) {
  400        "errored" === e._state ? r(e._storedError) : t.catch(r).catch(w);
  401      }function b(e, r, o) {
  402        function n() {
  403          e().then(() => p(r, o), e => p(!0, e)).catch(w);
  404        }!0 !== l && (l = !0, "writable" === t._state && !1 === O(t) ? _().then(n) : n());
  405      }function m(e, r) {
  406        !0 !== l && (l = !0, "writable" === t._state && !1 === O(t) ? _().then(() => p(e, r)).catch(w) : p(e, r));
  407      }function p(e, t) {
  408        M(s), We(a), void 0 !== i && i.removeEventListener("abort", f), e ? d(t) : u(void 0);
  409      }new Promise((e, t) => {
  410        !function r(o) {
  411          o ? e() : (!0 === l ? Promise.resolve(!0) : s._readyPromise.then(() => Be(a).then(({ value: e, done: t }) => !0 === t || (c = Y(s, e).catch(() => {}), !1)))).then(r, t);
  412        }(!1);
  413      }).catch(e => {
  414        c = Promise.resolve(), w(e);
  415      });
  416    });
  417  }function me(e, t) {
  418    return new Promise((r, o) => {
  419      const n = { _resolve: r, _reject: o, _forAuthorCode: t };e._reader._readIntoRequests.push(n);
  420    });
  421  }function ye(e, t) {
  422    return new Promise((r, o) => {
  423      const n = { _resolve: r, _reject: o, _forAuthorCode: t };e._reader._readRequests.push(n);
  424    });
  425  }function pe(e, t) {
  426    if (e._disturbed = !0, "closed" === e._state) return Promise.resolve(void 0);if ("errored" === e._state) return Promise.reject(e._storedError);return we(e), e._readableStreamController[le](t).then(() => void 0);
  427  }function we(e) {
  428    e._state = "closed";const t = e._reader;if (void 0 !== t) {
  429      if (Ce(t)) {
  430        for (const _ref of t._readRequests) {
  431          const e = _ref._resolve;
  432          const r = _ref._forAuthorCode;
  433          e(ge(void 0, !0, r));
  434        }t._readRequests = [];
  435      }_t(t);
  436    }
  437  }function ge(e, t, r) {
  438    let o = null;!0 === r && (o = Object.prototype);const n = Object.create(o);return Object.defineProperty(n, "value", { value: e, enumerable: !0, writable: !0, configurable: !0 }), Object.defineProperty(n, "done", { value: t, enumerable: !0, writable: !0, configurable: !0 }), n;
  439  }function Se(e, t) {
  440    e._state = "errored", e._storedError = t;const r = e._reader;if (void 0 !== r) {
  441      if (Ce(r)) {
  442        for (const e of r._readRequests) e._reject(t);r._readRequests = [];
  443      } else {
  444        for (const e of r._readIntoRequests) e._reject(t);r._readIntoRequests = [];
  445      }ft(r, t);
  446    }
  447  }function ve(e, t, r) {
  448    const o = e._reader._readRequests.shift();o._resolve(ge(t, r, o._forAuthorCode));
  449  }function Re(e) {
  450    return e._reader._readIntoRequests.length;
  451  }function Pe(e) {
  452    return e._reader._readRequests.length;
  453  }function Te(e) {
  454    const t = e._reader;return void 0 !== t && !!Ee(t);
  455  }function qe(e) {
  456    const t = e._reader;return void 0 !== t && !!Ce(t);
  457  }class ReadableStreamDefaultReader {
  458    constructor(e) {
  459      if (!1 === _e(e)) throw new TypeError("ReadableStreamDefaultReader can only be constructed with a ReadableStream instance");if (!0 === he(e)) throw new TypeError("This stream has already been locked for exclusive reading by another reader");je(this, e), this._readRequests = [];
  460    }get closed() {
  461      return Ce(this) ? this._closedPromise : Promise.reject(ct("closed"));
  462    }cancel(e) {
  463      return Ce(this) ? void 0 === this._ownerReadableStream ? Promise.reject(lt("cancel")) : Ae(this, e) : Promise.reject(ct("cancel"));
  464    }read() {
  465      return Ce(this) ? void 0 === this._ownerReadableStream ? Promise.reject(lt("read from")) : Be(this, !0) : Promise.reject(ct("read"));
  466    }releaseLock() {
  467      if (!Ce(this)) throw ct("releaseLock");if (void 0 !== this._ownerReadableStream) {
  468        if (this._readRequests.length > 0) throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");We(this);
  469      }
  470    }
  471  }class ReadableStreamBYOBReader {
  472    constructor(e) {
  473      if (!_e(e)) throw new TypeError("ReadableStreamBYOBReader can only be constructed with a ReadableStream instance given a byte source");if (!1 === Ne(e._readableStreamController)) throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");if (he(e)) throw new TypeError("This stream has already been locked for exclusive reading by another reader");je(this, e), this._readIntoRequests = [];
  474    }get closed() {
  475      return Ee(this) ? this._closedPromise : Promise.reject(ht("closed"));
  476    }cancel(e) {
  477      return Ee(this) ? void 0 === this._ownerReadableStream ? Promise.reject(lt("cancel")) : Ae(this, e) : Promise.reject(ht("cancel"));
  478    }read(e) {
  479      return Ee(this) ? void 0 === this._ownerReadableStream ? Promise.reject(lt("read from")) : ArrayBuffer.isView(e) ? (e.buffer, 0 === e.byteLength ? Promise.reject(new TypeError("view must have non-zero byteLength")) : function (e, t, r = !1) {
  480        const o = e._ownerReadableStream;if (o._disturbed = !0, "errored" === o._state) return Promise.reject(o._storedError);return function (e, t, r) {
  481          const o = e._controlledReadableByteStream;let n = 1;t.constructor !== DataView && (n = t.constructor.BYTES_PER_ELEMENT);const i = t.constructor,
  482                a = { buffer: _(t.buffer), byteOffset: t.byteOffset, byteLength: t.byteLength, bytesFilled: 0, elementSize: n, ctor: i, readerType: "byob" };if (e._pendingPullIntos.length > 0) return e._pendingPullIntos.push(a), me(o, r);if ("closed" === o._state) {
  483            const e = new i(a.buffer, a.byteOffset, 0);return Promise.resolve(ge(e, !0, r));
  484          }if (e._queueTotalSize > 0) {
  485            if (!0 === Je(e, a)) {
  486              const t = Ve(a);return Xe(e), Promise.resolve(ge(t, !1, r));
  487            }if (!0 === e._closeRequested) {
  488              const t = new TypeError("Insufficient bytes to fill elements in the given buffer");return nt(e, t), Promise.reject(t);
  489            }
  490          }e._pendingPullIntos.push(a);const s = me(o, r);return xe(e), s;
  491        }(o._readableStreamController, t, r);
  492      }(this, e, !0)) : Promise.reject(new TypeError("view must be an array buffer view")) : Promise.reject(ht("read"));
  493    }releaseLock() {
  494      if (!Ee(this)) throw ht("releaseLock");if (void 0 !== this._ownerReadableStream) {
  495        if (this._readIntoRequests.length > 0) throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");We(this);
  496      }
  497    }
  498  }function Ee(e) {
  499    return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_readIntoRequests");
  500  }function Ce(e) {
  501    return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_readRequests");
  502  }function je(e, t) {
  503    e._ownerReadableStream = t, t._reader = e, "readable" === t._state ? ut(e) : "closed" === t._state ? function (e) {
  504      ut(e), _t(e);
  505    }(e) : dt(e, t._storedError);
  506  }function Ae(e, t) {
  507    return pe(e._ownerReadableStream, t);
  508  }function We(e) {
  509    "readable" === e._ownerReadableStream._state ? ft(e, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")) : function (e, t) {
  510      dt(e, t);
  511    }(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;
  512  }function Be(e, t = !1) {
  513    const r = e._ownerReadableStream;return r._disturbed = !0, "closed" === r._state ? Promise.resolve(ge(void 0, !0, t)) : "errored" === r._state ? Promise.reject(r._storedError) : r._readableStreamController[ce](t);
  514  }class ReadableStreamDefaultController {
  515    constructor() {
  516      throw new TypeError();
  517    }get desiredSize() {
  518      if (!1 === Oe(this)) throw bt("desiredSize");return Me(this);
  519    }close() {
  520      if (!1 === Oe(this)) throw bt("close");if (!1 === Ye(this)) throw new TypeError("The stream is not in a state that permits close");Le(this);
  521    }enqueue(e) {
  522      if (!1 === Oe(this)) throw bt("enqueue");if (!1 === Ye(this)) throw new TypeError("The stream is not in a state that permits enqueue");return Ie(this, e);
  523    }error(e) {
  524      if (!1 === Oe(this)) throw bt("error");De(this, e);
  525    }[le](e) {
  526      v(this);const t = this._cancelAlgorithm(e);return Fe(this), t;
  527    }[ce](e) {
  528      const t = this._controlledReadableStream;if (this._queue.length > 0) {
  529        const r = g(this);return !0 === this._closeRequested && 0 === this._queue.length ? (Fe(this), we(t)) : ze(this), Promise.resolve(ge(r, !1, e));
  530      }const r = ye(t, e);return ze(this), r;
  531    }
  532  }function Oe(e) {
  533    return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_controlledReadableStream");
  534  }function ze(e) {
  535    !1 !== ke(e) && (!0 !== e._pulling ? (e._pulling = !0, e._pullAlgorithm().then(() => {
  536      if (e._pulling = !1, !0 === e._pullAgain) return e._pullAgain = !1, ze(e);
  537    }, t => {
  538      De(e, t);
  539    }).catch(w)) : e._pullAgain = !0);
  540  }function ke(e) {
  541    const t = e._controlledReadableStream;return !1 !== Ye(e) && !1 !== e._started && (!0 === he(t) && Pe(t) > 0 || Me(e) > 0);
  542  }function Fe(e) {
  543    e._pullAlgorithm = void 0, e._cancelAlgorithm = void 0, e._strategySizeAlgorithm = void 0;
  544  }function Le(e) {
  545    const t = e._controlledReadableStream;e._closeRequested = !0, 0 === e._queue.length && (Fe(e), we(t));
  546  }function Ie(e, t) {
  547    const r = e._controlledReadableStream;if (!0 === he(r) && Pe(r) > 0) ve(r, t, !1);else {
  548      let r;try {
  549        r = e._strategySizeAlgorithm(t);
  550      } catch (t) {
  551        throw De(e, t), t;
  552      }try {
  553        S(e, t, r);
  554      } catch (t) {
  555        throw De(e, t), t;
  556      }
  557    }ze(e);
  558  }function De(e, t) {
  559    const r = e._controlledReadableStream;"readable" === r._state && (v(e), Fe(e), Se(r, t));
  560  }function Me(e) {
  561    const t = e._controlledReadableStream._state;return "errored" === t ? null : "closed" === t ? 0 : e._strategyHWM - e._queueTotalSize;
  562  }function Ye(e) {
  563    const t = e._controlledReadableStream._state;return !1 === e._closeRequested && "readable" === t;
  564  }function $e(e, t, r, o, n, i, a) {
  565    t._controlledReadableStream = e, t._queue = void 0, t._queueTotalSize = void 0, v(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;const s = r();Promise.resolve(s).then(() => {
  566      t._started = !0, ze(t);
  567    }, e => {
  568      De(t, e);
  569    }).catch(w);
  570  }class ReadableStreamBYOBRequest {
  571    constructor() {
  572      throw new TypeError("ReadableStreamBYOBRequest cannot be used directly");
  573    }get view() {
  574      if (!1 === Qe(this)) throw mt("view");return this._view;
  575    }respond(e) {
  576      if (!1 === Qe(this)) throw mt("respond");if (void 0 === this._associatedReadableByteStreamController) throw new TypeError("This BYOB request has been invalidated");this._view.buffer, function (e, t) {
  577        if (!1 === l(t = Number(t))) throw new RangeError("bytesWritten must be a finite");tt(e, t);
  578      }(this._associatedReadableByteStreamController, e);
  579    }respondWithNewView(e) {
  580      if (!1 === Qe(this)) throw mt("respond");if (void 0 === this._associatedReadableByteStreamController) throw new TypeError("This BYOB request has been invalidated");if (!ArrayBuffer.isView(e)) throw new TypeError("You can only respond with array buffer views");e.buffer, function (e, t) {
  581        const r = e._pendingPullIntos[0];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, tt(e, t.byteLength);
  582      }(this._associatedReadableByteStreamController, e);
  583    }
  584  }class ReadableByteStreamController {
  585    constructor() {
  586      throw new TypeError("ReadableByteStreamController constructor cannot be used directly");
  587    }get byobRequest() {
  588      if (!1 === Ne(this)) throw yt("byobRequest");if (void 0 === this._byobRequest && this._pendingPullIntos.length > 0) {
  589        const e = this._pendingPullIntos[0],
  590              t = new Uint8Array(e.buffer, e.byteOffset + e.bytesFilled, e.byteLength - e.bytesFilled),
  591              r = Object.create(ReadableStreamBYOBRequest.prototype);!function (e, t, r) {
  592          e._associatedReadableByteStreamController = t, e._view = r;
  593        }(r, this, t), this._byobRequest = r;
  594      }return this._byobRequest;
  595    }get desiredSize() {
  596      if (!1 === Ne(this)) throw yt("desiredSize");return it(this);
  597    }close() {
  598      if (!1 === Ne(this)) throw yt("close");if (!0 === 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) {
  599        const t = e._controlledReadableByteStream;if (e._queueTotalSize > 0) return void (e._closeRequested = !0);if (e._pendingPullIntos.length > 0) {
  600          const t = e._pendingPullIntos[0];if (t.bytesFilled > 0) {
  601            const t = new TypeError("Insufficient bytes to fill elements in the given buffer");throw nt(e, t), t;
  602          }
  603        }ot(e), we(t);
  604      }(this);
  605    }enqueue(e) {
  606      if (!1 === Ne(this)) throw yt("enqueue");if (!0 === 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`);if (!ArrayBuffer.isView(e)) throw new TypeError("You can only enqueue array buffer views when using a ReadableByteStreamController");e.buffer, function (e, t) {
  607        const r = e._controlledReadableByteStream,
  608              o = t.buffer,
  609              n = t.byteOffset,
  610              i = t.byteLength,
  611              a = _(o);if (!0 === qe(r)) {
  612          if (0 === Pe(r)) Ge(e, a, n, i);else {
  613            const e = new Uint8Array(a, n, i);ve(r, e, !1);
  614          }
  615        } else !0 === Te(r) ? (Ge(e, a, n, i), et(e)) : Ge(e, a, n, i);xe(e);
  616      }(this, e);
  617    }error(e) {
  618      if (!1 === Ne(this)) throw yt("error");nt(this, e);
  619    }[le](e) {
  620      if (this._pendingPullIntos.length > 0) {
  621        this._pendingPullIntos[0].bytesFilled = 0;
  622      }v(this);const t = this._cancelAlgorithm(e);return ot(this), t;
  623    }[ce](e) {
  624      const t = this._controlledReadableByteStream;if (this._queueTotalSize > 0) {
  625        const t = this._queue.shift();let r;this._queueTotalSize -= t.byteLength, Xe(this);try {
  626          r = new Uint8Array(t.buffer, t.byteOffset, t.byteLength);
  627        } catch (e) {
  628          return Promise.reject(e);
  629        }return Promise.resolve(ge(r, !1, e));
  630      }const r = this._autoAllocateChunkSize;if (void 0 !== r) {
  631        let e;try {
  632          e = new ArrayBuffer(r);
  633        } catch (e) {
  634          return Promise.reject(e);
  635        }const t = { buffer: e, byteOffset: 0, byteLength: r, bytesFilled: 0, elementSize: 1, ctor: Uint8Array, readerType: "default" };this._pendingPullIntos.push(t);
  636      }const o = ye(t, e);return xe(this), o;
  637    }
  638  }function Ne(e) {
  639    return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_controlledReadableByteStream");
  640  }function Qe(e) {
  641    return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_associatedReadableByteStreamController");
  642  }function xe(e) {
  643    !1 !== function (e) {
  644      const t = e._controlledReadableByteStream;if ("readable" !== t._state) return !1;if (!0 === e._closeRequested) return !1;if (!1 === e._started) return !1;if (!0 === qe(t) && Pe(t) > 0) return !0;if (!0 === Te(t) && Re(t) > 0) return !0;if (it(e) > 0) return !0;return !1;
  645    }(e) && (!0 !== e._pulling ? (e._pulling = !0, e._pullAlgorithm().then(() => {
  646      e._pulling = !1, !0 === e._pullAgain && (e._pullAgain = !1, xe(e));
  647    }, t => {
  648      nt(e, t);
  649    }).catch(w)) : e._pullAgain = !0);
  650  }function He(e) {
  651    Ze(e), e._pendingPullIntos = [];
  652  }function Ue(e, t) {
  653    let r = !1;"closed" === e._state && (r = !0);const o = Ve(t);"default" === t.readerType ? ve(e, o, r) : function (e, t, r) {
  654      const o = e._reader._readIntoRequests.shift();o._resolve(ge(t, r, o._forAuthorCode));
  655    }(e, o, r);
  656  }function Ve(e) {
  657    const t = e.bytesFilled,
  658          r = e.elementSize;return new e.ctor(e.buffer, e.byteOffset, t / r);
  659  }function Ge(e, t, r, o) {
  660    e._queue.push({ buffer: t, byteOffset: r, byteLength: o }), e._queueTotalSize += o;
  661  }function Je(e, t) {
  662    const r = t.elementSize,
  663          o = t.bytesFilled - t.bytesFilled % r,
  664          n = Math.min(e._queueTotalSize, t.byteLength - t.bytesFilled),
  665          i = t.bytesFilled + n,
  666          a = i - i % r;let l = n,
  667        c = !1;a > o && (l = a - t.bytesFilled, c = !0);const u = e._queue;for (; l > 0;) {
  668      const r = u[0],
  669            o = Math.min(l, r.byteLength),
  670            n = t.byteOffset + t.bytesFilled;s(t.buffer, n, r.buffer, r.byteOffset, o), r.byteLength === o ? u.shift() : (r.byteOffset += o, r.byteLength -= o), e._queueTotalSize -= o, Ke(e, o, t), l -= o;
  671    }return c;
  672  }function Ke(e, t, r) {
  673    Ze(e), r.bytesFilled += t;
  674  }function Xe(e) {
  675    0 === e._queueTotalSize && !0 === e._closeRequested ? (ot(e), we(e._controlledReadableByteStream)) : xe(e);
  676  }function Ze(e) {
  677    void 0 !== e._byobRequest && (e._byobRequest._associatedReadableByteStreamController = void 0, e._byobRequest._view = void 0, e._byobRequest = void 0);
  678  }function et(e) {
  679    for (; e._pendingPullIntos.length > 0;) {
  680      if (0 === e._queueTotalSize) return;const t = e._pendingPullIntos[0];!0 === Je(e, t) && (rt(e), Ue(e._controlledReadableByteStream, t));
  681    }
  682  }function tt(e, t) {
  683    const r = e._pendingPullIntos[0];if ("closed" === e._controlledReadableByteStream._state) {
  684      if (0 !== t) throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");!function (e, t) {
  685        t.buffer = _(t.buffer);const r = e._controlledReadableByteStream;if (!0 === Te(r)) for (; Re(r) > 0;) Ue(r, rt(e));
  686      }(e, r);
  687    } else !function (e, t, r) {
  688      if (r.bytesFilled + t > r.byteLength) throw new RangeError("bytesWritten out of range");if (Ke(e, t, r), r.bytesFilled < r.elementSize) return;rt(e);const o = r.bytesFilled % r.elementSize;if (o > 0) {
  689        const t = r.byteOffset + r.bytesFilled,
  690              n = r.buffer.slice(t - o, t);Ge(e, n, 0, n.byteLength);
  691      }r.buffer = _(r.buffer), r.bytesFilled -= o, Ue(e._controlledReadableByteStream, r), et(e);
  692    }(e, t, r);xe(e);
  693  }function rt(e) {
  694    const t = e._pendingPullIntos.shift();return Ze(e), t;
  695  }function ot(e) {
  696    e._pullAlgorithm = void 0, e._cancelAlgorithm = void 0;
  697  }function nt(e, t) {
  698    const r = e._controlledReadableByteStream;"readable" === r._state && (He(e), v(e), ot(e), Se(r, t));
  699  }function it(e) {
  700    const t = e._controlledReadableByteStream._state;return "errored" === t ? null : "closed" === t ? 0 : e._strategyHWM - e._queueTotalSize;
  701  }function at(e) {
  702    if ("object" != typeof e || null === e) return !1;const t = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted").get;try {
  703      return t.call(e), !0;
  704    } catch (e) {
  705      return !1;
  706    }
  707  }function st(e) {
  708    return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`);
  709  }function lt(e) {
  710    return new TypeError("Cannot " + e + " a stream using a released reader");
  711  }function ct(e) {
  712    return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`);
  713  }function ut(e) {
  714    e._closedPromise = new Promise((t, r) => {
  715      e._closedPromise_resolve = t, e._closedPromise_reject = r;
  716    });
  717  }function dt(e, t) {
  718    ut(e), ft(e, t);
  719  }function ft(e, t) {
  720    e._closedPromise.catch(() => {}), e._closedPromise_reject(t), e._closedPromise_resolve = void 0, e._closedPromise_reject = void 0;
  721  }function _t(e) {
  722    e._closedPromise_resolve(void 0), e._closedPromise_resolve = void 0, e._closedPromise_reject = void 0;
  723  }function ht(e) {
  724    return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`);
  725  }function bt(e) {
  726    return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`);
  727  }function mt(e) {
  728    return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`);
  729  }function yt(e) {
  730    return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`);
  731  }class ByteLengthQueuingStrategy {
  732    constructor({ highWaterMark: e }) {
  733      i(this, "highWaterMark", e);
  734    }size(e) {
  735      return e.byteLength;
  736    }
  737  }class CountQueuingStrategy {
  738    constructor({ highWaterMark: e }) {
  739      i(this, "highWaterMark", e);
  740    }size() {
  741      return 1;
  742    }
  743  }class TransformStream {
  744    constructor(e = {}, t = {}, r = {}) {
  745      const o = t.size;let n = t.highWaterMark;const i = r.size;let a = r.highWaterMark;if (void 0 !== e.writableType) throw new RangeError("Invalid writable type specified");const s = b(o);if (void 0 === n && (n = 1), n = h(n), void 0 !== e.readableType) throw new RangeError("Invalid readable type specified");const l = b(i);let c;void 0 === a && (a = 0), a = h(a), function (e, t, r, o, n, i) {
  746        function a() {
  747          return t;
  748        }e._writable = function (e, t, r, o, n = 1, i = () => 1) {
  749          const a = Object.create(WritableStream.prototype);return q(a), $(a, Object.create(WritableStreamDefaultController.prototype), e, t, r, o, n, i), a;
  750        }(a, function (t) {
  751          return function (e, t) {
  752            const r = e._transformStreamController;if (!0 === e._backpressure) {
  753              const o = e._backpressureChangePromise;return o.then(() => {
  754                const o = e._writable,
  755                      n = o._state;if ("erroring" === n) throw o._storedError;return Tt(r, t);
  756              });
  757            }return Tt(r, t);
  758          }(e, t);
  759        }, function () {
  760          return function (e) {
  761            const t = e._readable,
  762                  r = e._transformStreamController,
  763                  o = r._flushAlgorithm();return Rt(r), o.then(() => {
  764              if ("errored" === t._state) throw t._storedError;const e = t._readableStreamController;!0 === Ye(e) && Le(e);
  765            }).catch(r => {
  766              throw wt(e, r), t._storedError;
  767            });
  768          }(e);
  769        }, function (t) {
  770          return function (e, t) {
  771            return wt(e, t), Promise.resolve();
  772          }(e, t);
  773        }, r, o), e._readable = de(a, function () {
  774          return function (e) {
  775            return St(e, !1), e._backpressureChangePromise;
  776          }(e);
  777        }, function (t) {
  778          return gt(e, t), Promise.resolve();
  779        }, n, i), e._backpressure = void 0, e._backpressureChangePromise = void 0, e._backpressureChangePromise_resolve = void 0, St(e, !0), e._transformStreamController = void 0;
  780      }(this, new Promise(e => {
  781        c = e;
  782      }), n, s, a, l), function (e, t) {
  783        const r = Object.create(TransformStreamDefaultController.prototype);let o = e => {
  784          try {
  785            return Pt(r, e), Promise.resolve();
  786          } catch (e) {
  787            return Promise.reject(e);
  788          }
  789        };const n = t.transform;if (void 0 !== n) {
  790          if ("function" != typeof n) throw new TypeError("transform is not a method");o = e => f(n, t, [e, r]);
  791        }const i = u(t, "flush", 0, [r]);!function (e, t, r, o) {
  792          t._controlledTransformStream = e, e._transformStreamController = t, t._transformAlgorithm = r, t._flushAlgorithm = o;
  793        }(e, r, o, i);
  794      }(this, e);const _ = d(e, "start", [this._transformStreamController]);c(_);
  795    }get readable() {
  796      if (!1 === pt(this)) throw Et("readable");return this._readable;
  797    }get writable() {
  798      if (!1 === pt(this)) throw Et("writable");return this._writable;
  799    }
  800  }function pt(e) {
  801    return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_transformStreamController");
  802  }function wt(e, t) {
  803    De(e._readable._readableStreamController, t), gt(e, t);
  804  }function gt(e, t) {
  805    Rt(e._transformStreamController), H(e._writable._writableStreamController, t), !0 === e._backpressure && St(e, !1);
  806  }function St(e, t) {
  807    void 0 !== e._backpressureChangePromise && e._backpressureChangePromise_resolve(), e._backpressureChangePromise = new Promise(t => {
  808      e._backpressureChangePromise_resolve = t;
  809    }), e._backpressure = t;
  810  }class TransformStreamDefaultController {
  811    constructor() {
  812      throw new TypeError("TransformStreamDefaultController instances cannot be created directly");
  813    }get desiredSize() {
  814      if (!1 === vt(this)) throw qt("desiredSize");return Me(this._controlledTransformStream._readable._readableStreamController);
  815    }enqueue(e) {
  816      if (!1 === vt(this)) throw qt("enqueue");Pt(this, e);
  817    }error(e) {
  818      if (!1 === vt(this)) throw qt("error");!function (e, t) {
  819        wt(e._controlledTransformStream, t);
  820      }(this, e);
  821    }terminate() {
  822      if (!1 === vt(this)) throw qt("terminate");!function (e) {
  823        const t = e._controlledTransformStream,
  824              r = t._readable._readableStreamController;!0 === Ye(r) && Le(r);const o = new TypeError("TransformStream terminated");gt(t, o);
  825      }(this);
  826    }
  827  }function vt(e) {
  828    return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_controlledTransformStream");
  829  }function Rt(e) {
  830    e._transformAlgorithm = void 0, e._flushAlgorithm = void 0;
  831  }function Pt(e, t) {
  832    const r = e._controlledTransformStream,
  833          o = r._readable._readableStreamController;if (!1 === Ye(o)) throw new TypeError("Readable side is not in a state that permits enqueue");try {
  834      Ie(o, t);
  835    } catch (e) {
  836      throw gt(r, e), r._readable._storedError;
  837    }(function (e) {
  838      return !0 !== ke(e);
  839    })(o) !== r._backpressure && St(r, !0);
  840  }function Tt(e, t) {
  841    return e._transformAlgorithm(t).catch(t => {
  842      throw wt(e._controlledTransformStream, t), t;
  843    });
  844  }function qt(e) {
  845    return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`);
  846  }function Et(e) {
  847    return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`);
  848  }const Ct = { ReadableStream: ReadableStream, WritableStream: WritableStream, ByteLengthQueuingStrategy: ByteLengthQueuingStrategy, CountQueuingStrategy: CountQueuingStrategy, TransformStream: TransformStream };void 0 !== r && Object.assign(r, Ct), e.ReadableStream = ReadableStream, e.WritableStream = WritableStream, e.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy, e.CountQueuingStrategy = CountQueuingStrategy, e.TransformStream = TransformStream, Object.defineProperty(e, "__esModule", { value: !0 });
  849});
  850
  851
  852}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  853},{}],2:[function(require,module,exports){
  854'use strict';
  855
  856const ea_lib = require('email-addresses');
  857
  858exports.parse = function parse(line, startAt) {
  859    if (!line) throw 'Nothing to parse';
  860
  861    line = line.trim();
  862
  863    const addr = ea_lib({
  864        input: line,
  865        rfc6532: true, // unicode
  866        partial: false, // return failed parses
  867        simple: false, // simple AST
  868        strict: false, // turn off obs- features in the rfc
  869        rejectTLD: false, // domains require a "."
  870        startAt: startAt || null
  871    });
  872
  873    if (!addr) throw 'No results';
  874
  875    // console.log("Parsed to: ", require('util').inspect(addr, {depth: 10, colors: true}));
  876
  877    return addr.addresses.map(map_addresses);
  878};
  879
  880function map_addresses(adr) {
  881    if (adr.type === 'group') {
  882        return new Group(adr.name, adr.addresses.map(map_addresses));
  883    }
  884    let comments;
  885    if (adr.parts.comments) {
  886        comments = adr.parts.comments.map(function (c) {
  887            return c.tokens.trim();
  888        }).join(' ').trim();
  889        // if (comments.length) {
  890        //     comments = '(' + comments + ')';
  891        // }
  892    }
  893    let l = adr.local;
  894    if (!adr.name && /:/.test(l)) l = '"' + l + '"';
  895    return new Address(adr.name, l + '@' + adr.domain, comments);
  896}
  897
  898exports.parseFrom = function (line) {
  899    return exports.parse(line, 'from');
  900};
  901
  902exports.parseSender = function (line) {
  903    return exports.parse(line, 'sender');
  904};
  905
  906exports.parseReplyTo = function (line) {
  907    return exports.parse(line, 'reply-to');
  908};
  909
  910class Group {
  911    constructor(display_name, addresses) {
  912        this.phrase = display_name;
  913        this.addresses = addresses;
  914    }
  915
  916    format() {
  917        return this.phrase + ":" + this.addresses.map(function (a) {
  918            return a.format();
  919        }).join(',');
  920    }
  921
  922    name() {
  923        let phrase = this.phrase;
  924
  925        if (!(phrase && phrase.length)) {
  926            phrase = this.comment;
  927        }
  928
  929        const name = _extract_name(phrase);
  930        return name;
  931    }
  932}
  933
  934class Address {
  935    constructor(phrase, address, comment) {
  936        this.phrase = phrase || '';
  937        this.address = address || '';
  938        this.comment = comment || '';
  939    }
  940
  941    host() {
  942        const match = /.*@(.*)$/.exec(this.address);
  943        if (!match) return null;
  944        return match[1];
  945    }
  946
  947    user() {
  948        const match = /^(.*)@/.exec(this.address);
  949        if (!match) return null;
  950        return match[1];
  951    }
  952
  953    format() {
  954        const phrase = this.phrase;
  955        const email = this.address;
  956        let comment = this.comment;
  957
  958        const addr = [];
  959        const atext = new RegExp('^[\\-\\w !#$%&\'*+/=?^`{|}~]+$');
  960
  961        if (phrase && phrase.length) {
  962            addr.push(atext.test(phrase.trim()) ? phrase : _quote_no_esc(phrase) ? phrase : '"' + phrase + '"');
  963
  964            if (email && email.length) {
  965                addr.push("<" + email + ">");
  966            }
  967        } else if (email && email.length) {
  968            addr.push(email);
  969        }
  970
  971        if (comment && /\S/.test(comment)) {
  972            comment = comment.replace(/^\s*\(?/, '(').replace(/\)?\s*$/, ')');
  973        }
  974
  975        if (comment && comment.length) {
  976            addr.push(comment);
  977        }
  978
  979        return addr.join(' ');
  980    }
  981
  982    name() {
  983        let phrase = this.phrase;
  984        const addr = this.address;
  985
  986        if (!(phrase && phrase.length)) {
  987            phrase = this.comment;
  988        }
  989
  990        let name = _extract_name(phrase);
  991
  992        // first.last@domain address
  993        if (name === '') {
  994            const match = /([^%.@_]+([._][^%.@_]+)+)[@%]/.exec(addr);
  995            if (match) {
  996                name = match[1].replace(/[._]+/g, ' ');
  997                name = _extract_name(name);
  998            }
  999        }
 1000
 1001        if (name === '' && /\/g=/i.test(addr)) {
 1002            // X400 style address
 1003            let match = /\/g=([^/]*)/i.exec(addr);
 1004            const f = match[1];
 1005            match = /\/s=([^/]*)/i.exec(addr);
 1006            const l = match[1];
 1007            name = _extract_name(f + " " + l);
 1008        }
 1009
 1010        return name;
 1011    }
 1012}
 1013
 1014exports.Address = Address;
 1015
 1016// This is because JS regexps have no equivalent of
 1017// zero-width negative look-behind assertion for: /(?<!\\)"/
 1018function _quote_no_esc(str) {
 1019    if (/^"/.test(str)) return true;
 1020    let match;
 1021    while (match = /^[\s\S]*?([\s\S])"/.exec(str)) {
 1022        if (match[1] !== '\\') {
 1023            return true;
 1024        }
 1025        str = str.substr(match[0].length);
 1026    }
 1027    return false;
 1028}
 1029
 1030exports.isAllLower = function (string) {
 1031    return string === string.toLowerCase();
 1032};
 1033
 1034exports.isAllUpper = function (string) {
 1035    return string === string.toUpperCase();
 1036};
 1037
 1038exports.nameCase = function (string) {
 1039
 1040    return string.toLowerCase().replace(/\b(\w+)/g, function (_, d1) {
 1041        // Set the case of the name to first char upper rest lower
 1042        return d1.charAt(0).toUpperCase() + d1.slice(1);
 1043    }).replace(/\bMc(\w)/gi, function (_, d1) {
 1044        // Scottish names such as 'McLeod'
 1045        return 'Mc' + d1.toUpperCase();
 1046    }).replace(/\bo'(\w)/gi, function (_, d1) {
 1047        // Irish names such as 'O'Malley, O'Reilly'
 1048        return 'O\'' + d1.toUpperCase();
 1049    }).replace(/\b(x*(ix)?v*(iv)?i*)\b/ig, function (_, d1) {
 1050        // Roman numerals, eg 'Level III Support'
 1051        return d1.toUpperCase();
 1052    });
 1053};
 1054
 1055// given a comment, attempt to extract a person's name
 1056function _extract_name(name) {
 1057    // Using encodings, too hard. See Mail::Message::Field::Full.
 1058    if (/=?.*?\?=/.test(name)) return '';
 1059
 1060    // trim whitespace
 1061    name = name.trim();
 1062    name = name.replace(/\s+/, ' ');
 1063
 1064    // Disregard numeric names (e.g. 123456.1234@compuserve.com)
 1065    if (/^[\d ]+$/.test(name)) return '';
 1066
 1067    name = name.replace(/^\((.*)\)$/, '$1') // remove outermost parenthesis
 1068    .replace(/^"(.*)"$/, '$1') // remove outer quotation marks
 1069    .replace(/\(.*?\)/g, '') // remove minimal embedded comments
 1070    .replace(/\\/g, '') // remove all escapes
 1071    .replace(/^"(.*)"$/, '$1') // remove internal quotation marks
 1072    .replace(/^([^\s]+) ?, ?(.*)$/, '$2 $1') // reverse "Last, First M." if applicable
 1073    .replace(/,.*/, '');
 1074
 1075    // Change casing only when the name contains only upper or only
 1076    // lower cased characters.
 1077    if (exports.isAllUpper(name) || exports.isAllLower(name)) {
 1078        // console.log("Changing case of: " + name);
 1079        name = exports.nameCase(name);
 1080        // console.log("Now: " + name);
 1081    }
 1082
 1083    // some cleanup
 1084    name = name.replace(/\[[^\]]*\]/g, '').replace(/(^[\s'"]+|[\s'"]+$)/g, '').replace(/\s{2,}/g, ' ');
 1085
 1086    return name;
 1087}
 1088
 1089},{"email-addresses":34}],3:[function(require,module,exports){
 1090"use strict";
 1091
 1092Object.defineProperty(exports, "__esModule", {
 1093  value: true
 1094});
 1095/**
 1096 * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}.
 1097 * @author Artem S Vybornov <vybornov@gmail.com>
 1098 * @license MIT
 1099 */
 1100var AES_asm = exports.AES_asm = function () {
 1101  "use strict";
 1102
 1103  /**
 1104   * Galois Field stuff init flag
 1105   */
 1106
 1107  var ginit_done = false;
 1108
 1109  /**
 1110   * Galois Field exponentiation and logarithm tables for 3 (the generator)
 1111   */
 1112  var gexp3, glog3;
 1113
 1114  /**
 1115   * Init Galois Field tables
 1116   */
 1117  function ginit() {
 1118    gexp3 = [], glog3 = [];
 1119
 1120    var a = 1,
 1121        c,
 1122        d;
 1123    for (c = 0; c < 255; c++) {
 1124      gexp3[c] = a;
 1125
 1126      // Multiply by three
 1127      d = a & 0x80, a <<= 1, a &= 255;
 1128      if (d === 0x80) a ^= 0x1b;
 1129      a ^= gexp3[c];
 1130
 1131      // Set the log table value
 1132      glog3[gexp3[c]] = c;
 1133    }
 1134    gexp3[255] = gexp3[0];
 1135    glog3[0] = 0;
 1136
 1137    ginit_done = true;
 1138  }
 1139
 1140  /**
 1141   * Galois Field multiplication
 1142   * @param {number} a
 1143   * @param {number} b
 1144   * @return {number}
 1145   */
 1146  function gmul(a, b) {
 1147    var c = gexp3[(glog3[a] + glog3[b]) % 255];
 1148    if (a === 0 || b === 0) c = 0;
 1149    return c;
 1150  }
 1151
 1152  /**
 1153   * Galois Field reciprocal
 1154   * @param {number} a
 1155   * @return {number}
 1156   */
 1157  function ginv(a) {
 1158    var i = gexp3[255 - glog3[a]];
 1159    if (a === 0) i = 0;
 1160    return i;
 1161  }
 1162
 1163  /**
 1164   * AES stuff init flag
 1165   */
 1166  var aes_init_done = false;
 1167
 1168  /**
 1169   * Encryption, Decryption, S-Box and KeyTransform tables
 1170   *
 1171   * @type {number[]}
 1172   */
 1173  var aes_sbox;
 1174
 1175  /**
 1176   * @type {number[]}
 1177   */
 1178  var aes_sinv;
 1179
 1180  /**
 1181   * @type {number[][]}
 1182   */
 1183  var aes_enc;
 1184
 1185  /**
 1186   * @type {number[][]}
 1187   */
 1188  var aes_dec;
 1189
 1190  /**
 1191   * Init AES tables
 1192   */
 1193  function aes_init() {
 1194    if (!ginit_done) ginit();
 1195
 1196    // Calculates AES S-Box value
 1197    function _s(a) {
 1198      var c, s, x;
 1199      s = x = ginv(a);
 1200      for (c = 0; c < 4; c++) {
 1201        s = (s << 1 | s >>> 7) & 255;
 1202        x ^= s;
 1203      }
 1204      x ^= 99;
 1205      return x;
 1206    }
 1207
 1208    // Tables
 1209    aes_sbox = [], aes_sinv = [], aes_enc = [[], [], [], []], aes_dec = [[], [], [], []];
 1210
 1211    for (var i = 0; i < 256; i++) {
 1212      var s = _s(i);
 1213
 1214      // S-Box and its inverse
 1215      aes_sbox[i] = s;
 1216      aes_sinv[s] = i;
 1217
 1218      // Ecryption and Decryption tables
 1219      aes_enc[0][i] = gmul(2, s) << 24 | s << 16 | s << 8 | gmul(3, s);
 1220      aes_dec[0][s] = gmul(14, i) << 24 | gmul(9, i) << 16 | gmul(13, i) << 8 | gmul(11, i);
 1221      // Rotate tables
 1222      for (var t = 1; t < 4; t++) {
 1223        aes_enc[t][i] = aes_enc[t - 1][i] >>> 8 | aes_enc[t - 1][i] << 24;
 1224        aes_dec[t][s] = aes_dec[t - 1][s] >>> 8 | aes_dec[t - 1][s] << 24;
 1225      }
 1226    }
 1227
 1228    aes_init_done = true;
 1229  }
 1230
 1231  /**
 1232   * Asm.js module constructor.
 1233   *
 1234   * <p>
 1235   * Heap buffer layout by offset:
 1236   * <pre>
 1237   * 0x0000   encryption key schedule
 1238   * 0x0400   decryption key schedule
 1239   * 0x0800   sbox
 1240   * 0x0c00   inv sbox
 1241   * 0x1000   encryption tables
 1242   * 0x2000   decryption tables
 1243   * 0x3000   reserved (future GCM multiplication lookup table)
 1244   * 0x4000   data
 1245   * </pre>
 1246   * Don't touch anything before <code>0x400</code>.
 1247   * </p>
 1248   *
 1249   * @alias AES_asm
 1250   * @class
 1251   * @param foreign - <i>ignored</i>
 1252   * @param buffer - heap buffer to link with
 1253   */
 1254  var wrapper = function wrapper(foreign, buffer) {
 1255    // Init AES stuff for the first time
 1256    if (!aes_init_done) aes_init();
 1257
 1258    // Fill up AES tables
 1259    var heap = new Uint32Array(buffer);
 1260    heap.set(aes_sbox, 0x0800 >> 2);
 1261    heap.set(aes_sinv, 0x0c00 >> 2);
 1262    for (var i = 0; i < 4; i++) {
 1263      heap.set(aes_enc[i], 0x1000 + 0x400 * i >> 2);
 1264      heap.set(aes_dec[i], 0x2000 + 0x400 * i >> 2);
 1265    }
 1266
 1267    /**
 1268     * Calculate AES key schedules.
 1269     * @instance
 1270     * @memberof AES_asm
 1271     * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly)
 1272     * @param {number} k0 - key vector components
 1273     * @param {number} k1 - key vector components
 1274     * @param {number} k2 - key vector components
 1275     * @param {number} k3 - key vector components
 1276     * @param {number} k4 - key vector components
 1277     * @param {number} k5 - key vector components
 1278     * @param {number} k6 - key vector components
 1279     * @param {number} k7 - key vector components
 1280     */
 1281    function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) {
 1282      var ekeys = heap.subarray(0x000, 60),
 1283          dkeys = heap.subarray(0x100, 0x100 + 60);
 1284
 1285      // Encryption key schedule
 1286      ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]);
 1287      for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) {
 1288        var k = ekeys[i - 1];
 1289        if (i % ks === 0 || ks === 8 && i % ks === 4) {
 1290          k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255];
 1291        }
 1292        if (i % ks === 0) {
 1293          k = k << 8 ^ k >>> 24 ^ rcon << 24;
 1294          rcon = rcon << 1 ^ (rcon & 0x80 ? 0x1b : 0);
 1295        }
 1296        ekeys[i] = ekeys[i - ks] ^ k;
 1297      }
 1298
 1299      // Decryption key schedule
 1300      for (var j = 0; j < i; j += 4) {
 1301        for (var jj = 0; jj < 4; jj++) {
 1302          var k = ekeys[i - (4 + j) + (4 - jj) % 4];
 1303          if (j < 4 || j >= i - 4) {
 1304            dkeys[j + jj] = k;
 1305          } else {
 1306            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]];
 1307          }
 1308        }
 1309      }
 1310
 1311      // Set rounds number
 1312      asm.set_rounds(ks + 5);
 1313    }
 1314
 1315    // create library object with necessary properties
 1316    var stdlib = { Uint8Array: Uint8Array, Uint32Array: Uint32Array };
 1317
 1318    var asm = function (stdlib, foreign, buffer) {
 1319      "use asm";
 1320
 1321      var S0 = 0,
 1322          S1 = 0,
 1323          S2 = 0,
 1324          S3 = 0,
 1325          I0 = 0,
 1326          I1 = 0,
 1327          I2 = 0,
 1328          I3 = 0,
 1329          N0 = 0,
 1330          N1 = 0,
 1331          N2 = 0,
 1332          N3 = 0,
 1333          M0 = 0,
 1334          M1 = 0,
 1335          M2 = 0,
 1336          M3 = 0,
 1337          H0 = 0,
 1338          H1 = 0,
 1339          H2 = 0,
 1340          H3 = 0,
 1341          R = 0;
 1342
 1343      var HEAP = new stdlib.Uint32Array(buffer),
 1344          DATA = new stdlib.Uint8Array(buffer);
 1345
 1346      /**
 1347       * AES core
 1348       * @param {number} k - precomputed key schedule offset
 1349       * @param {number} s - precomputed sbox table offset
 1350       * @param {number} t - precomputed round table offset
 1351       * @param {number} r - number of inner rounds to perform
 1352       * @param {number} x0 - 128-bit input block vector
 1353       * @param {number} x1 - 128-bit input block vector
 1354       * @param {number} x2 - 128-bit input block vector
 1355       * @param {number} x3 - 128-bit input block vector
 1356       */
 1357      function _core(k, s, t, r, x0, x1, x2, x3) {
 1358        k = k | 0;
 1359        s = s | 0;
 1360        t = t | 0;
 1361        r = r | 0;
 1362        x0 = x0 | 0;
 1363        x1 = x1 | 0;
 1364        x2 = x2 | 0;
 1365        x3 = x3 | 0;
 1366
 1367        var t1 = 0,
 1368            t2 = 0,
 1369            t3 = 0,
 1370            y0 = 0,
 1371            y1 = 0,
 1372            y2 = 0,
 1373            y3 = 0,
 1374            i = 0;
 1375
 1376        t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00;
 1377
 1378        // round 0
 1379        x0 = x0 ^ HEAP[(k | 0) >> 2], x1 = x1 ^ HEAP[(k | 4) >> 2], x2 = x2 ^ HEAP[(k | 8) >> 2], x3 = x3 ^ HEAP[(k | 12) >> 2];
 1380
 1381        // round 1..r
 1382        for (i = 16; (i | 0) <= r << 4; i = i + 16 | 0) {
 1383          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];
 1384          x0 = y0, x1 = y1, x2 = y2, x3 = y3;
 1385        }
 1386
 1387        // final round
 1388        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];
 1389      }
 1390
 1391      /**
 1392       * ECB mode encryption
 1393       * @param {number} x0 - 128-bit input block vector
 1394       * @param {number} x1 - 128-bit input block vector
 1395       * @param {number} x2 - 128-bit input block vector
 1396       * @param {number} x3 - 128-bit input block vector
 1397       */
 1398      function _ecb_enc(x0, x1, x2, x3) {
 1399        x0 = x0 | 0;
 1400        x1 = x1 | 0;
 1401        x2 = x2 | 0;
 1402        x3 = x3 | 0;
 1403
 1404        _core(0x0000, 0x0800, 0x1000, R, x0, x1, x2, x3);
 1405      }
 1406
 1407      /**
 1408       * ECB mode decryption
 1409       * @param {number} x0 - 128-bit input block vector
 1410       * @param {number} x1 - 128-bit input block vector
 1411       * @param {number} x2 - 128-bit input block vector
 1412       * @param {number} x3 - 128-bit input block vector
 1413       */
 1414      function _ecb_dec(x0, x1, x2, x3) {
 1415        x0 = x0 | 0;
 1416        x1 = x1 | 0;
 1417        x2 = x2 | 0;
 1418        x3 = x3 | 0;
 1419
 1420        var t = 0;
 1421
 1422        _core(0x0400, 0x0c00, 0x2000, R, x0, x3, x2, x1);
 1423
 1424        t = S1, S1 = S3, S3 = t;
 1425      }
 1426
 1427      /**
 1428       * CBC mode encryption
 1429       * @param {number} x0 - 128-bit input block vector
 1430       * @param {number} x1 - 128-bit input block vector
 1431       * @param {number} x2 - 128-bit input block vector
 1432       * @param {number} x3 - 128-bit input block vector
 1433       */
 1434      function _cbc_enc(x0, x1, x2, x3) {
 1435        x0 = x0 | 0;
 1436        x1 = x1 | 0;
 1437        x2 = x2 | 0;
 1438        x3 = x3 | 0;
 1439
 1440        _core(0x0000, 0x0800, 0x1000, R, I0 ^ x0, I1 ^ x1, I2 ^ x2, I3 ^ x3);
 1441
 1442        I0 = S0, I1 = S1, I2 = S2, I3 = S3;
 1443      }
 1444
 1445      /**
 1446       * CBC mode decryption
 1447       * @param {number} x0 - 128-bit input block vector
 1448       * @param {number} x1 - 128-bit input block vector
 1449       * @param {number} x2 - 128-bit input block vector
 1450       * @param {number} x3 - 128-bit input block vector
 1451       */
 1452      function _cbc_dec(x0, x1, x2, x3) {
 1453        x0 = x0 | 0;
 1454        x1 = x1 | 0;
 1455        x2 = x2 | 0;
 1456        x3 = x3 | 0;
 1457
 1458        var t = 0;
 1459
 1460        _core(0x0400, 0x0c00, 0x2000, R, x0, x3, x2, x1);
 1461
 1462        t = S1, S1 = S3, S3 = t;
 1463
 1464        S0 = S0 ^ I0, S1 = S1 ^ I1, S2 = S2 ^ I2, S3 = S3 ^ I3;
 1465
 1466        I0 = x0, I1 = x1, I2 = x2, I3 = x3;
 1467      }
 1468
 1469      /**
 1470       * CFB mode encryption
 1471       * @param {number} x0 - 128-bit input block vector
 1472       * @param {number} x1 - 128-bit input block vector
 1473       * @param {number} x2 - 128-bit input block vector
 1474       * @param {number} x3 - 128-bit input block vector
 1475       */
 1476      function _cfb_enc(x0, x1, x2, x3) {
 1477        x0 = x0 | 0;
 1478        x1 = x1 | 0;
 1479        x2 = x2 | 0;
 1480        x3 = x3 | 0;
 1481
 1482        _core(0x0000, 0x0800, 0x1000, R, I0, I1, I2, I3);
 1483
 1484        I0 = S0 = S0 ^ x0, I1 = S1 = S1 ^ x1, I2 = S2 = S2 ^ x2, I3 = S3 = S3 ^ x3;
 1485      }
 1486
 1487      /**
 1488       * CFB mode decryption
 1489       * @param {number} x0 - 128-bit input block vector
 1490       * @param {number} x1 - 128-bit input block vector
 1491       * @param {number} x2 - 128-bit input block vector
 1492       * @param {number} x3 - 128-bit input block vector
 1493       */
 1494      function _cfb_dec(x0, x1, x2, x3) {
 1495        x0 = x0 | 0;
 1496        x1 = x1 | 0;
 1497        x2 = x2 | 0;
 1498        x3 = x3 | 0;
 1499
 1500        _core(0x0000, 0x0800, 0x1000, R, I0, I1, I2, I3);
 1501
 1502        S0 = S0 ^ x0, S1 = S1 ^ x1, S2 = S2 ^ x2, S3 = S3 ^ x3;
 1503
 1504        I0 = x0, I1 = x1, I2 = x2, I3 = x3;
 1505      }
 1506
 1507      /**
 1508       * OFB mode encryption / decryption
 1509       * @param {number} x0 - 128-bit input block vector
 1510       * @param {number} x1 - 128-bit input block vector
 1511       * @param {number} x2 - 128-bit input block vector
 1512       * @param {number} x3 - 128-bit input block vector
 1513       */
 1514      function _ofb(x0, x1, x2, x3) {
 1515        x0 = x0 | 0;
 1516        x1 = x1 | 0;
 1517        x2 = x2 | 0;
 1518        x3 = x3 | 0;
 1519
 1520        _core(0x0000, 0x0800, 0x1000, R, I0, I1, I2, I3);
 1521
 1522        I0 = S0, I1 = S1, I2 = S2, I3 = S3;
 1523
 1524        S0 = S0 ^ x0, S1 = S1 ^ x1, S2 = S2 ^ x2, S3 = S3 ^ x3;
 1525      }
 1526
 1527      /**
 1528       * CTR mode encryption / decryption
 1529       * @param {number} x0 - 128-bit input block vector
 1530       * @param {number} x1 - 128-bit input block vector
 1531       * @param {number} x2 - 128-bit input block vector
 1532       * @param {number} x3 - 128-bit input block vector
 1533       */
 1534      function _ctr(x0, x1, x2, x3) {
 1535        x0 = x0 | 0;
 1536        x1 = x1 | 0;
 1537        x2 = x2 | 0;
 1538        x3 = x3 | 0;
 1539
 1540        _core(0x0000, 0x0800, 0x1000, R, N0, N1, N2, N3);
 1541
 1542        N3 = ~M3 & N3 | M3 & N3 + 1;
 1543        N2 = ~M2 & N2 | M2 & N2 + ((N3 | 0) == 0);
 1544        N1 = ~M1 & N1 | M1 & N1 + ((N2 | 0) == 0);
 1545        N0 = ~M0 & N0 | M0 & N0 + ((N1 | 0) == 0);
 1546
 1547        S0 = S0 ^ x0;
 1548        S1 = S1 ^ x1;
 1549        S2 = S2 ^ x2;
 1550        S3 = S3 ^ x3;
 1551      }
 1552
 1553      /**
 1554       * GCM mode MAC calculation
 1555       * @param {number} x0 - 128-bit input block vector
 1556       * @param {number} x1 - 128-bit input block vector
 1557       * @param {number} x2 - 128-bit input block vector
 1558       * @param {number} x3 - 128-bit input block vector
 1559       */
 1560      function _gcm_mac(x0, x1, x2, x3) {
 1561        x0 = x0 | 0;
 1562        x1 = x1 | 0;
 1563        x2 = x2 | 0;
 1564        x3 = x3 | 0;
 1565
 1566        var y0 = 0,
 1567            y1 = 0,
 1568            y2 = 0,
 1569            y3 = 0,
 1570            z0 = 0,
 1571            z1 = 0,
 1572            z2 = 0,
 1573            z3 = 0,
 1574            i = 0,
 1575            c = 0;
 1576
 1577        x0 = x0 ^ I0, x1 = x1 ^ I1, x2 = x2 ^ I2, x3 = x3 ^ I3;
 1578
 1579        y0 = H0 | 0, y1 = H1 | 0, y2 = H2 | 0, y3 = H3 | 0;
 1580
 1581        for (; (i | 0) < 128; i = i + 1 | 0) {
 1582          if (y0 >>> 31) {
 1583            z0 = z0 ^ x0, z1 = z1 ^ x1, z2 = z2 ^ x2, z3 = z3 ^ x3;
 1584          }
 1585
 1586          y0 = y0 << 1 | y1 >>> 31, y1 = y1 << 1 | y2 >>> 31, y2 = y2 << 1 | y3 >>> 31, y3 = y3 << 1;
 1587
 1588          c = x3 & 1;
 1589
 1590          x3 = x3 >>> 1 | x2 << 31, x2 = x2 >>> 1 | x1 << 31, x1 = x1 >>> 1 | x0 << 31, x0 = x0 >>> 1;
 1591
 1592          if (c) x0 = x0 ^ 0xe1000000;
 1593        }
 1594
 1595        I0 = z0, I1 = z1, I2 = z2, I3 = z3;
 1596      }
 1597
 1598      /**
 1599       * Set the internal rounds number.
 1600       * @instance
 1601       * @memberof AES_asm
 1602       * @param {number} r - number if inner AES rounds
 1603       */
 1604      function set_rounds(r) {
 1605        r = r | 0;
 1606        R = r;
 1607      }
 1608
 1609      /**
 1610       * Populate the internal state of the module.
 1611       * @instance
 1612       * @memberof AES_asm
 1613       * @param {number} s0 - state vector
 1614       * @param {number} s1 - state vector
 1615       * @param {number} s2 - state vector
 1616       * @param {number} s3 - state vector
 1617       */
 1618      function set_state(s0, s1, s2, s3) {
 1619        s0 = s0 | 0;
 1620        s1 = s1 | 0;
 1621        s2 = s2 | 0;
 1622        s3 = s3 | 0;
 1623
 1624        S0 = s0, S1 = s1, S2 = s2, S3 = s3;
 1625      }
 1626
 1627      /**
 1628       * Populate the internal iv of the module.
 1629       * @instance
 1630       * @memberof AES_asm
 1631       * @param {number} i0 - iv vector
 1632       * @param {number} i1 - iv vector
 1633       * @param {number} i2 - iv vector
 1634       * @param {number} i3 - iv vector
 1635       */
 1636      function set_iv(i0, i1, i2, i3) {
 1637        i0 = i0 | 0;
 1638        i1 = i1 | 0;
 1639        i2 = i2 | 0;
 1640        i3 = i3 | 0;
 1641
 1642        I0 = i0, I1 = i1, I2 = i2, I3 = i3;
 1643      }
 1644
 1645      /**
 1646       * Set nonce for CTR-family modes.
 1647       * @instance
 1648       * @memberof AES_asm
 1649       * @param {number} n0 - nonce vector
 1650       * @param {number} n1 - nonce vector
 1651       * @param {number} n2 - nonce vector
 1652       * @param {number} n3 - nonce vector
 1653       */
 1654      function set_nonce(n0, n1, n2, n3) {
 1655        n0 = n0 | 0;
 1656        n1 = n1 | 0;
 1657        n2 = n2 | 0;
 1658        n3 = n3 | 0;
 1659
 1660        N0 = n0, N1 = n1, N2 = n2, N3 = n3;
 1661      }
 1662
 1663      /**
 1664       * Set counter mask for CTR-family modes.
 1665       * @instance
 1666       * @memberof AES_asm
 1667       * @param {number} m0 - counter mask vector
 1668       * @param {number} m1 - counter mask vector
 1669       * @param {number} m2 - counter mask vector
 1670       * @param {number} m3 - counter mask vector
 1671       */
 1672      function set_mask(m0, m1, m2, m3) {
 1673        m0 = m0 | 0;
 1674        m1 = m1 | 0;
 1675        m2 = m2 | 0;
 1676        m3 = m3 | 0;
 1677
 1678        M0 = m0, M1 = m1, M2 = m2, M3 = m3;
 1679      }
 1680
 1681      /**
 1682       * Set counter for CTR-family modes.
 1683       * @instance
 1684       * @memberof AES_asm
 1685       * @param {number} c0 - counter vector
 1686       * @param {number} c1 - counter vector
 1687       * @param {number} c2 - counter vector
 1688       * @param {number} c3 - counter vector
 1689       */
 1690      function set_counter(c0, c1, c2, c3) {
 1691        c0 = c0 | 0;
 1692        c1 = c1 | 0;
 1693        c2 = c2 | 0;
 1694        c3 = c3 | 0;
 1695
 1696        N3 = ~M3 & N3 | M3 & c3, N2 = ~M2 & N2 | M2 & c2, N1 = ~M1 & N1 | M1 & c1, N0 = ~M0 & N0 | M0 & c0;
 1697      }
 1698
 1699      /**
 1700       * Store the internal state vector into the heap.
 1701       * @instance
 1702       * @memberof AES_asm
 1703       * @param {number} pos - offset where to put the data
 1704       * @return {number} The number of bytes have been written into the heap, always 16.
 1705       */
 1706      function get_state(pos) {
 1707        pos = pos | 0;
 1708
 1709        if (pos & 15) return -1;
 1710
 1711        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;
 1712
 1713        return 16;
 1714      }
 1715
 1716      /**
 1717       * Store the internal iv vector into the heap.
 1718       * @instance
 1719       * @memberof AES_asm
 1720       * @param {number} pos - offset where to put the data
 1721       * @return {number} The number of bytes have been written into the heap, always 16.
 1722       */
 1723      function get_iv(pos) {
 1724        pos = pos | 0;
 1725
 1726        if (pos & 15) return -1;
 1727
 1728        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;
 1729
 1730        return 16;
 1731      }
 1732
 1733      /**
 1734       * GCM initialization.
 1735       * @instance
 1736       * @memberof AES_asm
 1737       */
 1738      function gcm_init() {
 1739        _ecb_enc(0, 0, 0, 0);
 1740        H0 = S0, H1 = S1, H2 = S2, H3 = S3;
 1741      }
 1742
 1743      /**
 1744       * Perform ciphering operation on the supplied data.
 1745       * @instance
 1746       * @memberof AES_asm
 1747       * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)
 1748       * @param {number} pos - offset of the data being processed
 1749       * @param {number} len - length of the data being processed
 1750       * @return {number} Actual amount of data have been processed.
 1751       */
 1752      function cipher(mode, pos, len) {
 1753        mode = mode | 0;
 1754        pos = pos | 0;
 1755        len = len | 0;
 1756
 1757        var ret = 0;
 1758
 1759        if (pos & 15) return -1;
 1760
 1761        while ((len | 0) >= 16) {
 1762          _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]);
 1763
 1764          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;
 1765
 1766          ret = ret + 16 | 0, pos = pos + 16 | 0, len = len - 16 | 0;
 1767        }
 1768
 1769        return ret | 0;
 1770      }
 1771
 1772      /**
 1773       * Calculates MAC of the supplied data.
 1774       * @instance
 1775       * @memberof AES_asm
 1776       * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)
 1777       * @param {number} pos - offset of the data being processed
 1778       * @param {number} len - length of the data being processed
 1779       * @return {number} Actual amount of data have been processed.
 1780       */
 1781      function mac(mode, pos, len) {
 1782        mode = mode | 0;
 1783        pos = pos | 0;
 1784        len = len | 0;
 1785
 1786        var ret = 0;
 1787
 1788        if (pos & 15) return -1;
 1789
 1790        while ((len | 0) >= 16) {
 1791          _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]);
 1792
 1793          ret = ret + 16 | 0, pos = pos + 16 | 0, len = len - 16 | 0;
 1794        }
 1795
 1796        return ret | 0;
 1797      }
 1798
 1799      /**
 1800       * AES cipher modes table (virual methods)
 1801       */
 1802      var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr];
 1803
 1804      /**
 1805       * AES MAC modes table (virual methods)
 1806       */
 1807      var _mac_modes = [_cbc_enc, _gcm_mac];
 1808
 1809      /**
 1810       * Asm.js module exports
 1811       */
 1812      return {
 1813        set_rounds: set_rounds,
 1814        set_state: set_state,
 1815        set_iv: set_iv,
 1816        set_nonce: set_nonce,
 1817        set_mask: set_mask,
 1818        set_counter: set_counter,
 1819        get_state: get_state,
 1820        get_iv: get_iv,
 1821        gcm_init: gcm_init,
 1822        cipher: cipher,
 1823        mac: mac
 1824      };
 1825    }(stdlib, foreign, buffer);
 1826
 1827    asm.set_key = set_key;
 1828
 1829    return asm;
 1830  };
 1831
 1832  /**
 1833   * AES enciphering mode constants
 1834   * @enum {number}
 1835   * @const
 1836   */
 1837  wrapper.ENC = {
 1838    ECB: 0,
 1839    CBC: 2,
 1840    CFB: 4,
 1841    OFB: 6,
 1842    CTR: 7
 1843  },
 1844
 1845  /**
 1846   * AES deciphering mode constants
 1847   * @enum {number}
 1848   * @const
 1849   */
 1850  wrapper.DEC = {
 1851    ECB: 1,
 1852    CBC: 3,
 1853    CFB: 5,
 1854    OFB: 6,
 1855    CTR: 7
 1856  },
 1857
 1858  /**
 1859   * AES MAC mode constants
 1860   * @enum {number}
 1861   * @const
 1862   */
 1863  wrapper.MAC = {
 1864    CBC: 0,
 1865    GCM: 1
 1866  };
 1867
 1868  /**
 1869   * Heap data offset
 1870   * @type {number}
 1871   * @const
 1872   */
 1873  wrapper.HEAP_DATA = 0x4000;
 1874
 1875  return wrapper;
 1876}();
 1877
 1878},{}],4:[function(require,module,exports){
 1879'use strict';
 1880
 1881Object.defineProperty(exports, "__esModule", {
 1882    value: true
 1883});
 1884exports.AES = undefined;
 1885
 1886var _aes = require('./aes.asm');
 1887
 1888var _utils = require('../other/utils');
 1889
 1890var _errors = require('../other/errors');
 1891
 1892var heap_pool = [];
 1893var asm_pool = [];
 1894var AES = /** @class */function () {
 1895    function AES(key, iv, padding, mode) {
 1896        if (padding === void 0) {
 1897            padding = true;
 1898        }
 1899        this.pos = 0;
 1900        this.len = 0;
 1901        this.mode = mode;
 1902        // The AES object state
 1903        this.pos = 0;
 1904        this.len = 0;
 1905        this.key = key;
 1906        this.iv = iv;
 1907        this.padding = padding;
 1908        // The AES "worker"
 1909        this.acquire_asm();
 1910    }
 1911    AES.prototype.acquire_asm = function () {
 1912        if (this.heap === undefined && this.asm === undefined) {
 1913            this.heap = heap_pool.pop() || (0, _utils._heap_init)().subarray(_aes.AES_asm.HEAP_DATA);
 1914            this.asm = asm_pool.pop() || (0, _aes.AES_asm)(null, this.heap.buffer);
 1915            this.reset(this.key, this.iv);
 1916        }
 1917    };
 1918    AES.prototype.release_asm = function () {
 1919        heap_pool.push(this.heap);
 1920        ;
 1921        asm_pool.push(this.asm);
 1922        this.heap = undefined;
 1923        this.asm = undefined;
 1924    };
 1925    AES.prototype.reset = function (key, iv) {
 1926        // Key
 1927        var keylen = key.length;
 1928        if (keylen !== 16 && keylen !== 24 && keylen !== 32) throw new _errors.IllegalArgumentError('illegal key size');
 1929        var keyview = new DataView(key.buffer, key.byteOffset, key.byteLength);
 1930        this.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);
 1931        // IV
 1932        if (iv !== undefined) {
 1933            if (iv.length !== 16) throw new _errors.IllegalArgumentError('illegal iv size');
 1934            var ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);
 1935            this.asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12));
 1936        } else {
 1937            this.asm.set_iv(0, 0, 0, 0);
 1938        }
 1939    };
 1940    AES.prototype.AES_Encrypt_process = function (data) {
 1941        if (!(0, _utils.is_bytes)(data)) throw new TypeError("data isn't of expected type");
 1942        this.acquire_asm();
 1943        var asm = this.asm;
 1944        var heap = this.heap;
 1945        var amode = _aes.AES_asm.ENC[this.mode];
 1946        var hpos = _aes.AES_asm.HEAP_DATA;
 1947        var pos = this.pos;
 1948        var len = this.len;
 1949        var dpos = 0;
 1950        var dlen = data.length || 0;
 1951        var rpos = 0;
 1952        var rlen = len + dlen & -16;
 1953        var wlen = 0;
 1954        var result = new Uint8Array(rlen);
 1955        while (dlen > 0) {
 1956            wlen = (0, _utils._heap_write)(heap, pos + len, data, dpos, dlen);
 1957            len += wlen;
 1958            dpos += wlen;
 1959            dlen -= wlen;
 1960            wlen = asm.cipher(amode, hpos + pos, len);
 1961            if (wlen) result.set(heap.subarray(pos, pos + wlen), rpos);
 1962            rpos += wlen;
 1963            if (wlen < len) {
 1964                pos += wlen;
 1965                len -= wlen;
 1966            } else {
 1967                pos = 0;
 1968                len = 0;
 1969            }
 1970        }
 1971        this.pos = pos;
 1972        this.len = len;
 1973        return result;
 1974    };
 1975    AES.prototype.AES_Encrypt_finish = function () {
 1976        this.acquire_asm();
 1977        var asm = this.asm;
 1978        var heap = this.heap;
 1979        var amode = _aes.AES_asm.ENC[this.mode];
 1980        var hpos = _aes.AES_asm.HEAP_DATA;
 1981        var pos = this.pos;
 1982        var len = this.len;
 1983        var plen = 16 - len % 16;
 1984        var rlen = len;
 1985        if (this.hasOwnProperty('padding')) {
 1986            if (this.padding) {
 1987                for (var p = 0; p < plen; ++p) {
 1988                    heap[pos + len + p] = plen;
 1989                }
 1990                len += plen;
 1991                rlen = len;
 1992            } else if (len % 16) {
 1993                throw new _errors.IllegalArgumentError('data length must be a multiple of the block size');
 1994            }
 1995        } else {
 1996            len += plen;
 1997        }
 1998        var result = new Uint8Array(rlen);
 1999        if (len) asm.cipher(amode, hpos + pos, len);
 2000        if (rlen) result.set(heap.subarray(pos, pos + rlen));
 2001        this.pos = 0;
 2002        this.len = 0;
 2003        this.release_asm();
 2004        return result;
 2005    };
 2006    AES.prototype.AES_Decrypt_process = function (data) {
 2007        if (!(0, _utils.is_bytes)(data)) throw new TypeError("data isn't of expected type");
 2008        this.acquire_asm();
 2009        var asm = this.asm;
 2010        var heap = this.heap;
 2011        var amode = _aes.AES_asm.DEC[this.mode];
 2012        var hpos = _aes.AES_asm.HEAP_DATA;
 2013        var pos = this.pos;
 2014        var len = this.len;
 2015        var dpos = 0;
 2016        var dlen = data.length || 0;
 2017        var rpos = 0;
 2018        var rlen = len + dlen & -16;
 2019        var plen = 0;
 2020        var wlen = 0;
 2021        if (this.padding) {
 2022            plen = len + dlen - rlen || 16;
 2023            rlen -= plen;
 2024        }
 2025        var result = new Uint8Array(rlen);
 2026        while (dlen > 0) {
 2027            wlen = (0, _utils._heap_write)(heap, pos + len, data, dpos, dlen);
 2028            len += wlen;
 2029            dpos += wlen;
 2030            dlen -= wlen;
 2031            wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0));
 2032            if (wlen) result.set(heap.subarray(pos, pos + wlen), rpos);
 2033            rpos += wlen;
 2034            if (wlen < len) {
 2035                pos += wlen;
 2036                len -= wlen;
 2037            } else {
 2038                pos = 0;
 2039                len = 0;
 2040            }
 2041        }
 2042        this.pos = pos;
 2043        this.len = len;
 2044        return result;
 2045    };
 2046    AES.prototype.AES_Decrypt_finish = function () {
 2047        this.acquire_asm();
 2048        var asm = this.asm;
 2049        var heap = this.heap;
 2050        var amode = _aes.AES_asm.DEC[this.mode];
 2051        var hpos = _aes.AES_asm.HEAP_DATA;
 2052        var pos = this.pos;
 2053        var len = this.len;
 2054        var rlen = len;
 2055        if (len > 0) {
 2056            if (len % 16) {
 2057                if (this.hasOwnProperty('padding')) {
 2058                    throw new _errors.IllegalArgumentError('data length must be a multiple of the block size');
 2059                } else {
 2060                    len += 16 - len % 16;
 2061                }
 2062            }
 2063            asm.cipher(amode, hpos + pos, len);
 2064            if (this.hasOwnProperty('padding') && this.padding) {
 2065                var pad = heap[pos + rlen - 1];
 2066                if (pad < 1 || pad > 16 || pad > rlen) throw new _errors.SecurityError('bad padding');
 2067                var pcheck = 0;
 2068                for (var i = pad; i > 1; i--) pcheck |= pad ^ heap[pos + rlen - i];
 2069                if (pcheck) throw new _errors.SecurityError('bad padding');
 2070                rlen -= pad;
 2071            }
 2072        }
 2073        var result = new Uint8Array(rlen);
 2074        if (rlen > 0) {
 2075            result.set(heap.subarray(pos, pos + rlen));
 2076        }
 2077        this.pos = 0;
 2078        this.len = 0;
 2079        this.release_asm();
 2080        return result;
 2081    };
 2082    return AES;
 2083}();
 2084exports.AES = AES;
 2085
 2086},{"../other/errors":15,"../other/utils":16,"./aes.asm":3}],5:[function(require,module,exports){
 2087'use strict';
 2088
 2089Object.defineProperty(exports, "__esModule", {
 2090    value: true
 2091});
 2092exports.AES_CBC = undefined;
 2093
 2094var _aes = require('./aes');
 2095
 2096var _utils = require('../other/utils');
 2097
 2098var __extends = undefined && undefined.__extends || function () {
 2099    var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
 2100        d.__proto__ = b;
 2101    } || function (d, b) {
 2102        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
 2103    };
 2104    return function (d, b) {
 2105        extendStatics(d, b);
 2106        function __() {
 2107            this.constructor = d;
 2108        }
 2109        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
 2110    };
 2111}();
 2112
 2113var AES_CBC = /** @class */function (_super) {
 2114    __extends(AES_CBC, _super);
 2115    function AES_CBC(key, iv, padding) {
 2116        if (padding === void 0) {
 2117            padding = true;
 2118        }
 2119        return _super.call(this, key, iv, padding, 'CBC') || this;
 2120    }
 2121    AES_CBC.encrypt = function (data, key, padding, iv) {
 2122        if (padding === void 0) {
 2123            padding = true;
 2124        }
 2125        return new AES_CBC(key, iv, padding).encrypt(data);
 2126    };
 2127    AES_CBC.decrypt = function (data, key, padding, iv) {
 2128        if (padding === void 0) {
 2129            padding = true;
 2130        }
 2131        return new AES_CBC(key, iv, padding).decrypt(data);
 2132    };
 2133    AES_CBC.prototype.encrypt = function (data) {
 2134        var r1 = this.AES_Encrypt_process(data);
 2135        var r2 = this.AES_Encrypt_finish();
 2136        return (0, _utils.joinBytes)(r1, r2);
 2137    };
 2138    AES_CBC.prototype.decrypt = function (data) {
 2139        var r1 = this.AES_Decrypt_process(data);
 2140        var r2 = this.AES_Decrypt_finish();
 2141        return (0, _utils.joinBytes)(r1, r2);
 2142    };
 2143    return AES_CBC;
 2144}(_aes.AES);
 2145exports.AES_CBC = AES_CBC;
 2146
 2147},{"../other/utils":16,"./aes":4}],6:[function(require,module,exports){
 2148'use strict';
 2149
 2150Object.defineProperty(exports, "__esModule", {
 2151    value: true
 2152});
 2153exports.AES_CFB = undefined;
 2154
 2155var _aes = require('./aes');
 2156
 2157var _utils = require('../other/utils');
 2158
 2159var __extends = undefined && undefined.__extends || function () {
 2160    var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
 2161        d.__proto__ = b;
 2162    } || function (d, b) {
 2163        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
 2164    };
 2165    return function (d, b) {
 2166        extendStatics(d, b);
 2167        function __() {
 2168            this.constructor = d;
 2169        }
 2170        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
 2171    };
 2172}();
 2173
 2174var AES_CFB = /** @class */function (_super) {
 2175    __extends(AES_CFB, _super);
 2176    function AES_CFB(key, iv) {
 2177        var _this = _super.call(this, key, iv, true, 'CFB') || this;
 2178        delete _this.padding;
 2179        return _this;
 2180    }
 2181    AES_CFB.encrypt = function (data, key, iv) {
 2182        return new AES_CFB(key, iv).encrypt(data);
 2183    };
 2184    AES_CFB.decrypt = function (data, key, iv) {
 2185        return new AES_CFB(key, iv).decrypt(data);
 2186    };
 2187    AES_CFB.prototype.encrypt = function (data) {
 2188        var r1 = this.AES_Encrypt_process(data);
 2189        var r2 = this.AES_Encrypt_finish();
 2190        return (0, _utils.joinBytes)(r1, r2);
 2191    };
 2192    AES_CFB.prototype.decrypt = function (data) {
 2193        var r1 = this.AES_Decrypt_process(data);
 2194        var r2 = this.AES_Decrypt_finish();
 2195        return (0, _utils.joinBytes)(r1, r2);
 2196    };
 2197    return AES_CFB;
 2198}(_aes.AES);
 2199exports.AES_CFB = AES_CFB;
 2200
 2201},{"../other/utils":16,"./aes":4}],7:[function(require,module,exports){
 2202'use strict';
 2203
 2204Object.defineProperty(exports, "__esModule", {
 2205    value: true
 2206});
 2207exports.AES_CTR = undefined;
 2208
 2209var _aes = require('./aes');
 2210
 2211var _errors = require('../other/errors');
 2212
 2213var _utils = require('../other/utils');
 2214
 2215var __extends = undefined && undefined.__extends || function () {
 2216    var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
 2217        d.__proto__ = b;
 2218    } || function (d, b) {
 2219        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
 2220    };
 2221    return function (d, b) {
 2222        extendStatics(d, b);
 2223        function __() {
 2224            this.constructor = d;
 2225        }
 2226        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
 2227    };
 2228}();
 2229
 2230var AES_CTR = /** @class */function (_super) {
 2231    __extends(AES_CTR, _super);
 2232    function AES_CTR(key, nonce) {
 2233        var _this = _super.call(this, key, undefined, false, 'CTR') || this;
 2234        delete _this.padding;
 2235        _this.AES_CTR_set_options(nonce);
 2236        return _this;
 2237    }
 2238    AES_CTR.encrypt = function (data, key, nonce) {
 2239        return new AES_CTR(key, nonce).encrypt(data);
 2240    };
 2241    AES_CTR.decrypt = function (data, key, nonce) {
 2242        return new AES_CTR(key, nonce).encrypt(data);
 2243    };
 2244    AES_CTR.prototype.encrypt = function (data) {
 2245        var r1 = this.AES_Encrypt_process(data);
 2246        var r2 = this.AES_Encrypt_finish();
 2247        return (0, _utils.joinBytes)(r1, r2);
 2248    };
 2249    AES_CTR.prototype.decrypt = function (data) {
 2250        var r1 = this.AES_Encrypt_process(data);
 2251        var r2 = this.AES_Encrypt_finish();
 2252        return (0, _utils.joinBytes)(r1, r2);
 2253    };
 2254    AES_CTR.prototype.AES_CTR_set_options = function (nonce, counter, size) {
 2255        if (size !== undefined) {
 2256            if (size < 8 || size > 48) throw new _errors.IllegalArgumentError('illegal counter size');
 2257            var mask = Math.pow(2, size) - 1;
 2258            this.asm.set_mask(0, 0, mask / 0x100000000 | 0, mask | 0);
 2259        } else {
 2260            size = 48;
 2261            this.asm.set_mask(0, 0, 0xffff, 0xffffffff);
 2262        }
 2263        if (nonce !== undefined) {
 2264            var len = nonce.length;
 2265            if (!len || len > 16) throw new _errors.IllegalArgumentError('illegal nonce size');
 2266            var view = new DataView(new ArrayBuffer(16));
 2267            new Uint8Array(view.buffer).set(nonce);
 2268            this.asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12));
 2269        } else {
 2270            throw new Error('nonce is required');
 2271        }
 2272        if (counter !== undefined) {
 2273            if (counter < 0 || counter >= Math.pow(2, size)) throw new _errors.IllegalArgumentError('illegal counter value');
 2274            this.asm.set_counter(0, 0, counter / 0x100000000 | 0, counter | 0);
 2275        }
 2276    };
 2277    return AES_CTR;
 2278}(_aes.AES);
 2279exports.AES_CTR = AES_CTR;
 2280
 2281},{"../other/errors":15,"../other/utils":16,"./aes":4}],8:[function(require,module,exports){
 2282'use strict';
 2283
 2284Object.defineProperty(exports, "__esModule", {
 2285    value: true
 2286});
 2287exports.AES_ECB = undefined;
 2288
 2289var _aes = require('./aes');
 2290
 2291var _utils = require('../other/utils');
 2292
 2293var __extends = undefined && undefined.__extends || function () {
 2294    var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
 2295        d.__proto__ = b;
 2296    } || function (d, b) {
 2297        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
 2298    };
 2299    return function (d, b) {
 2300        extendStatics(d, b);
 2301        function __() {
 2302            this.constructor = d;
 2303        }
 2304        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
 2305    };
 2306}();
 2307
 2308var AES_ECB = /** @class */function (_super) {
 2309    __extends(AES_ECB, _super);
 2310    function AES_ECB(key, padding) {
 2311        if (padding === void 0) {
 2312            padding = false;
 2313        }
 2314        return _super.call(this, key, undefined, padding, 'ECB') || this;
 2315    }
 2316    AES_ECB.encrypt = function (data, key, padding) {
 2317        if (padding === void 0) {
 2318            padding = false;
 2319        }
 2320        return new AES_ECB(key, padding).encrypt(data);
 2321    };
 2322    AES_ECB.decrypt = function (data, key, padding) {
 2323        if (padding === void 0) {
 2324            padding = false;
 2325        }
 2326        return new AES_ECB(key, padding).decrypt(data);
 2327    };
 2328    AES_ECB.prototype.encrypt = function (data) {
 2329        var r1 = this.AES_Encrypt_process(data);
 2330        var r2 = this.AES_Encrypt_finish();
 2331        return (0, _utils.joinBytes)(r1, r2);
 2332    };
 2333    AES_ECB.prototype.decrypt = function (data) {
 2334        var r1 = this.AES_Decrypt_process(data);
 2335        var r2 = this.AES_Decrypt_finish();
 2336        return (0, _utils.joinBytes)(r1, r2);
 2337    };
 2338    return AES_ECB;
 2339}(_aes.AES);
 2340exports.AES_ECB = AES_ECB;
 2341
 2342},{"../other/utils":16,"./aes":4}],9:[function(require,module,exports){
 2343'use strict';
 2344
 2345Object.defineProperty(exports, "__esModule", {
 2346    value: true
 2347});
 2348exports.AES_GCM = undefined;
 2349
 2350var _errors = require('../other/errors');
 2351
 2352var _utils = require('../other/utils');
 2353
 2354var _aes = require('./aes');
 2355
 2356var _aes2 = require('./aes.asm');
 2357
 2358var __extends = undefined && undefined.__extends || function () {
 2359    var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
 2360        d.__proto__ = b;
 2361    } || function (d, b) {
 2362        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
 2363    };
 2364    return function (d, b) {
 2365        extendStatics(d, b);
 2366        function __() {
 2367            this.constructor = d;
 2368        }
 2369        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
 2370    };
 2371}();
 2372
 2373var _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5
 2374var AES_GCM = /** @class */function (_super) {
 2375    __extends(AES_GCM, _super);
 2376    function AES_GCM(key, nonce, adata, tagSize) {
 2377        if (tagSize === void 0) {
 2378            tagSize = 16;
 2379        }
 2380        var _this = _super.call(this, key, undefined, false, 'CTR') || this;
 2381        _this.tagSize = tagSize;
 2382        _this.gamma0 = 0;
 2383        _this.counter = 1;
 2384        // Init GCM
 2385        _this.asm.gcm_init();
 2386        // Tag size
 2387        if (_this.tagSize < 4 || _this.tagSize > 16) throw new _errors.IllegalArgumentError('illegal tagSize value');
 2388        // Nonce
 2389        var noncelen = nonce.length || 0;
 2390        var noncebuf = new Uint8Array(16);
 2391        if (noncelen !== 12) {
 2392            _this._gcm_mac_process(nonce);
 2393            _this.heap[0] = 0;
 2394            _this.heap[1] = 0;
 2395            _this.heap[2] = 0;
 2396            _this.heap[3] = 0;
 2397            _this.heap[4] = 0;
 2398            _this.heap[5] = 0;
 2399            _this.heap[6] = 0;
 2400            _this.heap[7] = 0;
 2401            _this.heap[8] = 0;
 2402            _this.heap[9] = 0;
 2403            _this.heap[10] = 0;
 2404            _this.heap[11] = noncelen >>> 29;
 2405            _this.heap[12] = noncelen >>> 21 & 255;
 2406            _this.heap[13] = noncelen >>> 13 & 255;
 2407            _this.heap[14] = noncelen >>> 5 & 255;
 2408            _this.heap[15] = noncelen << 3 & 255;
 2409            _this.asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA, 16);
 2410            _this.asm.get_iv(_aes2.AES_asm.HEAP_DATA);
 2411            _this.asm.set_iv(0, 0, 0, 0);
 2412            noncebuf.set(_this.heap.subarray(0, 16));
 2413        } else {
 2414            noncebuf.set(nonce);
 2415            noncebuf[15] = 1;
 2416        }
 2417        var nonceview = new DataView(noncebuf.buffer);
 2418        _this.gamma0 = nonceview.getUint32(12);
 2419        _this.asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0);
 2420        _this.asm.set_mask(0, 0, 0, 0xffffffff);
 2421        // Associated data
 2422        if (adata !== undefined) {
 2423            if (adata.length > _AES_GCM_data_maxLength) throw new _errors.IllegalArgumentError('illegal adata length');
 2424            if (adata.length) {
 2425                _this.adata = adata;
 2426                _this._gcm_mac_process(adata);
 2427            } else {
 2428                _this.adata = undefined;
 2429            }
 2430        } else {
 2431            _this.adata = undefined;
 2432        }
 2433        // Counter
 2434        if (_this.counter < 1 || _this.counter > 0xffffffff) throw new RangeError('counter must be a positive 32-bit integer');
 2435        _this.asm.set_counter(0, 0, 0, _this.gamma0 + _this.counter | 0);
 2436        return _this;
 2437    }
 2438    AES_GCM.encrypt = function (cleartext, key, nonce, adata, tagsize) {
 2439        return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext);
 2440    };
 2441    AES_GCM.decrypt = function (ciphertext, key, nonce, adata, tagsize) {
 2442        return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext);
 2443    };
 2444    AES_GCM.prototype.encrypt = function (data) {
 2445        return this.AES_GCM_encrypt(data);
 2446    };
 2447    AES_GCM.prototype.decrypt = function (data) {
 2448        return this.AES_GCM_decrypt(data);
 2449    };
 2450    AES_GCM.prototype.AES_GCM_Encrypt_process = function (data) {
 2451        var dpos = 0;
 2452        var dlen = data.length || 0;
 2453        var asm = this.asm;
 2454        var heap = this.heap;
 2455        var counter = this.counter;
 2456        var pos = this.pos;
 2457        var len = this.len;
 2458        var rpos = 0;
 2459        var rlen = len + dlen & -16;
 2460        var wlen = 0;
 2461        if ((counter - 1 << 4) + len + dlen > _AES_GCM_data_maxLength) throw new RangeError('counter overflow');
 2462        var result = new Uint8Array(rlen);
 2463        while (dlen > 0) {
 2464            wlen = (0, _utils._heap_write)(heap, pos + len, data, dpos, dlen);
 2465            len += wlen;
 2466            dpos += wlen;
 2467            dlen -= wlen;
 2468            wlen = asm.cipher(_aes2.AES_asm.ENC.CTR, _aes2.AES_asm.HEAP_DATA + pos, len);
 2469            wlen = asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA + pos, wlen);
 2470            if (wlen) result.set(heap.subarray(pos, pos + wlen), rpos);
 2471            counter += wlen >>> 4;
 2472            rpos += wlen;
 2473            if (wlen < len) {
 2474                pos += wlen;
 2475                len -= wlen;
 2476            } else {
 2477                pos = 0;
 2478                len = 0;
 2479            }
 2480        }
 2481        this.counter = counter;
 2482        this.pos = pos;
 2483        this.len = len;
 2484        return result;
 2485    };
 2486    AES_GCM.prototype.AES_GCM_Encrypt_finish = function () {
 2487        var asm = this.asm;
 2488        var heap = this.heap;
 2489        var counter = this.counter;
 2490        var tagSize = this.tagSize;
 2491        var adata = this.adata;
 2492        var pos = this.pos;
 2493        var len = this.len;
 2494        var result = new Uint8Array(len + tagSize);
 2495        asm.cipher(_aes2.AES_asm.ENC.CTR, _aes2.AES_asm.HEAP_DATA + pos, len + 15 & -16);
 2496        if (len) result.set(heap.subarray(pos, pos + len));
 2497        var i = len;
 2498        for (; i & 15; i++) heap[pos + i] = 0;
 2499        asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA + pos, i);
 2500        var alen = adata !== undefined ? adata.length : 0;
 2501        var clen = (counter - 1 << 4) + len;
 2502        heap[0] = 0;
 2503        heap[1] = 0;
 2504        heap[2] = 0;
 2505        heap[3] = alen >>> 29;
 2506        heap[4] = alen >>> 21;
 2507        heap[5] = alen >>> 13 & 255;
 2508        heap[6] = alen >>> 5 & 255;
 2509        heap[7] = alen << 3 & 255;
 2510        heap[8] = heap[9] = heap[10] = 0;
 2511        heap[11] = clen >>> 29;
 2512        heap[12] = clen >>> 21 & 255;
 2513        heap[13] = clen >>> 13 & 255;
 2514        heap[14] = clen >>> 5 & 255;
 2515        heap[15] = clen << 3 & 255;
 2516        asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA, 16);
 2517        asm.get_iv(_aes2.AES_asm.HEAP_DATA);
 2518        asm.set_counter(0, 0, 0, this.gamma0);
 2519        asm.cipher(_aes2.AES_asm.ENC.CTR, _aes2.AES_asm.HEAP_DATA, 16);
 2520        result.set(heap.subarray(0, tagSize), len);
 2521        this.counter = 1;
 2522        this.pos = 0;
 2523        this.len = 0;
 2524        return result;
 2525    };
 2526    AES_GCM.prototype.AES_GCM_Decrypt_process = function (data) {
 2527        var dpos = 0;
 2528        var dlen = data.length || 0;
 2529        var asm = this.asm;
 2530        var heap = this.heap;
 2531        var counter = this.counter;
 2532        var tagSize = this.tagSize;
 2533        var pos = this.pos;
 2534        var len = this.len;
 2535        var rpos = 0;
 2536        var rlen = len + dlen > tagSize ? len + dlen - tagSize & -16 : 0;
 2537        var tlen = len + dlen - rlen;
 2538        var wlen = 0;
 2539        if ((counter - 1 << 4) + len + dlen > _AES_GCM_data_maxLength) throw new RangeError('counter overflow');
 2540        var result = new Uint8Array(rlen);
 2541        while (dlen > tlen) {
 2542            wlen = (0, _utils._heap_write)(heap, pos + len, data, dpos, dlen - tlen);
 2543            len += wlen;
 2544            dpos += wlen;
 2545            dlen -= wlen;
 2546            wlen = asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA + pos, wlen);
 2547            wlen = asm.cipher(_aes2.AES_asm.DEC.CTR, _aes2.AES_asm.HEAP_DATA + pos, wlen);
 2548            if (wlen) result.set(heap.subarray(pos, pos + wlen), rpos);
 2549            counter += wlen >>> 4;
 2550            rpos += wlen;
 2551            pos = 0;
 2552            len = 0;
 2553        }
 2554        if (dlen > 0) {
 2555            len += (0, _utils._heap_write)(heap, 0, data, dpos, dlen);
 2556        }
 2557        this.counter = counter;
 2558        this.pos = pos;
 2559        this.len = len;
 2560        return result;
 2561    };
 2562    AES_GCM.prototype.AES_GCM_Decrypt_finish = function () {
 2563        var asm = this.asm;
 2564        var heap = this.heap;
 2565        var tagSize = this.tagSize;
 2566        var adata = this.adata;
 2567        var counter = this.counter;
 2568        var pos = this.pos;
 2569        var len = this.len;
 2570        var rlen = len - tagSize;
 2571        if (len < tagSize) throw new _errors.IllegalStateError('authentication tag not found');
 2572        var result = new Uint8Array(rlen);
 2573        var atag = new Uint8Array(heap.subarray(pos + rlen, pos + len));
 2574        var i = rlen;
 2575        for (; i & 15; i++) heap[pos + i] = 0;
 2576        asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA + pos, i);
 2577        asm.cipher(_aes2.AES_asm.DEC.CTR, _aes2.AES_asm.HEAP_DATA + pos, i);
 2578        if (rlen) result.set(heap.subarray(pos, pos + rlen));
 2579        var alen = adata !== undefined ? adata.length : 0;
 2580        var clen = (counter - 1 << 4) + len - tagSize;
 2581        heap[0] = 0;
 2582        heap[1] = 0;
 2583        heap[2] = 0;
 2584        heap[3] = alen >>> 29;
 2585        heap[4] = alen >>> 21;
 2586        heap[5] = alen >>> 13 & 255;
 2587        heap[6] = alen >>> 5 & 255;
 2588        heap[7] = alen << 3 & 255;
 2589        heap[8] = heap[9] = heap[10] = 0;
 2590        heap[11] = clen >>> 29;
 2591        heap[12] = clen >>> 21 & 255;
 2592        heap[13] = clen >>> 13 & 255;
 2593        heap[14] = clen >>> 5 & 255;
 2594        heap[15] = clen << 3 & 255;
 2595        asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA, 16);
 2596        asm.get_iv(_aes2.AES_asm.HEAP_DATA);
 2597        asm.set_counter(0, 0, 0, this.gamma0);
 2598        asm.cipher(_aes2.AES_asm.ENC.CTR, _aes2.AES_asm.HEAP_DATA, 16);
 2599        var acheck = 0;
 2600        for (var i_1 = 0; i_1 < tagSize; ++i_1) acheck |= atag[i_1] ^ heap[i_1];
 2601        if (acheck) throw new _errors.SecurityError('data integrity check failed');
 2602        this.counter = 1;
 2603        this.pos = 0;
 2604        this.len = 0;
 2605        return result;
 2606    };
 2607    AES_GCM.prototype.AES_GCM_decrypt = function (data) {
 2608        var result1 = this.AES_GCM_Decrypt_process(data);
 2609        var result2 = this.AES_GCM_Decrypt_finish();
 2610        var result = new Uint8Array(result1.length + result2.length);
 2611        if (result1.length) result.set(result1);
 2612        if (result2.length) result.set(result2, result1.length);
 2613        return result;
 2614    };
 2615    AES_GCM.prototype.AES_GCM_encrypt = function (data) {
 2616        var result1 = this.AES_GCM_Encrypt_process(data);
 2617        var result2 = this.AES_GCM_Encrypt_finish();
 2618        var result = new Uint8Array(result1.length + result2.length);
 2619        if (result1.length) result.set(result1);
 2620        if (result2.length) result.set(result2, result1.length);
 2621        return result;
 2622    };
 2623    AES_GCM.prototype._gcm_mac_process = function (data) {
 2624        var heap = this.heap;
 2625        var asm = this.asm;
 2626        var dpos = 0;
 2627        var dlen = data.length || 0;
 2628        var wlen = 0;
 2629        while (dlen > 0) {
 2630            wlen = (0, _utils._heap_write)(heap, 0, data, dpos, dlen);
 2631            dpos += wlen;
 2632            dlen -= wlen;
 2633            while (wlen & 15) heap[wlen++] = 0;
 2634            asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA, wlen);
 2635        }
 2636    };
 2637    return AES_GCM;
 2638}(_aes.AES);
 2639exports.AES_GCM = AES_GCM;
 2640
 2641},{"../other/errors":15,"../other/utils":16,"./aes":4,"./aes.asm":3}],10:[function(require,module,exports){
 2642'use strict';
 2643
 2644Object.defineProperty(exports, "__esModule", {
 2645    value: true
 2646});
 2647exports.Hash = undefined;
 2648
 2649var _utils = require('../other/utils');
 2650
 2651var _errors = require('../other/errors');
 2652
 2653var Hash = /** @class */function () {
 2654    function Hash() {
 2655        this.pos = 0;
 2656        this.len = 0;
 2657        this.acquire_asm();
 2658    }
 2659    Hash.prototype.acquire_asm = function () {
 2660        if (this.heap === undefined && this.asm === undefined) {
 2661            this.heap = this.constructor.heap_pool.pop() || (0, _utils._heap_init)();
 2662            this.asm = this.constructor.asm_pool.pop() || this.constructor.asm_function({ Uint8Array: Uint8Array }, null, this.heap.buffer);
 2663            this.reset();
 2664        }
 2665    };
 2666    Hash.prototype.release_asm = function () {
 2667        this.constructor.heap_pool.push(this.heap);
 2668        ;
 2669        this.constructor.asm_pool.push(this.asm);
 2670        this.heap = undefined;
 2671        this.asm = undefined;
 2672    };
 2673    Hash.prototype.reset = function () {
 2674        this.acquire_asm();
 2675        this.result = null;
 2676        this.pos = 0;
 2677        this.len = 0;
 2678        this.asm.reset();
 2679        return this;
 2680    };
 2681    Hash.prototype.process = function (data) {
 2682        if (this.result !== null) throw new _errors.IllegalStateError('state must be reset before processing new data');
 2683        this.acquire_asm();
 2684        var asm = this.asm;
 2685        var heap = this.heap;
 2686        var hpos = this.pos;
 2687        var hlen = this.len;
 2688        var dpos = 0;
 2689        var dlen = data.length;
 2690        var wlen = 0;
 2691        while (dlen > 0) {
 2692            wlen = (0, _utils._heap_write)(heap, hpos + hlen, data, dpos, dlen);
 2693            hlen += wlen;
 2694            dpos += wlen;
 2695            dlen -= wlen;
 2696            wlen = asm.process(hpos, hlen);
 2697            hpos += wlen;
 2698            hlen -= wlen;
 2699            if (!hlen) hpos = 0;
 2700        }
 2701        this.pos = hpos;
 2702        this.len = hlen;
 2703        return this;
 2704    };
 2705    Hash.prototype.finish = function () {
 2706        if (this.result !== null) throw new _errors.IllegalStateError('state must be reset before processing new data');
 2707        this.acquire_asm();
 2708        this.asm.finish(this.pos, this.len, 0);
 2709        this.result = new Uint8Array(this.HASH_SIZE);
 2710        this.result.set(this.heap.subarray(0, this.HASH_SIZE));
 2711        this.pos = 0;
 2712        this.len = 0;
 2713        this.release_asm();
 2714        return this;
 2715    };
 2716    return Hash;
 2717}();
 2718exports.Hash = Hash;
 2719
 2720},{"../other/errors":15,"../other/utils":16}],11:[function(require,module,exports){
 2721"use strict";
 2722
 2723Object.defineProperty(exports, "__esModule", {
 2724    value: true
 2725});
 2726exports.sha1_asm = sha1_asm;
 2727function sha1_asm(stdlib, foreign, buffer) {
 2728    "use asm";
 2729
 2730    // SHA256 state
 2731
 2732    var H0 = 0,
 2733        H1 = 0,
 2734        H2 = 0,
 2735        H3 = 0,
 2736        H4 = 0,
 2737        TOTAL0 = 0,
 2738        TOTAL1 = 0;
 2739
 2740    // HMAC state
 2741    var I0 = 0,
 2742        I1 = 0,
 2743        I2 = 0,
 2744        I3 = 0,
 2745        I4 = 0,
 2746        O0 = 0,
 2747        O1 = 0,
 2748        O2 = 0,
 2749        O3 = 0,
 2750        O4 = 0;
 2751
 2752    // I/O buffer
 2753    var HEAP = new stdlib.Uint8Array(buffer);
 2754
 2755    function _core(w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15) {
 2756        w0 = w0 | 0;
 2757        w1 = w1 | 0;
 2758        w2 = w2 | 0;
 2759        w3 = w3 | 0;
 2760        w4 = w4 | 0;
 2761        w5 = w5 | 0;
 2762        w6 = w6 | 0;
 2763        w7 = w7 | 0;
 2764        w8 = w8 | 0;
 2765        w9 = w9 | 0;
 2766        w10 = w10 | 0;
 2767        w11 = w11 | 0;
 2768        w12 = w12 | 0;
 2769        w13 = w13 | 0;
 2770        w14 = w14 | 0;
 2771        w15 = w15 | 0;
 2772
 2773        var a = 0,
 2774            b = 0,
 2775            c = 0,
 2776            d = 0,
 2777            e = 0,
 2778            n = 0,
 2779            t = 0,
 2780            w16 = 0,
 2781            w17 = 0,
 2782            w18 = 0,
 2783            w19 = 0,
 2784            w20 = 0,
 2785            w21 = 0,
 2786            w22 = 0,
 2787            w23 = 0,
 2788            w24 = 0,
 2789            w25 = 0,
 2790            w26 = 0,
 2791            w27 = 0,
 2792            w28 = 0,
 2793            w29 = 0,
 2794            w30 = 0,
 2795            w31 = 0,
 2796            w32 = 0,
 2797            w33 = 0,
 2798            w34 = 0,
 2799            w35 = 0,
 2800            w36 = 0,
 2801            w37 = 0,
 2802            w38 = 0,
 2803            w39 = 0,
 2804            w40 = 0,
 2805            w41 = 0,
 2806            w42 = 0,
 2807            w43 = 0,
 2808            w44 = 0,
 2809            w45 = 0,
 2810            w46 = 0,
 2811            w47 = 0,
 2812            w48 = 0,
 2813            w49 = 0,
 2814            w50 = 0,
 2815            w51 = 0,
 2816            w52 = 0,
 2817            w53 = 0,
 2818            w54 = 0,
 2819            w55 = 0,
 2820            w56 = 0,
 2821            w57 = 0,
 2822            w58 = 0,
 2823            w59 = 0,
 2824            w60 = 0,
 2825            w61 = 0,
 2826            w62 = 0,
 2827            w63 = 0,
 2828            w64 = 0,
 2829            w65 = 0,
 2830            w66 = 0,
 2831            w67 = 0,
 2832            w68 = 0,
 2833            w69 = 0,
 2834            w70 = 0,
 2835            w71 = 0,
 2836            w72 = 0,
 2837            w73 = 0,
 2838            w74 = 0,
 2839            w75 = 0,
 2840            w76 = 0,
 2841            w77 = 0,
 2842            w78 = 0,
 2843            w79 = 0;
 2844
 2845        a = H0;
 2846        b = H1;
 2847        c = H2;
 2848        d = H3;
 2849        e = H4;
 2850
 2851        // 0
 2852        t = w0 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2853        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2854
 2855        // 1
 2856        t = w1 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2857        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2858
 2859        // 2
 2860        t = w2 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2861        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2862
 2863        // 3
 2864        t = w3 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2865        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2866
 2867        // 4
 2868        t = w4 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2869        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2870
 2871        // 5
 2872        t = w5 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2873        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2874
 2875        // 6
 2876        t = w6 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2877        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2878
 2879        // 7
 2880        t = w7 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2881        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2882
 2883        // 8
 2884        t = w8 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2885        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2886
 2887        // 9
 2888        t = w9 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2889        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2890
 2891        // 10
 2892        t = w10 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2893        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2894
 2895        // 11
 2896        t = w11 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2897        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2898
 2899        // 12
 2900        t = w12 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2901        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2902
 2903        // 13
 2904        t = w13 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2905        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2906
 2907        // 14
 2908        t = w14 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2909        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2910
 2911        // 15
 2912        t = w15 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2913        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2914
 2915        // 16
 2916        n = w13 ^ w8 ^ w2 ^ w0;
 2917        w16 = n << 1 | n >>> 31;
 2918        t = w16 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2919        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2920
 2921        // 17
 2922        n = w14 ^ w9 ^ w3 ^ w1;
 2923        w17 = n << 1 | n >>> 31;
 2924        t = w17 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2925        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2926
 2927        // 18
 2928        n = w15 ^ w10 ^ w4 ^ w2;
 2929        w18 = n << 1 | n >>> 31;
 2930        t = w18 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2931        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2932
 2933        // 19
 2934        n = w16 ^ w11 ^ w5 ^ w3;
 2935        w19 = n << 1 | n >>> 31;
 2936        t = w19 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
 2937        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2938
 2939        // 20
 2940        n = w17 ^ w12 ^ w6 ^ w4;
 2941        w20 = n << 1 | n >>> 31;
 2942        t = w20 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 2943        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2944
 2945        // 21
 2946        n = w18 ^ w13 ^ w7 ^ w5;
 2947        w21 = n << 1 | n >>> 31;
 2948        t = w21 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 2949        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2950
 2951        // 22
 2952        n = w19 ^ w14 ^ w8 ^ w6;
 2953        w22 = n << 1 | n >>> 31;
 2954        t = w22 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 2955        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2956
 2957        // 23
 2958        n = w20 ^ w15 ^ w9 ^ w7;
 2959        w23 = n << 1 | n >>> 31;
 2960        t = w23 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 2961        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2962
 2963        // 24
 2964        n = w21 ^ w16 ^ w10 ^ w8;
 2965        w24 = n << 1 | n >>> 31;
 2966        t = w24 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 2967        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2968
 2969        // 25
 2970        n = w22 ^ w17 ^ w11 ^ w9;
 2971        w25 = n << 1 | n >>> 31;
 2972        t = w25 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 2973        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2974
 2975        // 26
 2976        n = w23 ^ w18 ^ w12 ^ w10;
 2977        w26 = n << 1 | n >>> 31;
 2978        t = w26 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 2979        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2980
 2981        // 27
 2982        n = w24 ^ w19 ^ w13 ^ w11;
 2983        w27 = n << 1 | n >>> 31;
 2984        t = w27 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 2985        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2986
 2987        // 28
 2988        n = w25 ^ w20 ^ w14 ^ w12;
 2989        w28 = n << 1 | n >>> 31;
 2990        t = w28 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 2991        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2992
 2993        // 29
 2994        n = w26 ^ w21 ^ w15 ^ w13;
 2995        w29 = n << 1 | n >>> 31;
 2996        t = w29 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 2997        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 2998
 2999        // 30
 3000        n = w27 ^ w22 ^ w16 ^ w14;
 3001        w30 = n << 1 | n >>> 31;
 3002        t = w30 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 3003        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3004
 3005        // 31
 3006        n = w28 ^ w23 ^ w17 ^ w15;
 3007        w31 = n << 1 | n >>> 31;
 3008        t = w31 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 3009        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3010
 3011        // 32
 3012        n = w29 ^ w24 ^ w18 ^ w16;
 3013        w32 = n << 1 | n >>> 31;
 3014        t = w32 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 3015        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3016
 3017        // 33
 3018        n = w30 ^ w25 ^ w19 ^ w17;
 3019        w33 = n << 1 | n >>> 31;
 3020        t = w33 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 3021        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3022
 3023        // 34
 3024        n = w31 ^ w26 ^ w20 ^ w18;
 3025        w34 = n << 1 | n >>> 31;
 3026        t = w34 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 3027        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3028
 3029        // 35
 3030        n = w32 ^ w27 ^ w21 ^ w19;
 3031        w35 = n << 1 | n >>> 31;
 3032        t = w35 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 3033        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3034
 3035        // 36
 3036        n = w33 ^ w28 ^ w22 ^ w20;
 3037        w36 = n << 1 | n >>> 31;
 3038        t = w36 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 3039        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3040
 3041        // 37
 3042        n = w34 ^ w29 ^ w23 ^ w21;
 3043        w37 = n << 1 | n >>> 31;
 3044        t = w37 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 3045        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3046
 3047        // 38
 3048        n = w35 ^ w30 ^ w24 ^ w22;
 3049        w38 = n << 1 | n >>> 31;
 3050        t = w38 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 3051        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3052
 3053        // 39
 3054        n = w36 ^ w31 ^ w25 ^ w23;
 3055        w39 = n << 1 | n >>> 31;
 3056        t = w39 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
 3057        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3058
 3059        // 40
 3060        n = w37 ^ w32 ^ w26 ^ w24;
 3061        w40 = n << 1 | n >>> 31;
 3062        t = w40 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3063        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3064
 3065        // 41
 3066        n = w38 ^ w33 ^ w27 ^ w25;
 3067        w41 = n << 1 | n >>> 31;
 3068        t = w41 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3069        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3070
 3071        // 42
 3072        n = w39 ^ w34 ^ w28 ^ w26;
 3073        w42 = n << 1 | n >>> 31;
 3074        t = w42 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3075        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3076
 3077        // 43
 3078        n = w40 ^ w35 ^ w29 ^ w27;
 3079        w43 = n << 1 | n >>> 31;
 3080        t = w43 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3081        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3082
 3083        // 44
 3084        n = w41 ^ w36 ^ w30 ^ w28;
 3085        w44 = n << 1 | n >>> 31;
 3086        t = w44 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3087        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3088
 3089        // 45
 3090        n = w42 ^ w37 ^ w31 ^ w29;
 3091        w45 = n << 1 | n >>> 31;
 3092        t = w45 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3093        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3094
 3095        // 46
 3096        n = w43 ^ w38 ^ w32 ^ w30;
 3097        w46 = n << 1 | n >>> 31;
 3098        t = w46 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3099        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3100
 3101        // 47
 3102        n = w44 ^ w39 ^ w33 ^ w31;
 3103        w47 = n << 1 | n >>> 31;
 3104        t = w47 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3105        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3106
 3107        // 48
 3108        n = w45 ^ w40 ^ w34 ^ w32;
 3109        w48 = n << 1 | n >>> 31;
 3110        t = w48 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3111        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3112
 3113        // 49
 3114        n = w46 ^ w41 ^ w35 ^ w33;
 3115        w49 = n << 1 | n >>> 31;
 3116        t = w49 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3117        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3118
 3119        // 50
 3120        n = w47 ^ w42 ^ w36 ^ w34;
 3121        w50 = n << 1 | n >>> 31;
 3122        t = w50 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3123        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3124
 3125        // 51
 3126        n = w48 ^ w43 ^ w37 ^ w35;
 3127        w51 = n << 1 | n >>> 31;
 3128        t = w51 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3129        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3130
 3131        // 52
 3132        n = w49 ^ w44 ^ w38 ^ w36;
 3133        w52 = n << 1 | n >>> 31;
 3134        t = w52 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3135        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3136
 3137        // 53
 3138        n = w50 ^ w45 ^ w39 ^ w37;
 3139        w53 = n << 1 | n >>> 31;
 3140        t = w53 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3141        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3142
 3143        // 54
 3144        n = w51 ^ w46 ^ w40 ^ w38;
 3145        w54 = n << 1 | n >>> 31;
 3146        t = w54 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3147        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3148
 3149        // 55
 3150        n = w52 ^ w47 ^ w41 ^ w39;
 3151        w55 = n << 1 | n >>> 31;
 3152        t = w55 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3153        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3154
 3155        // 56
 3156        n = w53 ^ w48 ^ w42 ^ w40;
 3157        w56 = n << 1 | n >>> 31;
 3158        t = w56 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3159        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3160
 3161        // 57
 3162        n = w54 ^ w49 ^ w43 ^ w41;
 3163        w57 = n << 1 | n >>> 31;
 3164        t = w57 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3165        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3166
 3167        // 58
 3168        n = w55 ^ w50 ^ w44 ^ w42;
 3169        w58 = n << 1 | n >>> 31;
 3170        t = w58 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3171        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3172
 3173        // 59
 3174        n = w56 ^ w51 ^ w45 ^ w43;
 3175        w59 = n << 1 | n >>> 31;
 3176        t = w59 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
 3177        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3178
 3179        // 60
 3180        n = w57 ^ w52 ^ w46 ^ w44;
 3181        w60 = n << 1 | n >>> 31;
 3182        t = w60 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3183        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3184
 3185        // 61
 3186        n = w58 ^ w53 ^ w47 ^ w45;
 3187        w61 = n << 1 | n >>> 31;
 3188        t = w61 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3189        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3190
 3191        // 62
 3192        n = w59 ^ w54 ^ w48 ^ w46;
 3193        w62 = n << 1 | n >>> 31;
 3194        t = w62 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3195        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3196
 3197        // 63
 3198        n = w60 ^ w55 ^ w49 ^ w47;
 3199        w63 = n << 1 | n >>> 31;
 3200        t = w63 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3201        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3202
 3203        // 64
 3204        n = w61 ^ w56 ^ w50 ^ w48;
 3205        w64 = n << 1 | n >>> 31;
 3206        t = w64 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3207        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3208
 3209        // 65
 3210        n = w62 ^ w57 ^ w51 ^ w49;
 3211        w65 = n << 1 | n >>> 31;
 3212        t = w65 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3213        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3214
 3215        // 66
 3216        n = w63 ^ w58 ^ w52 ^ w50;
 3217        w66 = n << 1 | n >>> 31;
 3218        t = w66 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3219        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3220
 3221        // 67
 3222        n = w64 ^ w59 ^ w53 ^ w51;
 3223        w67 = n << 1 | n >>> 31;
 3224        t = w67 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3225        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3226
 3227        // 68
 3228        n = w65 ^ w60 ^ w54 ^ w52;
 3229        w68 = n << 1 | n >>> 31;
 3230        t = w68 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3231        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3232
 3233        // 69
 3234        n = w66 ^ w61 ^ w55 ^ w53;
 3235        w69 = n << 1 | n >>> 31;
 3236        t = w69 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3237        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3238
 3239        // 70
 3240        n = w67 ^ w62 ^ w56 ^ w54;
 3241        w70 = n << 1 | n >>> 31;
 3242        t = w70 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3243        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3244
 3245        // 71
 3246        n = w68 ^ w63 ^ w57 ^ w55;
 3247        w71 = n << 1 | n >>> 31;
 3248        t = w71 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3249        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3250
 3251        // 72
 3252        n = w69 ^ w64 ^ w58 ^ w56;
 3253        w72 = n << 1 | n >>> 31;
 3254        t = w72 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3255        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3256
 3257        // 73
 3258        n = w70 ^ w65 ^ w59 ^ w57;
 3259        w73 = n << 1 | n >>> 31;
 3260        t = w73 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3261        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3262
 3263        // 74
 3264        n = w71 ^ w66 ^ w60 ^ w58;
 3265        w74 = n << 1 | n >>> 31;
 3266        t = w74 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3267        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3268
 3269        // 75
 3270        n = w72 ^ w67 ^ w61 ^ w59;
 3271        w75 = n << 1 | n >>> 31;
 3272        t = w75 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3273        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3274
 3275        // 76
 3276        n = w73 ^ w68 ^ w62 ^ w60;
 3277        w76 = n << 1 | n >>> 31;
 3278        t = w76 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3279        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3280
 3281        // 77
 3282        n = w74 ^ w69 ^ w63 ^ w61;
 3283        w77 = n << 1 | n >>> 31;
 3284        t = w77 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3285        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3286
 3287        // 78
 3288        n = w75 ^ w70 ^ w64 ^ w62;
 3289        w78 = n << 1 | n >>> 31;
 3290        t = w78 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3291        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3292
 3293        // 79
 3294        n = w76 ^ w71 ^ w65 ^ w63;
 3295        w79 = n << 1 | n >>> 31;
 3296        t = w79 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
 3297        e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
 3298
 3299        H0 = H0 + a | 0;
 3300        H1 = H1 + b | 0;
 3301        H2 = H2 + c | 0;
 3302        H3 = H3 + d | 0;
 3303        H4 = H4 + e | 0;
 3304    }
 3305
 3306    function _core_heap(offset) {
 3307        offset = offset | 0;
 3308
 3309        _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]);
 3310    }
 3311
 3312    // offset — multiple of 32
 3313    function _state_to_heap(output) {
 3314        output = output | 0;
 3315
 3316        HEAP[output | 0] = H0 >>> 24;
 3317        HEAP[output | 1] = H0 >>> 16 & 255;
 3318        HEAP[output | 2] = H0 >>> 8 & 255;
 3319        HEAP[output | 3] = H0 & 255;
 3320        HEAP[output | 4] = H1 >>> 24;
 3321        HEAP[output | 5] = H1 >>> 16 & 255;
 3322        HEAP[output | 6] = H1 >>> 8 & 255;
 3323        HEAP[output | 7] = H1 & 255;
 3324        HEAP[output | 8] = H2 >>> 24;
 3325        HEAP[output | 9] = H2 >>> 16 & 255;
 3326        HEAP[output | 10] = H2 >>> 8 & 255;
 3327        HEAP[output | 11] = H2 & 255;
 3328        HEAP[output | 12] = H3 >>> 24;
 3329        HEAP[output | 13] = H3 >>> 16 & 255;
 3330        HEAP[output | 14] = H3 >>> 8 & 255;
 3331        HEAP[output | 15] = H3 & 255;
 3332        HEAP[output | 16] = H4 >>> 24;
 3333        HEAP[output | 17] = H4 >>> 16 & 255;
 3334        HEAP[output | 18] = H4 >>> 8 & 255;
 3335        HEAP[output | 19] = H4 & 255;
 3336    }
 3337
 3338    function reset() {
 3339        H0 = 0x67452301;
 3340        H1 = 0xefcdab89;
 3341        H2 = 0x98badcfe;
 3342        H3 = 0x10325476;
 3343        H4 = 0xc3d2e1f0;
 3344        TOTAL0 = TOTAL1 = 0;
 3345    }
 3346
 3347    function init(h0, h1, h2, h3, h4, total0, total1) {
 3348        h0 = h0 | 0;
 3349        h1 = h1 | 0;
 3350        h2 = h2 | 0;
 3351        h3 = h3 | 0;
 3352        h4 = h4 | 0;
 3353        total0 = total0 | 0;
 3354        total1 = total1 | 0;
 3355
 3356        H0 = h0;
 3357        H1 = h1;
 3358        H2 = h2;
 3359        H3 = h3;
 3360        H4 = h4;
 3361        TOTAL0 = total0;
 3362        TOTAL1 = total1;
 3363    }
 3364
 3365    // offset — multiple of 64
 3366    function process(offset, length) {
 3367        offset = offset | 0;
 3368        length = length | 0;
 3369
 3370        var hashed = 0;
 3371
 3372        if (offset & 63) return -1;
 3373
 3374        while ((length | 0) >= 64) {
 3375            _core_heap(offset);
 3376
 3377            offset = offset + 64 | 0;
 3378            length = length - 64 | 0;
 3379
 3380            hashed = hashed + 64 | 0;
 3381        }
 3382
 3383        TOTAL0 = TOTAL0 + hashed | 0;
 3384        if (TOTAL0 >>> 0 < hashed >>> 0) TOTAL1 = TOTAL1 + 1 | 0;
 3385
 3386        return hashed | 0;
 3387    }
 3388
 3389    // offset — multiple of 64
 3390    // output — multiple of 32
 3391    function finish(offset, length, output) {
 3392        offset = offset | 0;
 3393        length = length | 0;
 3394        output = output | 0;
 3395
 3396        var hashed = 0,
 3397            i = 0;
 3398
 3399        if (offset & 63) return -1;
 3400
 3401        if (~output) if (output & 31) return -1;
 3402
 3403        if ((length | 0) >= 64) {
 3404            hashed = process(offset, length) | 0;
 3405            if ((hashed | 0) == -1) return -1;
 3406
 3407            offset = offset + hashed | 0;
 3408            length = length - hashed | 0;
 3409        }
 3410
 3411        hashed = hashed + length | 0;
 3412        TOTAL0 = TOTAL0 + length | 0;
 3413        if (TOTAL0 >>> 0 < length >>> 0) TOTAL1 = TOTAL1 + 1 | 0;
 3414
 3415        HEAP[offset | length] = 0x80;
 3416
 3417        if ((length | 0) >= 56) {
 3418            for (i = length + 1 | 0; (i | 0) < 64; i = i + 1 | 0) HEAP[offset | i] = 0x00;
 3419            _core_heap(offset);
 3420
 3421            length = 0;
 3422
 3423            HEAP[offset | 0] = 0;
 3424        }
 3425
 3426        for (i = length + 1 | 0; (i | 0) < 59; i = i + 1 | 0) HEAP[offset | i] = 0;
 3427
 3428        HEAP[offset | 56] = TOTAL1 >>> 21 & 255;
 3429        HEAP[offset | 57] = TOTAL1 >>> 13 & 255;
 3430        HEAP[offset | 58] = TOTAL1 >>> 5 & 255;
 3431        HEAP[offset | 59] = TOTAL1 << 3 & 255 | TOTAL0 >>> 29;
 3432        HEAP[offset | 60] = TOTAL0 >>> 21 & 255;
 3433        HEAP[offset | 61] = TOTAL0 >>> 13 & 255;
 3434        HEAP[offset | 62] = TOTAL0 >>> 5 & 255;
 3435        HEAP[offset | 63] = TOTAL0 << 3 & 255;
 3436        _core_heap(offset);
 3437
 3438        if (~output) _state_to_heap(output);
 3439
 3440        return hashed | 0;
 3441    }
 3442
 3443    function hmac_reset() {
 3444        H0 = I0;
 3445        H1 = I1;
 3446        H2 = I2;
 3447        H3 = I3;
 3448        H4 = I4;
 3449        TOTAL0 = 64;
 3450        TOTAL1 = 0;
 3451    }
 3452
 3453    function _hmac_opad() {
 3454        H0 = O0;
 3455        H1 = O1;
 3456        H2 = O2;
 3457        H3 = O3;
 3458        H4 = O4;
 3459        TOTAL0 = 64;
 3460        TOTAL1 = 0;
 3461    }
 3462
 3463    function hmac_init(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15) {
 3464        p0 = p0 | 0;
 3465        p1 = p1 | 0;
 3466        p2 = p2 | 0;
 3467        p3 = p3 | 0;
 3468        p4 = p4 | 0;
 3469        p5 = p5 | 0;
 3470        p6 = p6 | 0;
 3471        p7 = p7 | 0;
 3472        p8 = p8 | 0;
 3473        p9 = p9 | 0;
 3474        p10 = p10 | 0;
 3475        p11 = p11 | 0;
 3476        p12 = p12 | 0;
 3477        p13 = p13 | 0;
 3478        p14 = p14 | 0;
 3479        p15 = p15 | 0;
 3480
 3481        // opad
 3482        reset();
 3483        _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);
 3484        O0 = H0;
 3485        O1 = H1;
 3486        O2 = H2;
 3487        O3 = H3;
 3488        O4 = H4;
 3489
 3490        // ipad
 3491        reset();
 3492        _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);
 3493        I0 = H0;
 3494        I1 = H1;
 3495        I2 = H2;
 3496        I3 = H3;
 3497        I4 = H4;
 3498
 3499        TOTAL0 = 64;
 3500        TOTAL1 = 0;
 3501    }
 3502
 3503    // offset — multiple of 64
 3504    // output — multiple of 32
 3505    function hmac_finish(offset, length, output) {
 3506        offset = offset | 0;
 3507        length = length | 0;
 3508        output = output | 0;
 3509
 3510        var t0 = 0,
 3511            t1 = 0,
 3512            t2 = 0,
 3513            t3 = 0,
 3514            t4 = 0,
 3515            hashed = 0;
 3516
 3517        if (offset & 63) return -1;
 3518
 3519        if (~output) if (output & 31) return -1;
 3520
 3521        hashed = finish(offset, length, -1) | 0;
 3522        t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
 3523
 3524        _hmac_opad();
 3525        _core(t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672);
 3526
 3527        if (~output) _state_to_heap(output);
 3528
 3529        return hashed | 0;
 3530    }
 3531
 3532    // salt is assumed to be already processed
 3533    // offset — multiple of 64
 3534    // output — multiple of 32
 3535    function pbkdf2_generate_block(offset, length, block, count, output) {
 3536        offset = offset | 0;
 3537        length = length | 0;
 3538        block = block | 0;
 3539        count = count | 0;
 3540        output = output | 0;
 3541
 3542        var h0 = 0,
 3543            h1 = 0,
 3544            h2 = 0,
 3545            h3 = 0,
 3546            h4 = 0,
 3547            t0 = 0,
 3548            t1 = 0,
 3549            t2 = 0,
 3550            t3 = 0,
 3551            t4 = 0;
 3552
 3553        if (offset & 63) return -1;
 3554
 3555        if (~output) if (output & 31) return -1;
 3556
 3557        // pad block number into heap
 3558        // FIXME probable OOB write
 3559        HEAP[offset + length | 0] = block >>> 24;
 3560        HEAP[offset + length + 1 | 0] = block >>> 16 & 255;
 3561        HEAP[offset + length + 2 | 0] = block >>> 8 & 255;
 3562        HEAP[offset + length + 3 | 0] = block & 255;
 3563
 3564        // finish first iteration
 3565        hmac_finish(offset, length + 4 | 0, -1) | 0;
 3566        h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4;
 3567        count = count - 1 | 0;
 3568
 3569        // perform the rest iterations
 3570        while ((count | 0) > 0) {
 3571            hmac_reset();
 3572            _core(t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672);
 3573            t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
 3574
 3575            _hmac_opad();
 3576            _core(t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672);
 3577            t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
 3578
 3579            h0 = h0 ^ H0;
 3580            h1 = h1 ^ H1;
 3581            h2 = h2 ^ H2;
 3582            h3 = h3 ^ H3;
 3583            h4 = h4 ^ H4;
 3584
 3585            count = count - 1 | 0;
 3586        }
 3587
 3588        H0 = h0;
 3589        H1 = h1;
 3590        H2 = h2;
 3591        H3 = h3;
 3592        H4 = h4;
 3593
 3594        if (~output) _state_to_heap(output);
 3595
 3596        return 0;
 3597    }
 3598
 3599    return {
 3600        // SHA1
 3601        reset: reset,
 3602        init: init,
 3603        process: process,
 3604        finish: finish,
 3605
 3606        // HMAC-SHA1
 3607        hmac_reset: hmac_reset,
 3608        hmac_init: hmac_init,
 3609        hmac_finish: hmac_finish,
 3610
 3611        // PBKDF2-HMAC-SHA1
 3612        pbkdf2_generate_block: pbkdf2_generate_block
 3613    };
 3614}
 3615
 3616},{}],12:[function(require,module,exports){
 3617'use strict';
 3618
 3619Object.defineProperty(exports, "__esModule", {
 3620    value: true
 3621});
 3622exports.Sha1 = exports._sha1_hash_size = exports._sha1_block_size = undefined;
 3623
 3624var _sha = require('./sha1.asm');
 3625
 3626var _hash = require('../hash');
 3627
 3628var __extends = undefined && undefined.__extends || function () {
 3629    var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
 3630        d.__proto__ = b;
 3631    } || function (d, b) {
 3632        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
 3633    };
 3634    return function (d, b) {
 3635        extendStatics(d, b);
 3636        function __() {
 3637            this.constructor = d;
 3638        }
 3639        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
 3640    };
 3641}();
 3642var _sha1_block_size = exports._sha1_block_size = 64;
 3643var _sha1_hash_size = exports._sha1_hash_size = 20;
 3644var Sha1 = /** @class */function (_super) {
 3645    __extends(Sha1, _super);
 3646    function Sha1() {
 3647        var _this = _super !== null && _super.apply(this, arguments) || this;
 3648        _this.NAME = 'sha1';
 3649        _this.BLOCK_SIZE = _sha1_block_size;
 3650        _this.HASH_SIZE = _sha1_hash_size;
 3651        return _this;
 3652    }
 3653    Sha1.bytes = function (data) {
 3654        return new Sha1().process(data).finish().result;
 3655    };
 3656    Sha1.NAME = 'sha1';
 3657    Sha1.heap_pool = [];
 3658    Sha1.asm_pool = [];
 3659    Sha1.asm_function = _sha.sha1_asm;
 3660    return Sha1;
 3661}(_hash.Hash);
 3662exports.Sha1 = Sha1;
 3663
 3664},{"../hash":10,"./sha1.asm":11}],13:[function(require,module,exports){
 3665"use strict";
 3666
 3667Object.defineProperty(exports, "__esModule", {
 3668    value: true
 3669});
 3670exports.sha256_asm = sha256_asm;
 3671function sha256_asm(stdlib, foreign, buffer) {
 3672    "use asm";
 3673
 3674    // SHA256 state
 3675
 3676    var H0 = 0,
 3677        H1 = 0,
 3678        H2 = 0,
 3679        H3 = 0,
 3680        H4 = 0,
 3681        H5 = 0,
 3682        H6 = 0,
 3683        H7 = 0,
 3684        TOTAL0 = 0,
 3685        TOTAL1 = 0;
 3686
 3687    // HMAC state
 3688    var I0 = 0,
 3689        I1 = 0,
 3690        I2 = 0,
 3691        I3 = 0,
 3692        I4 = 0,
 3693        I5 = 0,
 3694        I6 = 0,
 3695        I7 = 0,
 3696        O0 = 0,
 3697        O1 = 0,
 3698        O2 = 0,
 3699        O3 = 0,
 3700        O4 = 0,
 3701        O5 = 0,
 3702        O6 = 0,
 3703        O7 = 0;
 3704
 3705    // I/O buffer
 3706    var HEAP = new stdlib.Uint8Array(buffer);
 3707
 3708    function _core(w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15) {
 3709        w0 = w0 | 0;
 3710        w1 = w1 | 0;
 3711        w2 = w2 | 0;
 3712        w3 = w3 | 0;
 3713        w4 = w4 | 0;
 3714        w5 = w5 | 0;
 3715        w6 = w6 | 0;
 3716        w7 = w7 | 0;
 3717        w8 = w8 | 0;
 3718        w9 = w9 | 0;
 3719        w10 = w10 | 0;
 3720        w11 = w11 | 0;
 3721        w12 = w12 | 0;
 3722        w13 = w13 | 0;
 3723        w14 = w14 | 0;
 3724        w15 = w15 | 0;
 3725
 3726        var a = 0,
 3727            b = 0,
 3728            c = 0,
 3729            d = 0,
 3730            e = 0,
 3731            f = 0,
 3732            g = 0,
 3733            h = 0;
 3734
 3735        a = H0;
 3736        b = H1;
 3737        c = H2;
 3738        d = H3;
 3739        e = H4;
 3740        f = H5;
 3741        g = H6;
 3742        h = H7;
 3743
 3744        // 0
 3745        h = w0 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x428a2f98 | 0;
 3746        d = d + h | 0;
 3747        h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
 3748
 3749        // 1
 3750        g = w1 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x71374491 | 0;
 3751        c = c + g | 0;
 3752        g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
 3753
 3754        // 2
 3755        f = w2 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0xb5c0fbcf | 0;
 3756        b = b + f | 0;
 3757        f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
 3758
 3759        // 3
 3760        e = w3 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0xe9b5dba5 | 0;
 3761        a = a + e | 0;
 3762        e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
 3763
 3764        // 4
 3765        d = w4 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x3956c25b | 0;
 3766        h = h + d | 0;
 3767        d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
 3768
 3769        // 5
 3770        c = w5 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x59f111f1 | 0;
 3771        g = g + c | 0;
 3772        c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
 3773
 3774        // 6
 3775        b = w6 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x923f82a4 | 0;
 3776        f = f + b | 0;
 3777        b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
 3778
 3779        // 7
 3780        a = w7 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0xab1c5ed5 | 0;
 3781        e = e + a | 0;
 3782        a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
 3783
 3784        // 8
 3785        h = w8 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0xd807aa98 | 0;
 3786        d = d + h | 0;
 3787        h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
 3788
 3789        // 9
 3790        g = w9 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x12835b01 | 0;
 3791        c = c + g | 0;
 3792        g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
 3793
 3794        // 10
 3795        f = w10 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x243185be | 0;
 3796        b = b + f | 0;
 3797        f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
 3798
 3799        // 11
 3800        e = w11 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x550c7dc3 | 0;
 3801        a = a + e | 0;
 3802        e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
 3803
 3804        // 12
 3805        d = w12 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x72be5d74 | 0;
 3806        h = h + d | 0;
 3807        d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
 3808
 3809        // 13
 3810        c = w13 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x80deb1fe | 0;
 3811        g = g + c | 0;
 3812        c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
 3813
 3814        // 14
 3815        b = w14 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x9bdc06a7 | 0;
 3816        f = f + b | 0;
 3817        b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
 3818
 3819        // 15
 3820        a = w15 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0xc19bf174 | 0;
 3821        e = e + a | 0;
 3822        a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
 3823
 3824        // 16
 3825        w0 = (w1 >>> 7 ^ w1 >>> 18 ^ w1 >>> 3 ^ w1 << 25 ^ w1 << 14) + (w14 >>> 17 ^ w14 >>> 19 ^ w14 >>> 10 ^ w14 << 15 ^ w14 << 13) + w0 + w9 | 0;
 3826        h = w0 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0xe49b69c1 | 0;
 3827        d = d + h | 0;
 3828        h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
 3829
 3830        // 17
 3831        w1 = (w2 >>> 7 ^ w2 >>> 18 ^ w2 >>> 3 ^ w2 << 25 ^ w2 << 14) + (w15 >>> 17 ^ w15 >>> 19 ^ w15 >>> 10 ^ w15 << 15 ^ w15 << 13) + w1 + w10 | 0;
 3832        g = w1 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0xefbe4786 | 0;
 3833        c = c + g | 0;
 3834        g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
 3835
 3836        // 18
 3837        w2 = (w3 >>> 7 ^ w3 >>> 18 ^ w3 >>> 3 ^ w3 << 25 ^ w3 << 14) + (w0 >>> 17 ^ w0 >>> 19 ^ w0 >>> 10 ^ w0 << 15 ^ w0 << 13) + w2 + w11 | 0;
 3838        f = w2 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x0fc19dc6 | 0;
 3839        b = b + f | 0;
 3840        f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
 3841
 3842        // 19
 3843        w3 = (w4 >>> 7 ^ w4 >>> 18 ^ w4 >>> 3 ^ w4 << 25 ^ w4 << 14) + (w1 >>> 17 ^ w1 >>> 19 ^ w1 >>> 10 ^ w1 << 15 ^ w1 << 13) + w3 + w12 | 0;
 3844        e = w3 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x240ca1cc | 0;
 3845        a = a + e | 0;
 3846        e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
 3847
 3848        // 20
 3849        w4 = (w5 >>> 7 ^ w5 >>> 18 ^ w5 >>> 3 ^ w5 << 25 ^ w5 << 14) + (w2 >>> 17 ^ w2 >>> 19 ^ w2 >>> 10 ^ w2 << 15 ^ w2 << 13) + w4 + w13 | 0;
 3850        d = w4 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x2de92c6f | 0;
 3851        h = h + d | 0;
 3852        d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
 3853
 3854        // 21
 3855        w5 = (w6 >>> 7 ^ w6 >>> 18 ^ w6 >>> 3 ^ w6 << 25 ^ w6 << 14) + (w3 >>> 17 ^ w3 >>> 19 ^ w3 >>> 10 ^ w3 << 15 ^ w3 << 13) + w5 + w14 | 0;
 3856        c = w5 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x4a7484aa | 0;
 3857        g = g + c | 0;
 3858        c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
 3859
 3860        // 22
 3861        w6 = (w7 >>> 7 ^ w7 >>> 18 ^ w7 >>> 3 ^ w7 << 25 ^ w7 << 14) + (w4 >>> 17 ^ w4 >>> 19 ^ w4 >>> 10 ^ w4 << 15 ^ w4 << 13) + w6 + w15 | 0;
 3862        b = w6 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x5cb0a9dc | 0;
 3863        f = f + b | 0;
 3864        b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
 3865
 3866        // 23
 3867        w7 = (w8 >>> 7 ^ w8 >>> 18 ^ w8 >>> 3 ^ w8 << 25 ^ w8 << 14) + (w5 >>> 17 ^ w5 >>> 19 ^ w5 >>> 10 ^ w5 << 15 ^ w5 << 13) + w7 + w0 | 0;
 3868        a = w7 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x76f988da | 0;
 3869        e = e + a | 0;
 3870        a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
 3871
 3872        // 24
 3873        w8 = (w9 >>> 7 ^ w9 >>> 18 ^ w9 >>> 3 ^ w9 << 25 ^ w9 << 14) + (w6 >>> 17 ^ w6 >>> 19 ^ w6 >>> 10 ^ w6 << 15 ^ w6 << 13) + w8 + w1 | 0;
 3874        h = w8 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x983e5152 | 0;
 3875        d = d + h | 0;
 3876        h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
 3877
 3878        // 25
 3879        w9 = (w10 >>> 7 ^ w10 >>> 18 ^ w10 >>> 3 ^ w10 << 25 ^ w10 << 14) + (w7 >>> 17 ^ w7 >>> 19 ^ w7 >>> 10 ^ w7 << 15 ^ w7 << 13) + w9 + w2 | 0;
 3880        g = w9 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0xa831c66d | 0;
 3881        c = c + g | 0;
 3882        g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
 3883
 3884        // 26
 3885        w10 = (w11 >>> 7 ^ w11 >>> 18 ^ w11 >>> 3 ^ w11 << 25 ^ w11 << 14) + (w8 >>> 17 ^ w8 >>> 19 ^ w8 >>> 10 ^ w8 << 15 ^ w8 << 13) + w10 + w3 | 0;
 3886        f = w10 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0xb00327c8 | 0;
 3887        b = b + f | 0;
 3888        f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
 3889
 3890        // 27
 3891        w11 = (w12 >>> 7 ^ w12 >>> 18 ^ w12 >>> 3 ^ w12 << 25 ^ w12 << 14) + (w9 >>> 17 ^ w9 >>> 19 ^ w9 >>> 10 ^ w9 << 15 ^ w9 << 13) + w11 + w4 | 0;
 3892        e = w11 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0xbf597fc7 | 0;
 3893        a = a + e | 0;
 3894        e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
 3895
 3896        // 28
 3897        w12 = (w13 >>> 7 ^ w13 >>> 18 ^ w13 >>> 3 ^ w13 << 25 ^ w13 << 14) + (w10 >>> 17 ^ w10 >>> 19 ^ w10 >>> 10 ^ w10 << 15 ^ w10 << 13) + w12 + w5 | 0;
 3898        d = w12 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0xc6e00bf3 | 0;
 3899        h = h + d | 0;
 3900        d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
 3901
 3902        // 29
 3903        w13 = (w14 >>> 7 ^ w14 >>> 18 ^ w14 >>> 3 ^ w14 << 25 ^ w14 << 14) + (w11 >>> 17 ^ w11 >>> 19 ^ w11 >>> 10 ^ w11 << 15 ^ w11 << 13) + w13 + w6 | 0;
 3904        c = w13 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0xd5a79147 | 0;
 3905        g = g + c | 0;
 3906        c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
 3907
 3908        // 30
 3909        w14 = (w15 >>> 7 ^ w15 >>> 18 ^ w15 >>> 3 ^ w15 << 25 ^ w15 << 14) + (w12 >>> 17 ^ w12 >>> 19 ^ w12 >>> 10 ^ w12 << 15 ^ w12 << 13) + w14 + w7 | 0;
 3910        b = w14 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x06ca6351 | 0;
 3911        f = f + b | 0;
 3912        b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
 3913
 3914        // 31
 3915        w15 = (w0 >>> 7 ^ w0 >>> 18 ^ w0 >>> 3 ^ w0 << 25 ^ w0 << 14) + (w13 >>> 17 ^ w13 >>> 19 ^ w13 >>> 10 ^ w13 << 15 ^ w13 << 13) + w15 + w8 | 0;
 3916        a = w15 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x14292967 | 0;
 3917        e = e + a | 0;
 3918        a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
 3919
 3920        // 32
 3921        w0 = (w1 >>> 7 ^ w1 >>> 18 ^ w1 >>> 3 ^ w1 << 25 ^ w1 << 14) + (w14 >>> 17 ^ w14 >>> 19 ^ w14 >>> 10 ^ w14 << 15 ^ w14 << 13) + w0 + w9 | 0;
 3922        h = w0 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x27b70a85 | 0;
 3923        d = d + h | 0;
 3924        h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
 3925
 3926        // 33
 3927        w1 = (w2 >>> 7 ^ w2 >>> 18 ^ w2 >>> 3 ^ w2 << 25 ^ w2 << 14) + (w15 >>> 17 ^ w15 >>> 19 ^ w15 >>> 10 ^ w15 << 15 ^ w15 << 13) + w1 + w10 | 0;
 3928        g = w1 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x2e1b2138 | 0;
 3929        c = c + g | 0;
 3930        g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
 3931
 3932        // 34
 3933        w2 = (w3 >>> 7 ^ w3 >>> 18 ^ w3 >>> 3 ^ w3 << 25 ^ w3 << 14) + (w0 >>> 17 ^ w0 >>> 19 ^ w0 >>> 10 ^ w0 << 15 ^ w0 << 13) + w2 + w11 | 0;
 3934        f = w2 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x4d2c6dfc | 0;
 3935        b = b + f | 0;
 3936        f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
 3937
 3938        // 35
 3939        w3 = (w4 >>> 7 ^ w4 >>> 18 ^ w4 >>> 3 ^ w4 << 25 ^ w4 << 14) + (w1 >>> 17 ^ w1 >>> 19 ^ w1 >>> 10 ^ w1 << 15 ^ w1 << 13) + w3 + w12 | 0;
 3940        e = w3 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x53380d13 | 0;
 3941        a = a + e | 0;
 3942        e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
 3943
 3944        // 36
 3945        w4 = (w5 >>> 7 ^ w5 >>> 18 ^ w5 >>> 3 ^ w5 << 25 ^ w5 << 14) + (w2 >>> 17 ^ w2 >>> 19 ^ w2 >>> 10 ^ w2 << 15 ^ w2 << 13) + w4 + w13 | 0;
 3946        d = w4 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x650a7354 | 0;
 3947        h = h + d | 0;
 3948        d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
 3949
 3950        // 37
 3951        w5 = (w6 >>> 7 ^ w6 >>> 18 ^ w6 >>> 3 ^ w6 << 25 ^ w6 << 14) + (w3 >>> 17 ^ w3 >>> 19 ^ w3 >>> 10 ^ w3 << 15 ^ w3 << 13) + w5 + w14 | 0;
 3952        c = w5 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x766a0abb | 0;
 3953        g = g + c | 0;
 3954        c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
 3955
 3956        // 38
 3957        w6 = (w7 >>> 7 ^ w7 >>> 18 ^ w7 >>> 3 ^ w7 << 25 ^ w7 << 14) + (w4 >>> 17 ^ w4 >>> 19 ^ w4 >>> 10 ^ w4 << 15 ^ w4 << 13) + w6 + w15 | 0;
 3958        b = w6 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x81c2c92e | 0;
 3959        f = f + b | 0;
 3960        b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
 3961
 3962        // 39
 3963        w7 = (w8 >>> 7 ^ w8 >>> 18 ^ w8 >>> 3 ^ w8 << 25 ^ w8 << 14) + (w5 >>> 17 ^ w5 >>> 19 ^ w5 >>> 10 ^ w5 << 15 ^ w5 << 13) + w7 + w0 | 0;
 3964        a = w7 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x92722c85 | 0;
 3965        e = e + a | 0;
 3966        a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
 3967
 3968        // 40
 3969        w8 = (w9 >>> 7 ^ w9 >>> 18 ^ w9 >>> 3 ^ w9 << 25 ^ w9 << 14) + (w6 >>> 17 ^ w6 >>> 19 ^ w6 >>> 10 ^ w6 << 15 ^ w6 << 13) + w8 + w1 | 0;
 3970        h = w8 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0xa2bfe8a1 | 0;
 3971        d = d + h | 0;
 3972        h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
 3973
 3974        // 41
 3975        w9 = (w10 >>> 7 ^ w10 >>> 18 ^ w10 >>> 3 ^ w10 << 25 ^ w10 << 14) + (w7 >>> 17 ^ w7 >>> 19 ^ w7 >>> 10 ^ w7 << 15 ^ w7 << 13) + w9 + w2 | 0;
 3976        g = w9 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0xa81a664b | 0;
 3977        c = c + g | 0;
 3978        g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
 3979
 3980        // 42
 3981        w10 = (w11 >>> 7 ^ w11 >>> 18 ^ w11 >>> 3 ^ w11 << 25 ^ w11 << 14) + (w8 >>> 17 ^ w8 >>> 19 ^ w8 >>> 10 ^ w8 << 15 ^ w8 << 13) + w10 + w3 | 0;
 3982        f = w10 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0xc24b8b70 | 0;
 3983        b = b + f | 0;
 3984        f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
 3985
 3986        // 43
 3987        w11 = (w12 >>> 7 ^ w12 >>> 18 ^ w12 >>> 3 ^ w12 << 25 ^ w12 << 14) + (w9 >>> 17 ^ w9 >>> 19 ^ w9 >>> 10 ^ w9 << 15 ^ w9 << 13) + w11 + w4 | 0;
 3988        e = w11 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0xc76c51a3 | 0;
 3989        a = a + e | 0;
 3990        e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
 3991
 3992        // 44
 3993        w12 = (w13 >>> 7 ^ w13 >>> 18 ^ w13 >>> 3 ^ w13 << 25 ^ w13 << 14) + (w10 >>> 17 ^ w10 >>> 19 ^ w10 >>> 10 ^ w10 << 15 ^ w10 << 13) + w12 + w5 | 0;
 3994        d = w12 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0xd192e819 | 0;
 3995        h = h + d | 0;
 3996        d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
 3997
 3998        // 45
 3999        w13 = (w14 >>> 7 ^ w14 >>> 18 ^ w14 >>> 3 ^ w14 << 25 ^ w14 << 14) + (w11 >>> 17 ^ w11 >>> 19 ^ w11 >>> 10 ^ w11 << 15 ^ w11 << 13) + w13 + w6 | 0;
 4000        c = w13 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0xd6990624 | 0;
 4001        g = g + c | 0;
 4002        c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
 4003
 4004        // 46
 4005        w14 = (w15 >>> 7 ^ w15 >>> 18 ^ w15 >>> 3 ^ w15 << 25 ^ w15 << 14) + (w12 >>> 17 ^ w12 >>> 19 ^ w12 >>> 10 ^ w12 << 15 ^ w12 << 13) + w14 + w7 | 0;
 4006        b = w14 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0xf40e3585 | 0;
 4007        f = f + b | 0;
 4008        b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
 4009
 4010        // 47
 4011        w15 = (w0 >>> 7 ^ w0 >>> 18 ^ w0 >>> 3 ^ w0 << 25 ^ w0 << 14) + (w13 >>> 17 ^ w13 >>> 19 ^ w13 >>> 10 ^ w13 << 15 ^ w13 << 13) + w15 + w8 | 0;
 4012        a = w15 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x106aa070 | 0;
 4013        e = e + a | 0;
 4014        a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
 4015
 4016        // 48
 4017        w0 = (w1 >>> 7 ^ w1 >>> 18 ^ w1 >>> 3 ^ w1 << 25 ^ w1 << 14) + (w14 >>> 17 ^ w14 >>> 19 ^ w14 >>> 10 ^ w14 << 15 ^ w14 << 13) + w0 + w9 | 0;
 4018        h = w0 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x19a4c116 | 0;
 4019        d = d + h | 0;
 4020        h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
 4021
 4022        // 49
 4023        w1 = (w2 >>> 7 ^ w2 >>> 18 ^ w2 >>> 3 ^ w2 << 25 ^ w2 << 14) + (w15 >>> 17 ^ w15 >>> 19 ^ w15 >>> 10 ^ w15 << 15 ^ w15 << 13) + w1 + w10 | 0;
 4024        g = w1 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x1e376c08 | 0;
 4025        c = c + g | 0;
 4026        g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
 4027
 4028        // 50
 4029        w2 = (w3 >>> 7 ^ w3 >>> 18 ^ w3 >>> 3 ^ w3 << 25 ^ w3 << 14) + (w0 >>> 17 ^ w0 >>> 19 ^ w0 >>> 10 ^ w0 << 15 ^ w0 << 13) + w2 + w11 | 0;
 4030        f = w2 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x2748774c | 0;
 4031        b = b + f | 0;
 4032        f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
 4033
 4034        // 51
 4035        w3 = (w4 >>> 7 ^ w4 >>> 18 ^ w4 >>> 3 ^ w4 << 25 ^ w4 << 14) + (w1 >>> 17 ^ w1 >>> 19 ^ w1 >>> 10 ^ w1 << 15 ^ w1 << 13) + w3 + w12 | 0;
 4036        e = w3 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x34b0bcb5 | 0;
 4037        a = a + e | 0;
 4038        e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
 4039
 4040        // 52
 4041        w4 = (w5 >>> 7 ^ w5 >>> 18 ^ w5 >>> 3 ^ w5 << 25 ^ w5 << 14) + (w2 >>> 17 ^ w2 >>> 19 ^ w2 >>> 10 ^ w2 << 15 ^ w2 << 13) + w4 + w13 | 0;
 4042        d = w4 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x391c0cb3 | 0;
 4043        h = h + d | 0;
 4044        d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
 4045
 4046        // 53
 4047        w5 = (w6 >>> 7 ^ w6 >>> 18 ^ w6 >>> 3 ^ w6 << 25 ^ w6 << 14) + (w3 >>> 17 ^ w3 >>> 19 ^ w3 >>> 10 ^ w3 << 15 ^ w3 << 13) + w5 + w14 | 0;
 4048        c = w5 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x4ed8aa4a | 0;
 4049        g = g + c | 0;
 4050        c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
 4051
 4052        // 54
 4053        w6 = (w7 >>> 7 ^ w7 >>> 18 ^ w7 >>> 3 ^ w7 << 25 ^ w7 << 14) + (w4 >>> 17 ^ w4 >>> 19 ^ w4 >>> 10 ^ w4 << 15 ^ w4 << 13) + w6 + w15 | 0;
 4054        b = w6 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x5b9cca4f | 0;
 4055        f = f + b | 0;
 4056        b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
 4057
 4058        // 55
 4059        w7 = (w8 >>> 7 ^ w8 >>> 18 ^ w8 >>> 3 ^ w8 << 25 ^ w8 << 14) + (w5 >>> 17 ^ w5 >>> 19 ^ w5 >>> 10 ^ w5 << 15 ^ w5 << 13) + w7 + w0 | 0;
 4060        a = w7 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x682e6ff3 | 0;
 4061        e = e + a | 0;
 4062        a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
 4063
 4064        // 56
 4065        w8 = (w9 >>> 7 ^ w9 >>> 18 ^ w9 >>> 3 ^ w9 << 25 ^ w9 << 14) + (w6 >>> 17 ^ w6 >>> 19 ^ w6 >>> 10 ^ w6 << 15 ^ w6 << 13) + w8 + w1 | 0;
 4066        h = w8 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x748f82ee | 0;
 4067        d = d + h | 0;
 4068        h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
 4069
 4070        // 57
 4071        w9 = (w10 >>> 7 ^ w10 >>> 18 ^ w10 >>> 3 ^ w10 << 25 ^ w10 << 14) + (w7 >>> 17 ^ w7 >>> 19 ^ w7 >>> 10 ^ w7 << 15 ^ w7 << 13) + w9 + w2 | 0;
 4072        g = w9 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x78a5636f | 0;
 4073        c = c + g | 0;
 4074        g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
 4075
 4076        // 58
 4077        w10 = (w11 >>> 7 ^ w11 >>> 18 ^ w11 >>> 3 ^ w11 << 25 ^ w11 << 14) + (w8 >>> 17 ^ w8 >>> 19 ^ w8 >>> 10 ^ w8 << 15 ^ w8 << 13) + w10 + w3 | 0;
 4078        f = w10 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x84c87814 | 0;
 4079        b = b + f | 0;
 4080        f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
 4081
 4082        // 59
 4083        w11 = (w12 >>> 7 ^ w12 >>> 18 ^ w12 >>> 3 ^ w12 << 25 ^ w12 << 14) + (w9 >>> 17 ^ w9 >>> 19 ^ w9 >>> 10 ^ w9 << 15 ^ w9 << 13) + w11 + w4 | 0;
 4084        e = w11 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x8cc70208 | 0;
 4085        a = a + e | 0;
 4086        e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
 4087
 4088        // 60
 4089        w12 = (w13 >>> 7 ^ w13 >>> 18 ^ w13 >>> 3 ^ w13 << 25 ^ w13 << 14) + (w10 >>> 17 ^ w10 >>> 19 ^ w10 >>> 10 ^ w10 << 15 ^ w10 << 13) + w12 + w5 | 0;
 4090        d = w12 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x90befffa | 0;
 4091        h = h + d | 0;
 4092        d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
 4093
 4094        // 61
 4095        w13 = (w14 >>> 7 ^ w14 >>> 18 ^ w14 >>> 3 ^ w14 << 25 ^ w14 << 14) + (w11 >>> 17 ^ w11 >>> 19 ^ w11 >>> 10 ^ w11 << 15 ^ w11 << 13) + w13 + w6 | 0;
 4096        c = w13 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0xa4506ceb | 0;
 4097        g = g + c | 0;
 4098        c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
 4099
 4100        // 62
 4101        w14 = (w15 >>> 7 ^ w15 >>> 18 ^ w15 >>> 3 ^ w15 << 25 ^ w15 << 14) + (w12 >>> 17 ^ w12 >>> 19 ^ w12 >>> 10 ^ w12 << 15 ^ w12 << 13) + w14 + w7 | 0;
 4102        b = w14 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0xbef9a3f7 | 0;
 4103        f = f + b | 0;
 4104        b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
 4105
 4106        // 63
 4107        w15 = (w0 >>> 7 ^ w0 >>> 18 ^ w0 >>> 3 ^ w0 << 25 ^ w0 << 14) + (w13 >>> 17 ^ w13 >>> 19 ^ w13 >>> 10 ^ w13 << 15 ^ w13 << 13) + w15 + w8 | 0;
 4108        a = w15 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0xc67178f2 | 0;
 4109        e = e + a | 0;
 4110        a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
 4111
 4112        H0 = H0 + a | 0;
 4113        H1 = H1 + b | 0;
 4114        H2 = H2 + c | 0;
 4115        H3 = H3 + d | 0;
 4116        H4 = H4 + e | 0;
 4117        H5 = H5 + f | 0;
 4118        H6 = H6 + g | 0;
 4119        H7 = H7 + h | 0;
 4120    }
 4121
 4122    function _core_heap(offset) {
 4123        offset = offset | 0;
 4124
 4125        _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]);
 4126    }
 4127
 4128    // offset — multiple of 32
 4129    function _state_to_heap(output) {
 4130        output = output | 0;
 4131
 4132        HEAP[output | 0] = H0 >>> 24;
 4133        HEAP[output | 1] = H0 >>> 16 & 255;
 4134        HEAP[output | 2] = H0 >>> 8 & 255;
 4135        HEAP[output | 3] = H0 & 255;
 4136        HEAP[output | 4] = H1 >>> 24;
 4137        HEAP[output | 5] = H1 >>> 16 & 255;
 4138        HEAP[output | 6] = H1 >>> 8 & 255;
 4139        HEAP[output | 7] = H1 & 255;
 4140        HEAP[output | 8] = H2 >>> 24;
 4141        HEAP[output | 9] = H2 >>> 16 & 255;
 4142        HEAP[output | 10] = H2 >>> 8 & 255;
 4143        HEAP[output | 11] = H2 & 255;
 4144        HEAP[output | 12] = H3 >>> 24;
 4145        HEAP[output | 13] = H3 >>> 16 & 255;
 4146        HEAP[output | 14] = H3 >>> 8 & 255;
 4147        HEAP[output | 15] = H3 & 255;
 4148        HEAP[output | 16] = H4 >>> 24;
 4149        HEAP[output | 17] = H4 >>> 16 & 255;
 4150        HEAP[output | 18] = H4 >>> 8 & 255;
 4151        HEAP[output | 19] = H4 & 255;
 4152        HEAP[output | 20] = H5 >>> 24;
 4153        HEAP[output | 21] = H5 >>> 16 & 255;
 4154        HEAP[output | 22] = H5 >>> 8 & 255;
 4155        HEAP[output | 23] = H5 & 255;
 4156        HEAP[output | 24] = H6 >>> 24;
 4157        HEAP[output | 25] = H6 >>> 16 & 255;
 4158        HEAP[output | 26] = H6 >>> 8 & 255;
 4159        HEAP[output | 27] = H6 & 255;
 4160        HEAP[output | 28] = H7 >>> 24;
 4161        HEAP[output | 29] = H7 >>> 16 & 255;
 4162        HEAP[output | 30] = H7 >>> 8 & 255;
 4163        HEAP[output | 31] = H7 & 255;
 4164    }
 4165
 4166    function reset() {
 4167        H0 = 0x6a09e667;
 4168        H1 = 0xbb67ae85;
 4169        H2 = 0x3c6ef372;
 4170        H3 = 0xa54ff53a;
 4171        H4 = 0x510e527f;
 4172        H5 = 0x9b05688c;
 4173        H6 = 0x1f83d9ab;
 4174        H7 = 0x5be0cd19;
 4175        TOTAL0 = TOTAL1 = 0;
 4176    }
 4177
 4178    function init(h0, h1, h2, h3, h4, h5, h6, h7, total0, total1) {
 4179        h0 = h0 | 0;
 4180        h1 = h1 | 0;
 4181        h2 = h2 | 0;
 4182        h3 = h3 | 0;
 4183        h4 = h4 | 0;
 4184        h5 = h5 | 0;
 4185        h6 = h6 | 0;
 4186        h7 = h7 | 0;
 4187        total0 = total0 | 0;
 4188        total1 = total1 | 0;
 4189
 4190        H0 = h0;
 4191        H1 = h1;
 4192        H2 = h2;
 4193        H3 = h3;
 4194        H4 = h4;
 4195        H5 = h5;
 4196        H6 = h6;
 4197        H7 = h7;
 4198        TOTAL0 = total0;
 4199        TOTAL1 = total1;
 4200    }
 4201
 4202    // offset — multiple of 64
 4203    function process(offset, length) {
 4204        offset = offset | 0;
 4205        length = length | 0;
 4206
 4207        var hashed = 0;
 4208
 4209        if (offset & 63) return -1;
 4210
 4211        while ((length | 0) >= 64) {
 4212            _core_heap(offset);
 4213
 4214            offset = offset + 64 | 0;
 4215            length = length - 64 | 0;
 4216
 4217            hashed = hashed + 64 | 0;
 4218        }
 4219
 4220        TOTAL0 = TOTAL0 + hashed | 0;
 4221        if (TOTAL0 >>> 0 < hashed >>> 0) TOTAL1 = TOTAL1 + 1 | 0;
 4222
 4223        return hashed | 0;
 4224    }
 4225
 4226    // offset — multiple of 64
 4227    // output — multiple of 32
 4228    function finish(offset, length, output) {
 4229        offset = offset | 0;
 4230        length = length | 0;
 4231        output = output | 0;
 4232
 4233        var hashed = 0,
 4234            i = 0;
 4235
 4236        if (offset & 63) return -1;
 4237
 4238        if (~output) if (output & 31) return -1;
 4239
 4240        if ((length | 0) >= 64) {
 4241            hashed = process(offset, length) | 0;
 4242            if ((hashed | 0) == -1) return -1;
 4243
 4244            offset = offset + hashed | 0;
 4245            length = length - hashed | 0;
 4246        }
 4247
 4248        hashed = hashed + length | 0;
 4249        TOTAL0 = TOTAL0 + length | 0;
 4250        if (TOTAL0 >>> 0 < length >>> 0) TOTAL1 = TOTAL1 + 1 | 0;
 4251
 4252        HEAP[offset | length] = 0x80;
 4253
 4254        if ((length | 0) >= 56) {
 4255            for (i = length + 1 | 0; (i | 0) < 64; i = i + 1 | 0) HEAP[offset | i] = 0x00;
 4256
 4257            _core_heap(offset);
 4258
 4259            length = 0;
 4260
 4261            HEAP[offset | 0] = 0;
 4262        }
 4263
 4264        for (i = length + 1 | 0; (i | 0) < 59; i = i + 1 | 0) HEAP[offset | i] = 0;
 4265
 4266        HEAP[offset | 56] = TOTAL1 >>> 21 & 255;
 4267        HEAP[offset | 57] = TOTAL1 >>> 13 & 255;
 4268        HEAP[offset | 58] = TOTAL1 >>> 5 & 255;
 4269        HEAP[offset | 59] = TOTAL1 << 3 & 255 | TOTAL0 >>> 29;
 4270        HEAP[offset | 60] = TOTAL0 >>> 21 & 255;
 4271        HEAP[offset | 61] = TOTAL0 >>> 13 & 255;
 4272        HEAP[offset | 62] = TOTAL0 >>> 5 & 255;
 4273        HEAP[offset | 63] = TOTAL0 << 3 & 255;
 4274        _core_heap(offset);
 4275
 4276        if (~output) _state_to_heap(output);
 4277
 4278        return hashed | 0;
 4279    }
 4280
 4281    function hmac_reset() {
 4282        H0 = I0;
 4283        H1 = I1;
 4284        H2 = I2;
 4285        H3 = I3;
 4286        H4 = I4;
 4287        H5 = I5;
 4288        H6 = I6;
 4289        H7 = I7;
 4290        TOTAL0 = 64;
 4291        TOTAL1 = 0;
 4292    }
 4293
 4294    function _hmac_opad() {
 4295        H0 = O0;
 4296        H1 = O1;
 4297        H2 = O2;
 4298        H3 = O3;
 4299        H4 = O4;
 4300        H5 = O5;
 4301        H6 = O6;
 4302        H7 = O7;
 4303        TOTAL0 = 64;
 4304        TOTAL1 = 0;
 4305    }
 4306
 4307    function hmac_init(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15) {
 4308        p0 = p0 | 0;
 4309        p1 = p1 | 0;
 4310        p2 = p2 | 0;
 4311        p3 = p3 | 0;
 4312        p4 = p4 | 0;
 4313        p5 = p5 | 0;
 4314        p6 = p6 | 0;
 4315        p7 = p7 | 0;
 4316        p8 = p8 | 0;
 4317        p9 = p9 | 0;
 4318        p10 = p10 | 0;
 4319        p11 = p11 | 0;
 4320        p12 = p12 | 0;
 4321        p13 = p13 | 0;
 4322        p14 = p14 | 0;
 4323        p15 = p15 | 0;
 4324
 4325        // opad
 4326        reset();
 4327        _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);
 4328        O0 = H0;
 4329        O1 = H1;
 4330        O2 = H2;
 4331        O3 = H3;
 4332        O4 = H4;
 4333        O5 = H5;
 4334        O6 = H6;
 4335        O7 = H7;
 4336
 4337        // ipad
 4338        reset();
 4339        _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);
 4340        I0 = H0;
 4341        I1 = H1;
 4342        I2 = H2;
 4343        I3 = H3;
 4344        I4 = H4;
 4345        I5 = H5;
 4346        I6 = H6;
 4347        I7 = H7;
 4348
 4349        TOTAL0 = 64;
 4350        TOTAL1 = 0;
 4351    }
 4352
 4353    // offset — multiple of 64
 4354    // output — multiple of 32
 4355    function hmac_finish(offset, length, output) {
 4356        offset = offset | 0;
 4357        length = length | 0;
 4358        output = output | 0;
 4359
 4360        var t0 = 0,
 4361            t1 = 0,
 4362            t2 = 0,
 4363            t3 = 0,
 4364            t4 = 0,
 4365            t5 = 0,
 4366            t6 = 0,
 4367            t7 = 0,
 4368            hashed = 0;
 4369
 4370        if (offset & 63) return -1;
 4371
 4372        if (~output) if (output & 31) return -1;
 4373
 4374        hashed = finish(offset, length, -1) | 0;
 4375        t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
 4376
 4377        _hmac_opad();
 4378        _core(t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768);
 4379
 4380        if (~output) _state_to_heap(output);
 4381
 4382        return hashed | 0;
 4383    }
 4384
 4385    // salt is assumed to be already processed
 4386    // offset — multiple of 64
 4387    // output — multiple of 32
 4388    function pbkdf2_generate_block(offset, length, block, count, output) {
 4389        offset = offset | 0;
 4390        length = length | 0;
 4391        block = block | 0;
 4392        count = count | 0;
 4393        output = output | 0;
 4394
 4395        var h0 = 0,
 4396            h1 = 0,
 4397            h2 = 0,
 4398            h3 = 0,
 4399            h4 = 0,
 4400            h5 = 0,
 4401            h6 = 0,
 4402            h7 = 0,
 4403            t0 = 0,
 4404            t1 = 0,
 4405            t2 = 0,
 4406            t3 = 0,
 4407            t4 = 0,
 4408            t5 = 0,
 4409            t6 = 0,
 4410            t7 = 0;
 4411
 4412        if (offset & 63) return -1;
 4413
 4414        if (~output) if (output & 31) return -1;
 4415
 4416        // pad block number into heap
 4417        // FIXME probable OOB write
 4418        HEAP[offset + length | 0] = block >>> 24;
 4419        HEAP[offset + length + 1 | 0] = block >>> 16 & 255;
 4420        HEAP[offset + length + 2 | 0] = block >>> 8 & 255;
 4421        HEAP[offset + length + 3 | 0] = block & 255;
 4422
 4423        // finish first iteration
 4424        hmac_finish(offset, length + 4 | 0, -1) | 0;
 4425        h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7;
 4426        count = count - 1 | 0;
 4427
 4428        // perform the rest iterations
 4429        while ((count | 0) > 0) {
 4430            hmac_reset();
 4431            _core(t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768);
 4432            t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
 4433
 4434            _hmac_opad();
 4435            _core(t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768);
 4436            t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
 4437
 4438            h0 = h0 ^ H0;
 4439            h1 = h1 ^ H1;
 4440            h2 = h2 ^ H2;
 4441            h3 = h3 ^ H3;
 4442            h4 = h4 ^ H4;
 4443            h5 = h5 ^ H5;
 4444            h6 = h6 ^ H6;
 4445            h7 = h7 ^ H7;
 4446
 4447            count = count - 1 | 0;
 4448        }
 4449
 4450        H0 = h0;
 4451        H1 = h1;
 4452        H2 = h2;
 4453        H3 = h3;
 4454        H4 = h4;
 4455        H5 = h5;
 4456        H6 = h6;
 4457        H7 = h7;
 4458
 4459        if (~output) _state_to_heap(output);
 4460
 4461        return 0;
 4462    }
 4463
 4464    return {
 4465        // SHA256
 4466        reset: reset,
 4467        init: init,
 4468        process: process,
 4469        finish: finish,
 4470
 4471        // HMAC-SHA256
 4472        hmac_reset: hmac_reset,
 4473        hmac_init: hmac_init,
 4474        hmac_finish: hmac_finish,
 4475
 4476        // PBKDF2-HMAC-SHA256
 4477        pbkdf2_generate_block: pbkdf2_generate_block
 4478    };
 4479}
 4480
 4481},{}],14:[function(require,module,exports){
 4482'use strict';
 4483
 4484Object.defineProperty(exports, "__esModule", {
 4485    value: true
 4486});
 4487exports.Sha256 = exports._sha256_hash_size = exports._sha256_block_size = undefined;
 4488
 4489var _sha = require('./sha256.asm');
 4490
 4491var _hash = require('../hash');
 4492
 4493var __extends = undefined && undefined.__extends || function () {
 4494    var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
 4495        d.__proto__ = b;
 4496    } || function (d, b) {
 4497        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
 4498    };
 4499    return function (d, b) {
 4500        extendStatics(d, b);
 4501        function __() {
 4502            this.constructor = d;
 4503        }
 4504        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
 4505    };
 4506}();
 4507var _sha256_block_size = exports._sha256_block_size = 64;
 4508var _sha256_hash_size = exports._sha256_hash_size = 32;
 4509var Sha256 = /** @class */function (_super) {
 4510    __extends(Sha256, _super);
 4511    function Sha256() {
 4512        var _this = _super !== null && _super.apply(this, arguments) || this;
 4513        _this.NAME = 'sha256';
 4514        _this.BLOCK_SIZE = _sha256_block_size;
 4515        _this.HASH_SIZE = _sha256_hash_size;
 4516        return _this;
 4517    }
 4518    Sha256.bytes = function (data) {
 4519        return new Sha256().process(data).finish().result;
 4520    };
 4521    Sha256.NAME = 'sha256';
 4522    Sha256.heap_pool = [];
 4523    Sha256.asm_pool = [];
 4524    Sha256.asm_function = _sha.sha256_asm;
 4525    return Sha256;
 4526}(_hash.Hash);
 4527exports.Sha256 = Sha256;
 4528
 4529},{"../hash":10,"./sha256.asm":13}],15:[function(require,module,exports){
 4530'use strict';
 4531
 4532Object.defineProperty(exports, "__esModule", {
 4533    value: true
 4534});
 4535var __extends = undefined && undefined.__extends || function () {
 4536    var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
 4537        d.__proto__ = b;
 4538    } || function (d, b) {
 4539        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
 4540    };
 4541    return function (d, b) {
 4542        extendStatics(d, b);
 4543        function __() {
 4544            this.constructor = d;
 4545        }
 4546        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
 4547    };
 4548}();
 4549var IllegalStateError = /** @class */function (_super) {
 4550    __extends(IllegalStateError, _super);
 4551    function IllegalStateError() {
 4552        var args = [];
 4553        for (var _i = 0; _i < arguments.length; _i++) {
 4554            args[_i] = arguments[_i];
 4555        }
 4556        var _this = _super.apply(this, args) || this;
 4557        Object.create(Error.prototype, { name: { value: 'IllegalStateError' } });
 4558        return _this;
 4559    }
 4560    return IllegalStateError;
 4561}(Error);
 4562exports.IllegalStateError = IllegalStateError;
 4563
 4564var IllegalArgumentError = /** @class */function (_super) {
 4565    __extends(IllegalArgumentError, _super);
 4566    function IllegalArgumentError() {
 4567        var args = [];
 4568        for (var _i = 0; _i < arguments.length; _i++) {
 4569            args[_i] = arguments[_i];
 4570        }
 4571        var _this = _super.apply(this, args) || this;
 4572        Object.create(Error.prototype, { name: { value: 'IllegalArgumentError' } });
 4573        return _this;
 4574    }
 4575    return IllegalArgumentError;
 4576}(Error);
 4577exports.IllegalArgumentError = IllegalArgumentError;
 4578
 4579var SecurityError = /** @class */function (_super) {
 4580    __extends(SecurityError, _super);
 4581    function SecurityError() {
 4582        var args = [];
 4583        for (var _i = 0; _i < arguments.length; _i++) {
 4584            args[_i] = arguments[_i];
 4585        }
 4586        var _this = _super.apply(this, args) || this;
 4587        Object.create(Error.prototype, { name: { value: 'SecurityError' } });
 4588        return _this;
 4589    }
 4590    return SecurityError;
 4591}(Error);
 4592exports.SecurityError = SecurityError;
 4593
 4594},{}],16:[function(require,module,exports){
 4595'use strict';
 4596
 4597Object.defineProperty(exports, "__esModule", {
 4598    value: true
 4599});
 4600exports.string_to_bytes = string_to_bytes;
 4601exports.hex_to_bytes = hex_to_bytes;
 4602exports.base64_to_bytes = base64_to_bytes;
 4603exports.bytes_to_string = bytes_to_string;
 4604exports.bytes_to_hex = bytes_to_hex;
 4605exports.bytes_to_base64 = bytes_to_base64;
 4606exports.pow2_ceil = pow2_ceil;
 4607exports.is_number = is_number;
 4608exports.is_string = is_string;
 4609exports.is_buffer = is_buffer;
 4610exports.is_bytes = is_bytes;
 4611exports.is_typed_array = is_typed_array;
 4612exports._heap_init = _heap_init;
 4613exports._heap_write = _heap_write;
 4614exports.joinBytes = joinBytes;
 4615var local_atob = typeof atob === 'undefined' ? function (str) {
 4616    return require('buffer').Buffer.from(str, 'base64').toString('binary');
 4617} : atob;
 4618var local_btoa = typeof btoa === 'undefined' ? function (str) {
 4619    return require('buffer').Buffer.from(str, 'binary').toString('base64');
 4620} : btoa;
 4621function string_to_bytes(str, utf8) {
 4622    if (utf8 === void 0) {
 4623        utf8 = false;
 4624    }
 4625    var len = str.length,
 4626        bytes = new Uint8Array(utf8 ? 4 * len : len);
 4627    for (var i = 0, j = 0; i < len; i++) {
 4628        var c = str.charCodeAt(i);
 4629        if (utf8 && 0xd800 <= c && c <= 0xdbff) {
 4630            if (++i >= len) throw new Error('Malformed string, low surrogate expected at position ' + i);
 4631            c = (c ^ 0xd800) << 10 | 0x10000 | str.charCodeAt(i) ^ 0xdc00;
 4632        } else if (!utf8 && c >>> 8) {
 4633            throw new Error('Wide characters are not allowed.');
 4634        }
 4635        if (!utf8 || c <= 0x7f) {
 4636            bytes[j++] = c;
 4637        } else if (c <= 0x7ff) {
 4638            bytes[j++] = 0xc0 | c >> 6;
 4639            bytes[j++] = 0x80 | c & 0x3f;
 4640        } else if (c <= 0xffff) {
 4641            bytes[j++] = 0xe0 | c >> 12;
 4642            bytes[j++] = 0x80 | c >> 6 & 0x3f;
 4643            bytes[j++] = 0x80 | c & 0x3f;
 4644        } else {
 4645            bytes[j++] = 0xf0 | c >> 18;
 4646            bytes[j++] = 0x80 | c >> 12 & 0x3f;
 4647            bytes[j++] = 0x80 | c >> 6 & 0x3f;
 4648            bytes[j++] = 0x80 | c & 0x3f;
 4649        }
 4650    }
 4651    return bytes.subarray(0, j);
 4652}
 4653function hex_to_bytes(str) {
 4654    var len = str.length;
 4655    if (len & 1) {
 4656        str = '0' + str;
 4657        len++;
 4658    }
 4659    var bytes = new Uint8Array(len >> 1);
 4660    for (var i = 0; i < len; i += 2) {
 4661        bytes[i >> 1] = parseInt(str.substr(i, 2), 16);
 4662    }
 4663    return bytes;
 4664}
 4665function base64_to_bytes(str) {
 4666    return string_to_bytes(local_atob(str));
 4667}
 4668function bytes_to_string(bytes, utf8) {
 4669    if (utf8 === void 0) {
 4670        utf8 = false;
 4671    }
 4672    var len = bytes.length,
 4673        chars = new Array(len);
 4674    for (var i = 0, j = 0; i < len; i++) {
 4675        var b = bytes[i];
 4676        if (!utf8 || b < 128) {
 4677            chars[j++] = b;
 4678        } else if (b >= 192 && b < 224 && i + 1 < len) {
 4679            chars[j++] = (b & 0x1f) << 6 | bytes[++i] & 0x3f;
 4680        } else if (b >= 224 && b < 240 && i + 2 < len) {
 4681            chars[j++] = (b & 0xf) << 12 | (bytes[++i] & 0x3f) << 6 | bytes[++i] & 0x3f;
 4682        } else if (b >= 240 && b < 248 && i + 3 < len) {
 4683            var c = (b & 7) << 18 | (bytes[++i] & 0x3f) << 12 | (bytes[++i] & 0x3f) << 6 | bytes[++i] & 0x3f;
 4684            if (c <= 0xffff) {
 4685                chars[j++] = c;
 4686            } else {
 4687                c ^= 0x10000;
 4688                chars[j++] = 0xd800 | c >> 10;
 4689                chars[j++] = 0xdc00 | c & 0x3ff;
 4690            }
 4691        } else {
 4692            throw new Error('Malformed UTF8 character at byte offset ' + i);
 4693        }
 4694    }
 4695    var str = '',
 4696        bs = 16384;
 4697    for (var i = 0; i < j; i += bs) {
 4698        str += String.fromCharCode.apply(String, chars.slice(i, i + bs <= j ? i + bs : j));
 4699    }
 4700    return str;
 4701}
 4702function bytes_to_hex(arr) {
 4703    var str = '';
 4704    for (var i = 0; i < arr.length; i++) {
 4705        var h = (arr[i] & 0xff).toString(16);
 4706        if (h.length < 2) str += '0';
 4707        str += h;
 4708    }
 4709    return str;
 4710}
 4711function bytes_to_base64(arr) {
 4712    return local_btoa(bytes_to_string(arr));
 4713}
 4714function pow2_ceil(a) {
 4715    a -= 1;
 4716    a |= a >>> 1;
 4717    a |= a >>> 2;
 4718    a |= a >>> 4;
 4719    a |= a >>> 8;
 4720    a |= a >>> 16;
 4721    a += 1;
 4722    return a;
 4723}
 4724function is_number(a) {
 4725    return typeof a === 'number';
 4726}
 4727function is_string(a) {
 4728    return typeof a === 'string';
 4729}
 4730function is_buffer(a) {
 4731    return a instanceof ArrayBuffer;
 4732}
 4733function is_bytes(a) {
 4734    return a instanceof Uint8Array;
 4735}
 4736function is_typed_array(a) {
 4737    return a instanceof Int8Array || a instanceof Uint8Array || a instanceof Int16Array || a instanceof Uint16Array || a instanceof Int32Array || a instanceof Uint32Array || a instanceof Float32Array || a instanceof Float64Array;
 4738}
 4739function _heap_init(heap, heapSize) {
 4740    var size = heap ? heap.byteLength : heapSize || 65536;
 4741    if (size & 0xfff || size <= 0) throw new Error('heap size must be a positive integer and a multiple of 4096');
 4742    heap = heap || new Uint8Array(new ArrayBuffer(size));
 4743    return heap;
 4744}
 4745function _heap_write(heap, hpos, data, dpos, dlen) {
 4746    var hlen = heap.length - hpos;
 4747    var wlen = hlen < dlen ? hlen : dlen;
 4748    heap.set(data.subarray(dpos, dpos + wlen), hpos);
 4749    return wlen;
 4750}
 4751function joinBytes() {
 4752    var arg = [];
 4753    for (var _i = 0; _i < arguments.length; _i++) {
 4754        arg[_i] = arguments[_i];
 4755    }
 4756    var totalLenght = arg.reduce(function (sum, curr) {
 4757        return sum + curr.length;
 4758    }, 0);
 4759    var ret = new Uint8Array(totalLenght);
 4760    var cursor = 0;
 4761    for (var i = 0; i < arg.length; i++) {
 4762        ret.set(arg[i], cursor);
 4763        cursor += arg[i].length;
 4764    }
 4765    return ret;
 4766}
 4767
 4768},{"buffer":"buffer"}],17:[function(require,module,exports){
 4769(function (module, exports) {
 4770  'use strict';
 4771
 4772  // Utils
 4773  function assert (val, msg) {
 4774    if (!val) throw new Error(msg || 'Assertion failed');
 4775  }
 4776
 4777  // Could use `inherits` module, but don't want to move from single file
 4778  // architecture yet.
 4779  function inherits (ctor, superCtor) {
 4780    ctor.super_ = superCtor;
 4781    var TempCtor = function () {};
 4782    TempCtor.prototype = superCtor.prototype;
 4783    ctor.prototype = new TempCtor();
 4784    ctor.prototype.constructor = ctor;
 4785  }
 4786
 4787  // BN
 4788
 4789  function BN (number, base, endian) {
 4790    if (BN.isBN(number)) {
 4791      return number;
 4792    }
 4793
 4794    this.negative = 0;
 4795    this.words = null;
 4796    this.length = 0;
 4797
 4798    // Reduction context
 4799    this.red = null;
 4800
 4801    if (number !== null) {
 4802      if (base === 'le' || base === 'be') {
 4803        endian = base;
 4804        base = 10;
 4805      }
 4806
 4807      this._init(number || 0, base || 10, endian || 'be');
 4808    }
 4809  }
 4810  if (typeof module === 'object') {
 4811    module.exports = BN;
 4812  } else {
 4813    exports.BN = BN;
 4814  }
 4815
 4816  BN.BN = BN;
 4817  BN.wordSize = 26;
 4818
 4819  var Buffer;
 4820  try {
 4821    Buffer = require('buffer').Buffer;
 4822  } catch (e) {
 4823  }
 4824
 4825  BN.isBN = function isBN (num) {
 4826    if (num instanceof BN) {
 4827      return true;
 4828    }
 4829
 4830    return num !== null && typeof num === 'object' &&
 4831      num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
 4832  };
 4833
 4834  BN.max = function max (left, right) {
 4835    if (left.cmp(right) > 0) return left;
 4836    return right;
 4837  };
 4838
 4839  BN.min = function min (left, right) {
 4840    if (left.cmp(right) < 0) return left;
 4841    return right;
 4842  };
 4843
 4844  BN.prototype._init = function init (number, base, endian) {
 4845    if (typeof number === 'number') {
 4846      return this._initNumber(number, base, endian);
 4847    }
 4848
 4849    if (typeof number === 'object') {
 4850      return this._initArray(number, base, endian);
 4851    }
 4852
 4853    if (base === 'hex') {
 4854      base = 16;
 4855    }
 4856    assert(base === (base | 0) && base >= 2 && base <= 36);
 4857
 4858    number = number.toString().replace(/\s+/g, '');
 4859    var start = 0;
 4860    if (number[0] === '-') {
 4861      start++;
 4862    }
 4863
 4864    if (base === 16) {
 4865      this._parseHex(number, start);
 4866    } else {
 4867      this._parseBase(number, base, start);
 4868    }
 4869
 4870    if (number[0] === '-') {
 4871      this.negative = 1;
 4872    }
 4873
 4874    this.strip();
 4875
 4876    if (endian !== 'le') return;
 4877
 4878    this._initArray(this.toArray(), base, endian);
 4879  };
 4880
 4881  BN.prototype._initNumber = function _initNumber (number, base, endian) {
 4882    if (number < 0) {
 4883      this.negative = 1;
 4884      number = -number;
 4885    }
 4886    if (number < 0x4000000) {
 4887      this.words = [ number & 0x3ffffff ];
 4888      this.length = 1;
 4889    } else if (number < 0x10000000000000) {
 4890      this.words = [
 4891        number & 0x3ffffff,
 4892        (number / 0x4000000) & 0x3ffffff
 4893      ];
 4894      this.length = 2;
 4895    } else {
 4896      assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
 4897      this.words = [
 4898        number & 0x3ffffff,
 4899        (number / 0x4000000) & 0x3ffffff,
 4900        1
 4901      ];
 4902      this.length = 3;
 4903    }
 4904
 4905    if (endian !== 'le') return;
 4906
 4907    // Reverse the bytes
 4908    this._initArray(this.toArray(), base, endian);
 4909  };
 4910
 4911  BN.prototype._initArray = function _initArray (number, base, endian) {
 4912    // Perhaps a Uint8Array
 4913    assert(typeof number.length === 'number');
 4914    if (number.length <= 0) {
 4915      this.words = [ 0 ];
 4916      this.length = 1;
 4917      return this;
 4918    }
 4919
 4920    this.length = Math.ceil(number.length / 3);
 4921    this.words = new Array(this.length);
 4922    for (var i = 0; i < this.length; i++) {
 4923      this.words[i] = 0;
 4924    }
 4925
 4926    var j, w;
 4927    var off = 0;
 4928    if (endian === 'be') {
 4929      for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
 4930        w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
 4931        this.words[j] |= (w << off) & 0x3ffffff;
 4932        this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
 4933        off += 24;
 4934        if (off >= 26) {
 4935          off -= 26;
 4936          j++;
 4937        }
 4938      }
 4939    } else if (endian === 'le') {
 4940      for (i = 0, j = 0; i < number.length; i += 3) {
 4941        w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
 4942        this.words[j] |= (w << off) & 0x3ffffff;
 4943        this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
 4944        off += 24;
 4945        if (off >= 26) {
 4946          off -= 26;
 4947          j++;
 4948        }
 4949      }
 4950    }
 4951    return this.strip();
 4952  };
 4953
 4954  function parseHex (str, start, end) {
 4955    var r = 0;
 4956    var len = Math.min(str.length, end);
 4957    for (var i = start; i < len; i++) {
 4958      var c = str.charCodeAt(i) - 48;
 4959
 4960      r <<= 4;
 4961
 4962      // 'a' - 'f'
 4963      if (c >= 49 && c <= 54) {
 4964        r |= c - 49 + 0xa;
 4965
 4966      // 'A' - 'F'
 4967      } else if (c >= 17 && c <= 22) {
 4968        r |= c - 17 + 0xa;
 4969
 4970      // '0' - '9'
 4971      } else {
 4972        r |= c & 0xf;
 4973      }
 4974    }
 4975    return r;
 4976  }
 4977
 4978  BN.prototype._parseHex = function _parseHex (number, start) {
 4979    // Create possibly bigger array to ensure that it fits the number
 4980    this.length = Math.ceil((number.length - start) / 6);
 4981    this.words = new Array(this.length);
 4982    for (var i = 0; i < this.length; i++) {
 4983      this.words[i] = 0;
 4984    }
 4985
 4986    var j, w;
 4987    // Scan 24-bit chunks and add them to the number
 4988    var off = 0;
 4989    for (i = number.length - 6, j = 0; i >= start; i -= 6) {
 4990      w = parseHex(number, i, i + 6);
 4991      this.words[j] |= (w << off) & 0x3ffffff;
 4992      // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
 4993      this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
 4994      off += 24;
 4995      if (off >= 26) {
 4996        off -= 26;
 4997        j++;
 4998      }
 4999    }
 5000    if (i + 6 !== start) {
 5001      w = parseHex(number, start, i + 6);
 5002      this.words[j] |= (w << off) & 0x3ffffff;
 5003      this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
 5004    }
 5005    this.strip();
 5006  };
 5007
 5008  function parseBase (str, start, end, mul) {
 5009    var r = 0;
 5010    var len = Math.min(str.length, end);
 5011    for (var i = start; i < len; i++) {
 5012      var c = str.charCodeAt(i) - 48;
 5013
 5014      r *= mul;
 5015
 5016      // 'a'
 5017      if (c >= 49) {
 5018        r += c - 49 + 0xa;
 5019
 5020      // 'A'
 5021      } else if (c >= 17) {
 5022        r += c - 17 + 0xa;
 5023
 5024      // '0' - '9'
 5025      } else {
 5026        r += c;
 5027      }
 5028    }
 5029    return r;
 5030  }
 5031
 5032  BN.prototype._parseBase = function _parseBase (number, base, start) {
 5033    // Initialize as zero
 5034    this.words = [ 0 ];
 5035    this.length = 1;
 5036
 5037    // Find length of limb in base
 5038    for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
 5039      limbLen++;
 5040    }
 5041    limbLen--;
 5042    limbPow = (limbPow / base) | 0;
 5043
 5044    var total = number.length - start;
 5045    var mod = total % limbLen;
 5046    var end = Math.min(total, total - mod) + start;
 5047
 5048    var word = 0;
 5049    for (var i = start; i < end; i += limbLen) {
 5050      word = parseBase(number, i, i + limbLen, base);
 5051
 5052      this.imuln(limbPow);
 5053      if (this.words[0] + word < 0x4000000) {
 5054        this.words[0] += word;
 5055      } else {
 5056        this._iaddn(word);
 5057      }
 5058    }
 5059
 5060    if (mod !== 0) {
 5061      var pow = 1;
 5062      word = parseBase(number, i, number.length, base);
 5063
 5064      for (i = 0; i < mod; i++) {
 5065        pow *= base;
 5066      }
 5067
 5068      this.imuln(pow);
 5069      if (this.words[0] + word < 0x4000000) {
 5070        this.words[0] += word;
 5071      } else {
 5072        this._iaddn(word);
 5073      }
 5074    }
 5075  };
 5076
 5077  BN.prototype.copy = function copy (dest) {
 5078    dest.words = new Array(this.length);
 5079    for (var i = 0; i < this.length; i++) {
 5080      dest.words[i] = this.words[i];
 5081    }
 5082    dest.length = this.length;
 5083    dest.negative = this.negative;
 5084    dest.red = this.red;
 5085  };
 5086
 5087  BN.prototype.clone = function clone () {
 5088    var r = new BN(null);
 5089    this.copy(r);
 5090    return r;
 5091  };
 5092
 5093  BN.prototype._expand = function _expand (size) {
 5094    while (this.length < size) {
 5095      this.words[this.length++] = 0;
 5096    }
 5097    return this;
 5098  };
 5099
 5100  // Remove leading `0` from `this`
 5101  BN.prototype.strip = function strip () {
 5102    while (this.length > 1 && this.words[this.length - 1] === 0) {
 5103      this.length--;
 5104    }
 5105    return this._normSign();
 5106  };
 5107
 5108  BN.prototype._normSign = function _normSign () {
 5109    // -0 = 0
 5110    if (this.length === 1 && this.words[0] === 0) {
 5111      this.negative = 0;
 5112    }
 5113    return this;
 5114  };
 5115
 5116  BN.prototype.inspect = function inspect () {
 5117    return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
 5118  };
 5119
 5120  /*
 5121
 5122  var zeros = [];
 5123  var groupSizes = [];
 5124  var groupBases = [];
 5125
 5126  var s = '';
 5127  var i = -1;
 5128  while (++i < BN.wordSize) {
 5129    zeros[i] = s;
 5130    s += '0';
 5131  }
 5132  groupSizes[0] = 0;
 5133  groupSizes[1] = 0;
 5134  groupBases[0] = 0;
 5135  groupBases[1] = 0;
 5136  var base = 2 - 1;
 5137  while (++base < 36 + 1) {
 5138    var groupSize = 0;
 5139    var groupBase = 1;
 5140    while (groupBase < (1 << BN.wordSize) / base) {
 5141      groupBase *= base;
 5142      groupSize += 1;
 5143    }
 5144    groupSizes[base] = groupSize;
 5145    groupBases[base] = groupBase;
 5146  }
 5147
 5148  */
 5149
 5150  var zeros = [
 5151    '',
 5152    '0',
 5153    '00',
 5154    '000',
 5155    '0000',
 5156    '00000',
 5157    '000000',
 5158    '0000000',
 5159    '00000000',
 5160    '000000000',
 5161    '0000000000',
 5162    '00000000000',
 5163    '000000000000',
 5164    '0000000000000',
 5165    '00000000000000',
 5166    '000000000000000',
 5167    '0000000000000000',
 5168    '00000000000000000',
 5169    '000000000000000000',
 5170    '0000000000000000000',
 5171    '00000000000000000000',
 5172    '000000000000000000000',
 5173    '0000000000000000000000',
 5174    '00000000000000000000000',
 5175    '000000000000000000000000',
 5176    '0000000000000000000000000'
 5177  ];
 5178
 5179  var groupSizes = [
 5180    0, 0,
 5181    25, 16, 12, 11, 10, 9, 8,
 5182    8, 7, 7, 7, 7, 6, 6,
 5183    6, 6, 6, 6, 6, 5, 5,
 5184    5, 5, 5, 5, 5, 5, 5,
 5185    5, 5, 5, 5, 5, 5, 5
 5186  ];
 5187
 5188  var groupBases = [
 5189    0, 0,
 5190    33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
 5191    43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
 5192    16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
 5193    6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
 5194    24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
 5195  ];
 5196
 5197  BN.prototype.toString = function toString (base, padding) {
 5198    base = base || 10;
 5199    padding = padding | 0 || 1;
 5200
 5201    var out;
 5202    if (base === 16 || base === 'hex') {
 5203      out = '';
 5204      var off = 0;
 5205      var carry = 0;
 5206      for (var i = 0; i < this.length; i++) {
 5207        var w = this.words[i];
 5208        var word = (((w << off) | carry) & 0xffffff).toString(16);
 5209        carry = (w >>> (24 - off)) & 0xffffff;
 5210        if (carry !== 0 || i !== this.length - 1) {
 5211          out = zeros[6 - word.length] + word + out;
 5212        } else {
 5213          out = word + out;
 5214        }
 5215        off += 2;
 5216        if (off >= 26) {
 5217          off -= 26;
 5218          i--;
 5219        }
 5220      }
 5221      if (carry !== 0) {
 5222        out = carry.toString(16) + out;
 5223      }
 5224      while (out.length % padding !== 0) {
 5225        out = '0' + out;
 5226      }
 5227      if (this.negative !== 0) {
 5228        out = '-' + out;
 5229      }
 5230      return out;
 5231    }
 5232
 5233    if (base === (base | 0) && base >= 2 && base <= 36) {
 5234      // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
 5235      var groupSize = groupSizes[base];
 5236      // var groupBase = Math.pow(base, groupSize);
 5237      var groupBase = groupBases[base];
 5238      out = '';
 5239      var c = this.clone();
 5240      c.negative = 0;
 5241      while (!c.isZero()) {
 5242        var r = c.modn(groupBase).toString(base);
 5243        c = c.idivn(groupBase);
 5244
 5245        if (!c.isZero()) {
 5246          out = zeros[groupSize - r.length] + r + out;
 5247        } else {
 5248          out = r + out;
 5249        }
 5250      }
 5251      if (this.isZero()) {
 5252        out = '0' + out;
 5253      }
 5254      while (out.length % padding !== 0) {
 5255        out = '0' + out;
 5256      }
 5257      if (this.negative !== 0) {
 5258        out = '-' + out;
 5259      }
 5260      return out;
 5261    }
 5262
 5263    assert(false, 'Base should be between 2 and 36');
 5264  };
 5265
 5266  BN.prototype.toNumber = function toNumber () {
 5267    var ret = this.words[0];
 5268    if (this.length === 2) {
 5269      ret += this.words[1] * 0x4000000;
 5270    } else if (this.length === 3 && this.words[2] === 0x01) {
 5271      // NOTE: at this stage it is known that the top bit is set
 5272      ret += 0x10000000000000 + (this.words[1] * 0x4000000);
 5273    } else if (this.length > 2) {
 5274      assert(false, 'Number can only safely store up to 53 bits');
 5275    }
 5276    return (this.negative !== 0) ? -ret : ret;
 5277  };
 5278
 5279  BN.prototype.toJSON = function toJSON () {
 5280    return this.toString(16);
 5281  };
 5282
 5283  BN.prototype.toBuffer = function toBuffer (endian, length) {
 5284    assert(typeof Buffer !== 'undefined');
 5285    return this.toArrayLike(Buffer, endian, length);
 5286  };
 5287
 5288  BN.prototype.toArray = function toArray (endian, length) {
 5289    return this.toArrayLike(Array, endian, length);
 5290  };
 5291
 5292  BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
 5293    var byteLength = this.byteLength();
 5294    var reqLength = length || Math.max(1, byteLength);
 5295    assert(byteLength <= reqLength, 'byte array longer than desired length');
 5296    assert(reqLength > 0, 'Requested array length <= 0');
 5297
 5298    this.strip();
 5299    var littleEndian = endian === 'le';
 5300    var res = new ArrayType(reqLength);
 5301
 5302    var b, i;
 5303    var q = this.clone();
 5304    if (!littleEndian) {
 5305      // Assume big-endian
 5306      for (i = 0; i < reqLength - byteLength; i++) {
 5307        res[i] = 0;
 5308      }
 5309
 5310      for (i = 0; !q.isZero(); i++) {
 5311        b = q.andln(0xff);
 5312        q.iushrn(8);
 5313
 5314        res[reqLength - i - 1] = b;
 5315      }
 5316    } else {
 5317      for (i = 0; !q.isZero(); i++) {
 5318        b = q.andln(0xff);
 5319        q.iushrn(8);
 5320
 5321        res[i] = b;
 5322      }
 5323
 5324      for (; i < reqLength; i++) {
 5325        res[i] = 0;
 5326      }
 5327    }
 5328
 5329    return res;
 5330  };
 5331
 5332  if (Math.clz32) {
 5333    BN.prototype._countBits = function _countBits (w) {
 5334      return 32 - Math.clz32(w);
 5335    };
 5336  } else {
 5337    BN.prototype._countBits = function _countBits (w) {
 5338      var t = w;
 5339      var r = 0;
 5340      if (t >= 0x1000) {
 5341        r += 13;
 5342        t >>>= 13;
 5343      }
 5344      if (t >= 0x40) {
 5345        r += 7;
 5346        t >>>= 7;
 5347      }
 5348      if (t >= 0x8) {
 5349        r += 4;
 5350        t >>>= 4;
 5351      }
 5352      if (t >= 0x02) {
 5353        r += 2;
 5354        t >>>= 2;
 5355      }
 5356      return r + t;
 5357    };
 5358  }
 5359
 5360  BN.prototype._zeroBits = function _zeroBits (w) {
 5361    // Short-cut
 5362    if (w === 0) return 26;
 5363
 5364    var t = w;
 5365    var r = 0;
 5366    if ((t & 0x1fff) === 0) {
 5367      r += 13;
 5368      t >>>= 13;
 5369    }
 5370    if ((t & 0x7f) === 0) {
 5371      r += 7;
 5372      t >>>= 7;
 5373    }
 5374    if ((t & 0xf) === 0) {
 5375      r += 4;
 5376      t >>>= 4;
 5377    }
 5378    if ((t & 0x3) === 0) {
 5379      r += 2;
 5380      t >>>= 2;
 5381    }
 5382    if ((t & 0x1) === 0) {
 5383      r++;
 5384    }
 5385    return r;
 5386  };
 5387
 5388  // Return number of used bits in a BN
 5389  BN.prototype.bitLength = function bitLength () {
 5390    var w = this.words[this.length - 1];
 5391    var hi = this._countBits(w);
 5392    return (this.length - 1) * 26 + hi;
 5393  };
 5394
 5395  function toBitArray (num) {
 5396    var w = new Array(num.bitLength());
 5397
 5398    for (var bit = 0; bit < w.length; bit++) {
 5399      var off = (bit / 26) | 0;
 5400      var wbit = bit % 26;
 5401
 5402      w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
 5403    }
 5404
 5405    return w;
 5406  }
 5407
 5408  // Number of trailing zero bits
 5409  BN.prototype.zeroBits = function zeroBits () {
 5410    if (this.isZero()) return 0;
 5411
 5412    var r = 0;
 5413    for (var i = 0; i < this.length; i++) {
 5414      var b = this._zeroBits(this.words[i]);
 5415      r += b;
 5416      if (b !== 26) break;
 5417    }
 5418    return r;
 5419  };
 5420
 5421  BN.prototype.byteLength = function byteLength () {
 5422    return Math.ceil(this.bitLength() / 8);
 5423  };
 5424
 5425  BN.prototype.toTwos = function toTwos (width) {
 5426    if (this.negative !== 0) {
 5427      return this.abs().inotn(width).iaddn(1);
 5428    }
 5429    return this.clone();
 5430  };
 5431
 5432  BN.prototype.fromTwos = function fromTwos (width) {
 5433    if (this.testn(width - 1)) {
 5434      return this.notn(width).iaddn(1).ineg();
 5435    }
 5436    return this.clone();
 5437  };
 5438
 5439  BN.prototype.isNeg = function isNeg () {
 5440    return this.negative !== 0;
 5441  };
 5442
 5443  // Return negative clone of `this`
 5444  BN.prototype.neg = function neg () {
 5445    return this.clone().ineg();
 5446  };
 5447
 5448  BN.prototype.ineg = function ineg () {
 5449    if (!this.isZero()) {
 5450      this.negative ^= 1;
 5451    }
 5452
 5453    return this;
 5454  };
 5455
 5456  // Or `num` with `this` in-place
 5457  BN.prototype.iuor = function iuor (num) {
 5458    while (this.length < num.length) {
 5459      this.words[this.length++] = 0;
 5460    }
 5461
 5462    for (var i = 0; i < num.length; i++) {
 5463      this.words[i] = this.words[i] | num.words[i];
 5464    }
 5465
 5466    return this.strip();
 5467  };
 5468
 5469  BN.prototype.ior = function ior (num) {
 5470    assert((this.negative | num.negative) === 0);
 5471    return this.iuor(num);
 5472  };
 5473
 5474  // Or `num` with `this`
 5475  BN.prototype.or = function or (num) {
 5476    if (this.length > num.length) return this.clone().ior(num);
 5477    return num.clone().ior(this);
 5478  };
 5479
 5480  BN.prototype.uor = function uor (num) {
 5481    if (this.length > num.length) return this.clone().iuor(num);
 5482    return num.clone().iuor(this);
 5483  };
 5484
 5485  // And `num` with `this` in-place
 5486  BN.prototype.iuand = function iuand (num) {
 5487    // b = min-length(num, this)
 5488    var b;
 5489    if (this.length > num.length) {
 5490      b = num;
 5491    } else {
 5492      b = this;
 5493    }
 5494
 5495    for (var i = 0; i < b.length; i++) {
 5496      this.words[i] = this.words[i] & num.words[i];
 5497    }
 5498
 5499    this.length = b.length;
 5500
 5501    return this.strip();
 5502  };
 5503
 5504  BN.prototype.iand = function iand (num) {
 5505    assert((this.negative | num.negative) === 0);
 5506    return this.iuand(num);
 5507  };
 5508
 5509  // And `num` with `this`
 5510  BN.prototype.and = function and (num) {
 5511    if (this.length > num.length) return this.clone().iand(num);
 5512    return num.clone().iand(this);
 5513  };
 5514
 5515  BN.prototype.uand = function uand (num) {
 5516    if (this.length > num.length) return this.clone().iuand(num);
 5517    return num.clone().iuand(this);
 5518  };
 5519
 5520  // Xor `num` with `this` in-place
 5521  BN.prototype.iuxor = function iuxor (num) {
 5522    // a.length > b.length
 5523    var a;
 5524    var b;
 5525    if (this.length > num.length) {
 5526      a = this;
 5527      b = num;
 5528    } else {
 5529      a = num;
 5530      b = this;
 5531    }
 5532
 5533    for (var i = 0; i < b.length; i++) {
 5534      this.words[i] = a.words[i] ^ b.words[i];
 5535    }
 5536
 5537    if (this !== a) {
 5538      for (; i < a.length; i++) {
 5539        this.words[i] = a.words[i];
 5540      }
 5541    }
 5542
 5543    this.length = a.length;
 5544
 5545    return this.strip();
 5546  };
 5547
 5548  BN.prototype.ixor = function ixor (num) {
 5549    assert((this.negative | num.negative) === 0);
 5550    return this.iuxor(num);
 5551  };
 5552
 5553  // Xor `num` with `this`
 5554  BN.prototype.xor = function xor (num) {
 5555    if (this.length > num.length) return this.clone().ixor(num);
 5556    return num.clone().ixor(this);
 5557  };
 5558
 5559  BN.prototype.uxor = function uxor (num) {
 5560    if (this.length > num.length) return this.clone().iuxor(num);
 5561    return num.clone().iuxor(this);
 5562  };
 5563
 5564  // Not ``this`` with ``width`` bitwidth
 5565  BN.prototype.inotn = function inotn (width) {
 5566    assert(typeof width === 'number' && width >= 0);
 5567
 5568    var bytesNeeded = Math.ceil(width / 26) | 0;
 5569    var bitsLeft = width % 26;
 5570
 5571    // Extend the buffer with leading zeroes
 5572    this._expand(bytesNeeded);
 5573
 5574    if (bitsLeft > 0) {
 5575      bytesNeeded--;
 5576    }
 5577
 5578    // Handle complete words
 5579    for (var i = 0; i < bytesNeeded; i++) {
 5580      this.words[i] = ~this.words[i] & 0x3ffffff;
 5581    }
 5582
 5583    // Handle the residue
 5584    if (bitsLeft > 0) {
 5585      this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
 5586    }
 5587
 5588    // And remove leading zeroes
 5589    return this.strip();
 5590  };
 5591
 5592  BN.prototype.notn = function notn (width) {
 5593    return this.clone().inotn(width);
 5594  };
 5595
 5596  // Set `bit` of `this`
 5597  BN.prototype.setn = function setn (bit, val) {
 5598    assert(typeof bit === 'number' && bit >= 0);
 5599
 5600    var off = (bit / 26) | 0;
 5601    var wbit = bit % 26;
 5602
 5603    this._expand(off + 1);
 5604
 5605    if (val) {
 5606      this.words[off] = this.words[off] | (1 << wbit);
 5607    } else {
 5608      this.words[off] = this.words[off] & ~(1 << wbit);
 5609    }
 5610
 5611    return this.strip();
 5612  };
 5613
 5614  // Add `num` to `this` in-place
 5615  BN.prototype.iadd = function iadd (num) {
 5616    var r;
 5617
 5618    // negative + positive
 5619    if (this.negative !== 0 && num.negative === 0) {
 5620      this.negative = 0;
 5621      r = this.isub(num);
 5622      this.negative ^= 1;
 5623      return this._normSign();
 5624
 5625    // positive + negative
 5626    } else if (this.negative === 0 && num.negative !== 0) {
 5627      num.negative = 0;
 5628      r = this.isub(num);
 5629      num.negative = 1;
 5630      return r._normSign();
 5631    }
 5632
 5633    // a.length > b.length
 5634    var a, b;
 5635    if (this.length > num.length) {
 5636      a = this;
 5637      b = num;
 5638    } else {
 5639      a = num;
 5640      b = this;
 5641    }
 5642
 5643    var carry = 0;
 5644    for (var i = 0; i < b.length; i++) {
 5645      r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
 5646      this.words[i] = r & 0x3ffffff;
 5647      carry = r >>> 26;
 5648    }
 5649    for (; carry !== 0 && i < a.length; i++) {
 5650      r = (a.words[i] | 0) + carry;
 5651      this.words[i] = r & 0x3ffffff;
 5652      carry = r >>> 26;
 5653    }
 5654
 5655    this.length = a.length;
 5656    if (carry !== 0) {
 5657      this.words[this.length] = carry;
 5658      this.length++;
 5659    // Copy the rest of the words
 5660    } else if (a !== this) {
 5661      for (; i < a.length; i++) {
 5662        this.words[i] = a.words[i];
 5663      }
 5664    }
 5665
 5666    return this;
 5667  };
 5668
 5669  // Add `num` to `this`
 5670  BN.prototype.add = function add (num) {
 5671    var res;
 5672    if (num.negative !== 0 && this.negative === 0) {
 5673      num.negative = 0;
 5674      res = this.sub(num);
 5675      num.negative ^= 1;
 5676      return res;
 5677    } else if (num.negative === 0 && this.negative !== 0) {
 5678      this.negative = 0;
 5679      res = num.sub(this);
 5680      this.negative = 1;
 5681      return res;
 5682    }
 5683
 5684    if (this.length > num.length) return this.clone().iadd(num);
 5685
 5686    return num.clone().iadd(this);
 5687  };
 5688
 5689  // Subtract `num` from `this` in-place
 5690  BN.prototype.isub = function isub (num) {
 5691    // this - (-num) = this + num
 5692    if (num.negative !== 0) {
 5693      num.negative = 0;
 5694      var r = this.iadd(num);
 5695      num.negative = 1;
 5696      return r._normSign();
 5697
 5698    // -this - num = -(this + num)
 5699    } else if (this.negative !== 0) {
 5700      this.negative = 0;
 5701      this.iadd(num);
 5702      this.negative = 1;
 5703      return this._normSign();
 5704    }
 5705
 5706    // At this point both numbers are positive
 5707    var cmp = this.cmp(num);
 5708
 5709    // Optimization - zeroify
 5710    if (cmp === 0) {
 5711      this.negative = 0;
 5712      this.length = 1;
 5713      this.words[0] = 0;
 5714      return this;
 5715    }
 5716
 5717    // a > b
 5718    var a, b;
 5719    if (cmp > 0) {
 5720      a = this;
 5721      b = num;
 5722    } else {
 5723      a = num;
 5724      b = this;
 5725    }
 5726
 5727    var carry = 0;
 5728    for (var i = 0; i < b.length; i++) {
 5729      r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
 5730      carry = r >> 26;
 5731      this.words[i] = r & 0x3ffffff;
 5732    }
 5733    for (; carry !== 0 && i < a.length; i++) {
 5734      r = (a.words[i] | 0) + carry;
 5735      carry = r >> 26;
 5736      this.words[i] = r & 0x3ffffff;
 5737    }
 5738
 5739    // Copy rest of the words
 5740    if (carry === 0 && i < a.length && a !== this) {
 5741      for (; i < a.length; i++) {
 5742        this.words[i] = a.words[i];
 5743      }
 5744    }
 5745
 5746    this.length = Math.max(this.length, i);
 5747
 5748    if (a !== this) {
 5749      this.negative = 1;
 5750    }
 5751
 5752    return this.strip();
 5753  };
 5754
 5755  // Subtract `num` from `this`
 5756  BN.prototype.sub = function sub (num) {
 5757    return this.clone().isub(num);
 5758  };
 5759
 5760  function smallMulTo (self, num, out) {
 5761    out.negative = num.negative ^ self.negative;
 5762    var len = (self.length + num.length) | 0;
 5763    out.length = len;
 5764    len = (len - 1) | 0;
 5765
 5766    // Peel one iteration (compiler can't do it, because of code complexity)
 5767    var a = self.words[0] | 0;
 5768    var b = num.words[0] | 0;
 5769    var r = a * b;
 5770
 5771    var lo = r & 0x3ffffff;
 5772    var carry = (r / 0x4000000) | 0;
 5773    out.words[0] = lo;
 5774
 5775    for (var k = 1; k < len; k++) {
 5776      // Sum all words with the same `i + j = k` and accumulate `ncarry`,
 5777      // note that ncarry could be >= 0x3ffffff
 5778      var ncarry = carry >>> 26;
 5779      var rword = carry & 0x3ffffff;
 5780      var maxJ = Math.min(k, num.length - 1);
 5781      for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
 5782        var i = (k - j) | 0;
 5783        a = self.words[i] | 0;
 5784        b = num.words[j] | 0;
 5785        r = a * b + rword;
 5786        ncarry += (r / 0x4000000) | 0;
 5787        rword = r & 0x3ffffff;
 5788      }
 5789      out.words[k] = rword | 0;
 5790      carry = ncarry | 0;
 5791    }
 5792    if (carry !== 0) {
 5793      out.words[k] = carry | 0;
 5794    } else {
 5795      out.length--;
 5796    }
 5797
 5798    return out.strip();
 5799  }
 5800
 5801  // TODO(indutny): it may be reasonable to omit it for users who don't need
 5802  // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
 5803  // multiplication (like elliptic secp256k1).
 5804  var comb10MulTo = function comb10MulTo (self, num, out) {
 5805    var a = self.words;
 5806    var b = num.words;
 5807    var o = out.words;
 5808    var c = 0;
 5809    var lo;
 5810    var mid;
 5811    var hi;
 5812    var a0 = a[0] | 0;
 5813    var al0 = a0 & 0x1fff;
 5814    var ah0 = a0 >>> 13;
 5815    var a1 = a[1] | 0;
 5816    var al1 = a1 & 0x1fff;
 5817    var ah1 = a1 >>> 13;
 5818    var a2 = a[2] | 0;
 5819    var al2 = a2 & 0x1fff;
 5820    var ah2 = a2 >>> 13;
 5821    var a3 = a[3] | 0;
 5822    var al3 = a3 & 0x1fff;
 5823    var ah3 = a3 >>> 13;
 5824    var a4 = a[4] | 0;
 5825    var al4 = a4 & 0x1fff;
 5826    var ah4 = a4 >>> 13;
 5827    var a5 = a[5] | 0;
 5828    var al5 = a5 & 0x1fff;
 5829    var ah5 = a5 >>> 13;
 5830    var a6 = a[6] | 0;
 5831    var al6 = a6 & 0x1fff;
 5832    var ah6 = a6 >>> 13;
 5833    var a7 = a[7] | 0;
 5834    var al7 = a7 & 0x1fff;
 5835    var ah7 = a7 >>> 13;
 5836    var a8 = a[8] | 0;
 5837    var al8 = a8 & 0x1fff;
 5838    var ah8 = a8 >>> 13;
 5839    var a9 = a[9] | 0;
 5840    var al9 = a9 & 0x1fff;
 5841    var ah9 = a9 >>> 13;
 5842    var b0 = b[0] | 0;
 5843    var bl0 = b0 & 0x1fff;
 5844    var bh0 = b0 >>> 13;
 5845    var b1 = b[1] | 0;
 5846    var bl1 = b1 & 0x1fff;
 5847    var bh1 = b1 >>> 13;
 5848    var b2 = b[2] | 0;
 5849    var bl2 = b2 & 0x1fff;
 5850    var bh2 = b2 >>> 13;
 5851    var b3 = b[3] | 0;
 5852    var bl3 = b3 & 0x1fff;
 5853    var bh3 = b3 >>> 13;
 5854    var b4 = b[4] | 0;
 5855    var bl4 = b4 & 0x1fff;
 5856    var bh4 = b4 >>> 13;
 5857    var b5 = b[5] | 0;
 5858    var bl5 = b5 & 0x1fff;
 5859    var bh5 = b5 >>> 13;
 5860    var b6 = b[6] | 0;
 5861    var bl6 = b6 & 0x1fff;
 5862    var bh6 = b6 >>> 13;
 5863    var b7 = b[7] | 0;
 5864    var bl7 = b7 & 0x1fff;
 5865    var bh7 = b7 >>> 13;
 5866    var b8 = b[8] | 0;
 5867    var bl8 = b8 & 0x1fff;
 5868    var bh8 = b8 >>> 13;
 5869    var b9 = b[9] | 0;
 5870    var bl9 = b9 & 0x1fff;
 5871    var bh9 = b9 >>> 13;
 5872
 5873    out.negative = self.negative ^ num.negative;
 5874    out.length = 19;
 5875    /* k = 0 */
 5876    lo = Math.imul(al0, bl0);
 5877    mid = Math.imul(al0, bh0);
 5878    mid = (mid + Math.imul(ah0, bl0)) | 0;
 5879    hi = Math.imul(ah0, bh0);
 5880    var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 5881    c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
 5882    w0 &= 0x3ffffff;
 5883    /* k = 1 */
 5884    lo = Math.imul(al1, bl0);
 5885    mid = Math.imul(al1, bh0);
 5886    mid = (mid + Math.imul(ah1, bl0)) | 0;
 5887    hi = Math.imul(ah1, bh0);
 5888    lo = (lo + Math.imul(al0, bl1)) | 0;
 5889    mid = (mid + Math.imul(al0, bh1)) | 0;
 5890    mid = (mid + Math.imul(ah0, bl1)) | 0;
 5891    hi = (hi + Math.imul(ah0, bh1)) | 0;
 5892    var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 5893    c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
 5894    w1 &= 0x3ffffff;
 5895    /* k = 2 */
 5896    lo = Math.imul(al2, bl0);
 5897    mid = Math.imul(al2, bh0);
 5898    mid = (mid + Math.imul(ah2, bl0)) | 0;
 5899    hi = Math.imul(ah2, bh0);
 5900    lo = (lo + Math.imul(al1, bl1)) | 0;
 5901    mid = (mid + Math.imul(al1, bh1)) | 0;
 5902    mid = (mid + Math.imul(ah1, bl1)) | 0;
 5903    hi = (hi + Math.imul(ah1, bh1)) | 0;
 5904    lo = (lo + Math.imul(al0, bl2)) | 0;
 5905    mid = (mid + Math.imul(al0, bh2)) | 0;
 5906    mid = (mid + Math.imul(ah0, bl2)) | 0;
 5907    hi = (hi + Math.imul(ah0, bh2)) | 0;
 5908    var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 5909    c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
 5910    w2 &= 0x3ffffff;
 5911    /* k = 3 */
 5912    lo = Math.imul(al3, bl0);
 5913    mid = Math.imul(al3, bh0);
 5914    mid = (mid + Math.imul(ah3, bl0)) | 0;
 5915    hi = Math.imul(ah3, bh0);
 5916    lo = (lo + Math.imul(al2, bl1)) | 0;
 5917    mid = (mid + Math.imul(al2, bh1)) | 0;
 5918    mid = (mid + Math.imul(ah2, bl1)) | 0;
 5919    hi = (hi + Math.imul(ah2, bh1)) | 0;
 5920    lo = (lo + Math.imul(al1, bl2)) | 0;
 5921    mid = (mid + Math.imul(al1, bh2)) | 0;
 5922    mid = (mid + Math.imul(ah1, bl2)) | 0;
 5923    hi = (hi + Math.imul(ah1, bh2)) | 0;
 5924    lo = (lo + Math.imul(al0, bl3)) | 0;
 5925    mid = (mid + Math.imul(al0, bh3)) | 0;
 5926    mid = (mid + Math.imul(ah0, bl3)) | 0;
 5927    hi = (hi + Math.imul(ah0, bh3)) | 0;
 5928    var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 5929    c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
 5930    w3 &= 0x3ffffff;
 5931    /* k = 4 */
 5932    lo = Math.imul(al4, bl0);
 5933    mid = Math.imul(al4, bh0);
 5934    mid = (mid + Math.imul(ah4, bl0)) | 0;
 5935    hi = Math.imul(ah4, bh0);
 5936    lo = (lo + Math.imul(al3, bl1)) | 0;
 5937    mid = (mid + Math.imul(al3, bh1)) | 0;
 5938    mid = (mid + Math.imul(ah3, bl1)) | 0;
 5939    hi = (hi + Math.imul(ah3, bh1)) | 0;
 5940    lo = (lo + Math.imul(al2, bl2)) | 0;
 5941    mid = (mid + Math.imul(al2, bh2)) | 0;
 5942    mid = (mid + Math.imul(ah2, bl2)) | 0;
 5943    hi = (hi + Math.imul(ah2, bh2)) | 0;
 5944    lo = (lo + Math.imul(al1, bl3)) | 0;
 5945    mid = (mid + Math.imul(al1, bh3)) | 0;
 5946    mid = (mid + Math.imul(ah1, bl3)) | 0;
 5947    hi = (hi + Math.imul(ah1, bh3)) | 0;
 5948    lo = (lo + Math.imul(al0, bl4)) | 0;
 5949    mid = (mid + Math.imul(al0, bh4)) | 0;
 5950    mid = (mid + Math.imul(ah0, bl4)) | 0;
 5951    hi = (hi + Math.imul(ah0, bh4)) | 0;
 5952    var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 5953    c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
 5954    w4 &= 0x3ffffff;
 5955    /* k = 5 */
 5956    lo = Math.imul(al5, bl0);
 5957    mid = Math.imul(al5, bh0);
 5958    mid = (mid + Math.imul(ah5, bl0)) | 0;
 5959    hi = Math.imul(ah5, bh0);
 5960    lo = (lo + Math.imul(al4, bl1)) | 0;
 5961    mid = (mid + Math.imul(al4, bh1)) | 0;
 5962    mid = (mid + Math.imul(ah4, bl1)) | 0;
 5963    hi = (hi + Math.imul(ah4, bh1)) | 0;
 5964    lo = (lo + Math.imul(al3, bl2)) | 0;
 5965    mid = (mid + Math.imul(al3, bh2)) | 0;
 5966    mid = (mid + Math.imul(ah3, bl2)) | 0;
 5967    hi = (hi + Math.imul(ah3, bh2)) | 0;
 5968    lo = (lo + Math.imul(al2, bl3)) | 0;
 5969    mid = (mid + Math.imul(al2, bh3)) | 0;
 5970    mid = (mid + Math.imul(ah2, bl3)) | 0;
 5971    hi = (hi + Math.imul(ah2, bh3)) | 0;
 5972    lo = (lo + Math.imul(al1, bl4)) | 0;
 5973    mid = (mid + Math.imul(al1, bh4)) | 0;
 5974    mid = (mid + Math.imul(ah1, bl4)) | 0;
 5975    hi = (hi + Math.imul(ah1, bh4)) | 0;
 5976    lo = (lo + Math.imul(al0, bl5)) | 0;
 5977    mid = (mid + Math.imul(al0, bh5)) | 0;
 5978    mid = (mid + Math.imul(ah0, bl5)) | 0;
 5979    hi = (hi + Math.imul(ah0, bh5)) | 0;
 5980    var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 5981    c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
 5982    w5 &= 0x3ffffff;
 5983    /* k = 6 */
 5984    lo = Math.imul(al6, bl0);
 5985    mid = Math.imul(al6, bh0);
 5986    mid = (mid + Math.imul(ah6, bl0)) | 0;
 5987    hi = Math.imul(ah6, bh0);
 5988    lo = (lo + Math.imul(al5, bl1)) | 0;
 5989    mid = (mid + Math.imul(al5, bh1)) | 0;
 5990    mid = (mid + Math.imul(ah5, bl1)) | 0;
 5991    hi = (hi + Math.imul(ah5, bh1)) | 0;
 5992    lo = (lo + Math.imul(al4, bl2)) | 0;
 5993    mid = (mid + Math.imul(al4, bh2)) | 0;
 5994    mid = (mid + Math.imul(ah4, bl2)) | 0;
 5995    hi = (hi + Math.imul(ah4, bh2)) | 0;
 5996    lo = (lo + Math.imul(al3, bl3)) | 0;
 5997    mid = (mid + Math.imul(al3, bh3)) | 0;
 5998    mid = (mid + Math.imul(ah3, bl3)) | 0;
 5999    hi = (hi + Math.imul(ah3, bh3)) | 0;
 6000    lo = (lo + Math.imul(al2, bl4)) | 0;
 6001    mid = (mid + Math.imul(al2, bh4)) | 0;
 6002    mid = (mid + Math.imul(ah2, bl4)) | 0;
 6003    hi = (hi + Math.imul(ah2, bh4)) | 0;
 6004    lo = (lo + Math.imul(al1, bl5)) | 0;
 6005    mid = (mid + Math.imul(al1, bh5)) | 0;
 6006    mid = (mid + Math.imul(ah1, bl5)) | 0;
 6007    hi = (hi + Math.imul(ah1, bh5)) | 0;
 6008    lo = (lo + Math.imul(al0, bl6)) | 0;
 6009    mid = (mid + Math.imul(al0, bh6)) | 0;
 6010    mid = (mid + Math.imul(ah0, bl6)) | 0;
 6011    hi = (hi + Math.imul(ah0, bh6)) | 0;
 6012    var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 6013    c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
 6014    w6 &= 0x3ffffff;
 6015    /* k = 7 */
 6016    lo = Math.imul(al7, bl0);
 6017    mid = Math.imul(al7, bh0);
 6018    mid = (mid + Math.imul(ah7, bl0)) | 0;
 6019    hi = Math.imul(ah7, bh0);
 6020    lo = (lo + Math.imul(al6, bl1)) | 0;
 6021    mid = (mid + Math.imul(al6, bh1)) | 0;
 6022    mid = (mid + Math.imul(ah6, bl1)) | 0;
 6023    hi = (hi + Math.imul(ah6, bh1)) | 0;
 6024    lo = (lo + Math.imul(al5, bl2)) | 0;
 6025    mid = (mid + Math.imul(al5, bh2)) | 0;
 6026    mid = (mid + Math.imul(ah5, bl2)) | 0;
 6027    hi = (hi + Math.imul(ah5, bh2)) | 0;
 6028    lo = (lo + Math.imul(al4, bl3)) | 0;
 6029    mid = (mid + Math.imul(al4, bh3)) | 0;
 6030    mid = (mid + Math.imul(ah4, bl3)) | 0;
 6031    hi = (hi + Math.imul(ah4, bh3)) | 0;
 6032    lo = (lo + Math.imul(al3, bl4)) | 0;
 6033    mid = (mid + Math.imul(al3, bh4)) | 0;
 6034    mid = (mid + Math.imul(ah3, bl4)) | 0;
 6035    hi = (hi + Math.imul(ah3, bh4)) | 0;
 6036    lo = (lo + Math.imul(al2, bl5)) | 0;
 6037    mid = (mid + Math.imul(al2, bh5)) | 0;
 6038    mid = (mid + Math.imul(ah2, bl5)) | 0;
 6039    hi = (hi + Math.imul(ah2, bh5)) | 0;
 6040    lo = (lo + Math.imul(al1, bl6)) | 0;
 6041    mid = (mid + Math.imul(al1, bh6)) | 0;
 6042    mid = (mid + Math.imul(ah1, bl6)) | 0;
 6043    hi = (hi + Math.imul(ah1, bh6)) | 0;
 6044    lo = (lo + Math.imul(al0, bl7)) | 0;
 6045    mid = (mid + Math.imul(al0, bh7)) | 0;
 6046    mid = (mid + Math.imul(ah0, bl7)) | 0;
 6047    hi = (hi + Math.imul(ah0, bh7)) | 0;
 6048    var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 6049    c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
 6050    w7 &= 0x3ffffff;
 6051    /* k = 8 */
 6052    lo = Math.imul(al8, bl0);
 6053    mid = Math.imul(al8, bh0);
 6054    mid = (mid + Math.imul(ah8, bl0)) | 0;
 6055    hi = Math.imul(ah8, bh0);
 6056    lo = (lo + Math.imul(al7, bl1)) | 0;
 6057    mid = (mid + Math.imul(al7, bh1)) | 0;
 6058    mid = (mid + Math.imul(ah7, bl1)) | 0;
 6059    hi = (hi + Math.imul(ah7, bh1)) | 0;
 6060    lo = (lo + Math.imul(al6, bl2)) | 0;
 6061    mid = (mid + Math.imul(al6, bh2)) | 0;
 6062    mid = (mid + Math.imul(ah6, bl2)) | 0;
 6063    hi = (hi + Math.imul(ah6, bh2)) | 0;
 6064    lo = (lo + Math.imul(al5, bl3)) | 0;
 6065    mid = (mid + Math.imul(al5, bh3)) | 0;
 6066    mid = (mid + Math.imul(ah5, bl3)) | 0;
 6067    hi = (hi + Math.imul(ah5, bh3)) | 0;
 6068    lo = (lo + Math.imul(al4, bl4)) | 0;
 6069    mid = (mid + Math.imul(al4, bh4)) | 0;
 6070    mid = (mid + Math.imul(ah4, bl4)) | 0;
 6071    hi = (hi + Math.imul(ah4, bh4)) | 0;
 6072    lo = (lo + Math.imul(al3, bl5)) | 0;
 6073    mid = (mid + Math.imul(al3, bh5)) | 0;
 6074    mid = (mid + Math.imul(ah3, bl5)) | 0;
 6075    hi = (hi + Math.imul(ah3, bh5)) | 0;
 6076    lo = (lo + Math.imul(al2, bl6)) | 0;
 6077    mid = (mid + Math.imul(al2, bh6)) | 0;
 6078    mid = (mid + Math.imul(ah2, bl6)) | 0;
 6079    hi = (hi + Math.imul(ah2, bh6)) | 0;
 6080    lo = (lo + Math.imul(al1, bl7)) | 0;
 6081    mid = (mid + Math.imul(al1, bh7)) | 0;
 6082    mid = (mid + Math.imul(ah1, bl7)) | 0;
 6083    hi = (hi + Math.imul(ah1, bh7)) | 0;
 6084    lo = (lo + Math.imul(al0, bl8)) | 0;
 6085    mid = (mid + Math.imul(al0, bh8)) | 0;
 6086    mid = (mid + Math.imul(ah0, bl8)) | 0;
 6087    hi = (hi + Math.imul(ah0, bh8)) | 0;
 6088    var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 6089    c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
 6090    w8 &= 0x3ffffff;
 6091    /* k = 9 */
 6092    lo = Math.imul(al9, bl0);
 6093    mid = Math.imul(al9, bh0);
 6094    mid = (mid + Math.imul(ah9, bl0)) | 0;
 6095    hi = Math.imul(ah9, bh0);
 6096    lo = (lo + Math.imul(al8, bl1)) | 0;
 6097    mid = (mid + Math.imul(al8, bh1)) | 0;
 6098    mid = (mid + Math.imul(ah8, bl1)) | 0;
 6099    hi = (hi + Math.imul(ah8, bh1)) | 0;
 6100    lo = (lo + Math.imul(al7, bl2)) | 0;
 6101    mid = (mid + Math.imul(al7, bh2)) | 0;
 6102    mid = (mid + Math.imul(ah7, bl2)) | 0;
 6103    hi = (hi + Math.imul(ah7, bh2)) | 0;
 6104    lo = (lo + Math.imul(al6, bl3)) | 0;
 6105    mid = (mid + Math.imul(al6, bh3)) | 0;
 6106    mid = (mid + Math.imul(ah6, bl3)) | 0;
 6107    hi = (hi + Math.imul(ah6, bh3)) | 0;
 6108    lo = (lo + Math.imul(al5, bl4)) | 0;
 6109    mid = (mid + Math.imul(al5, bh4)) | 0;
 6110    mid = (mid + Math.imul(ah5, bl4)) | 0;
 6111    hi = (hi + Math.imul(ah5, bh4)) | 0;
 6112    lo = (lo + Math.imul(al4, bl5)) | 0;
 6113    mid = (mid + Math.imul(al4, bh5)) | 0;
 6114    mid = (mid + Math.imul(ah4, bl5)) | 0;
 6115    hi = (hi + Math.imul(ah4, bh5)) | 0;
 6116    lo = (lo + Math.imul(al3, bl6)) | 0;
 6117    mid = (mid + Math.imul(al3, bh6)) | 0;
 6118    mid = (mid + Math.imul(ah3, bl6)) | 0;
 6119    hi = (hi + Math.imul(ah3, bh6)) | 0;
 6120    lo = (lo + Math.imul(al2, bl7)) | 0;
 6121    mid = (mid + Math.imul(al2, bh7)) | 0;
 6122    mid = (mid + Math.imul(ah2, bl7)) | 0;
 6123    hi = (hi + Math.imul(ah2, bh7)) | 0;
 6124    lo = (lo + Math.imul(al1, bl8)) | 0;
 6125    mid = (mid + Math.imul(al1, bh8)) | 0;
 6126    mid = (mid + Math.imul(ah1, bl8)) | 0;
 6127    hi = (hi + Math.imul(ah1, bh8)) | 0;
 6128    lo = (lo + Math.imul(al0, bl9)) | 0;
 6129    mid = (mid + Math.imul(al0, bh9)) | 0;
 6130    mid = (mid + Math.imul(ah0, bl9)) | 0;
 6131    hi = (hi + Math.imul(ah0, bh9)) | 0;
 6132    var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 6133    c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
 6134    w9 &= 0x3ffffff;
 6135    /* k = 10 */
 6136    lo = Math.imul(al9, bl1);
 6137    mid = Math.imul(al9, bh1);
 6138    mid = (mid + Math.imul(ah9, bl1)) | 0;
 6139    hi = Math.imul(ah9, bh1);
 6140    lo = (lo + Math.imul(al8, bl2)) | 0;
 6141    mid = (mid + Math.imul(al8, bh2)) | 0;
 6142    mid = (mid + Math.imul(ah8, bl2)) | 0;
 6143    hi = (hi + Math.imul(ah8, bh2)) | 0;
 6144    lo = (lo + Math.imul(al7, bl3)) | 0;
 6145    mid = (mid + Math.imul(al7, bh3)) | 0;
 6146    mid = (mid + Math.imul(ah7, bl3)) | 0;
 6147    hi = (hi + Math.imul(ah7, bh3)) | 0;
 6148    lo = (lo + Math.imul(al6, bl4)) | 0;
 6149    mid = (mid + Math.imul(al6, bh4)) | 0;
 6150    mid = (mid + Math.imul(ah6, bl4)) | 0;
 6151    hi = (hi + Math.imul(ah6, bh4)) | 0;
 6152    lo = (lo + Math.imul(al5, bl5)) | 0;
 6153    mid = (mid + Math.imul(al5, bh5)) | 0;
 6154    mid = (mid + Math.imul(ah5, bl5)) | 0;
 6155    hi = (hi + Math.imul(ah5, bh5)) | 0;
 6156    lo = (lo + Math.imul(al4, bl6)) | 0;
 6157    mid = (mid + Math.imul(al4, bh6)) | 0;
 6158    mid = (mid + Math.imul(ah4, bl6)) | 0;
 6159    hi = (hi + Math.imul(ah4, bh6)) | 0;
 6160    lo = (lo + Math.imul(al3, bl7)) | 0;
 6161    mid = (mid + Math.imul(al3, bh7)) | 0;
 6162    mid = (mid + Math.imul(ah3, bl7)) | 0;
 6163    hi = (hi + Math.imul(ah3, bh7)) | 0;
 6164    lo = (lo + Math.imul(al2, bl8)) | 0;
 6165    mid = (mid + Math.imul(al2, bh8)) | 0;
 6166    mid = (mid + Math.imul(ah2, bl8)) | 0;
 6167    hi = (hi + Math.imul(ah2, bh8)) | 0;
 6168    lo = (lo + Math.imul(al1, bl9)) | 0;
 6169    mid = (mid + Math.imul(al1, bh9)) | 0;
 6170    mid = (mid + Math.imul(ah1, bl9)) | 0;
 6171    hi = (hi + Math.imul(ah1, bh9)) | 0;
 6172    var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 6173    c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
 6174    w10 &= 0x3ffffff;
 6175    /* k = 11 */
 6176    lo = Math.imul(al9, bl2);
 6177    mid = Math.imul(al9, bh2);
 6178    mid = (mid + Math.imul(ah9, bl2)) | 0;
 6179    hi = Math.imul(ah9, bh2);
 6180    lo = (lo + Math.imul(al8, bl3)) | 0;
 6181    mid = (mid + Math.imul(al8, bh3)) | 0;
 6182    mid = (mid + Math.imul(ah8, bl3)) | 0;
 6183    hi = (hi + Math.imul(ah8, bh3)) | 0;
 6184    lo = (lo + Math.imul(al7, bl4)) | 0;
 6185    mid = (mid + Math.imul(al7, bh4)) | 0;
 6186    mid = (mid + Math.imul(ah7, bl4)) | 0;
 6187    hi = (hi + Math.imul(ah7, bh4)) | 0;
 6188    lo = (lo + Math.imul(al6, bl5)) | 0;
 6189    mid = (mid + Math.imul(al6, bh5)) | 0;
 6190    mid = (mid + Math.imul(ah6, bl5)) | 0;
 6191    hi = (hi + Math.imul(ah6, bh5)) | 0;
 6192    lo = (lo + Math.imul(al5, bl6)) | 0;
 6193    mid = (mid + Math.imul(al5, bh6)) | 0;
 6194    mid = (mid + Math.imul(ah5, bl6)) | 0;
 6195    hi = (hi + Math.imul(ah5, bh6)) | 0;
 6196    lo = (lo + Math.imul(al4, bl7)) | 0;
 6197    mid = (mid + Math.imul(al4, bh7)) | 0;
 6198    mid = (mid + Math.imul(ah4, bl7)) | 0;
 6199    hi = (hi + Math.imul(ah4, bh7)) | 0;
 6200    lo = (lo + Math.imul(al3, bl8)) | 0;
 6201    mid = (mid + Math.imul(al3, bh8)) | 0;
 6202    mid = (mid + Math.imul(ah3, bl8)) | 0;
 6203    hi = (hi + Math.imul(ah3, bh8)) | 0;
 6204    lo = (lo + Math.imul(al2, bl9)) | 0;
 6205    mid = (mid + Math.imul(al2, bh9)) | 0;
 6206    mid = (mid + Math.imul(ah2, bl9)) | 0;
 6207    hi = (hi + Math.imul(ah2, bh9)) | 0;
 6208    var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 6209    c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
 6210    w11 &= 0x3ffffff;
 6211    /* k = 12 */
 6212    lo = Math.imul(al9, bl3);
 6213    mid = Math.imul(al9, bh3);
 6214    mid = (mid + Math.imul(ah9, bl3)) | 0;
 6215    hi = Math.imul(ah9, bh3);
 6216    lo = (lo + Math.imul(al8, bl4)) | 0;
 6217    mid = (mid + Math.imul(al8, bh4)) | 0;
 6218    mid = (mid + Math.imul(ah8, bl4)) | 0;
 6219    hi = (hi + Math.imul(ah8, bh4)) | 0;
 6220    lo = (lo + Math.imul(al7, bl5)) | 0;
 6221    mid = (mid + Math.imul(al7, bh5)) | 0;
 6222    mid = (mid + Math.imul(ah7, bl5)) | 0;
 6223    hi = (hi + Math.imul(ah7, bh5)) | 0;
 6224    lo = (lo + Math.imul(al6, bl6)) | 0;
 6225    mid = (mid + Math.imul(al6, bh6)) | 0;
 6226    mid = (mid + Math.imul(ah6, bl6)) | 0;
 6227    hi = (hi + Math.imul(ah6, bh6)) | 0;
 6228    lo = (lo + Math.imul(al5, bl7)) | 0;
 6229    mid = (mid + Math.imul(al5, bh7)) | 0;
 6230    mid = (mid + Math.imul(ah5, bl7)) | 0;
 6231    hi = (hi + Math.imul(ah5, bh7)) | 0;
 6232    lo = (lo + Math.imul(al4, bl8)) | 0;
 6233    mid = (mid + Math.imul(al4, bh8)) | 0;
 6234    mid = (mid + Math.imul(ah4, bl8)) | 0;
 6235    hi = (hi + Math.imul(ah4, bh8)) | 0;
 6236    lo = (lo + Math.imul(al3, bl9)) | 0;
 6237    mid = (mid + Math.imul(al3, bh9)) | 0;
 6238    mid = (mid + Math.imul(ah3, bl9)) | 0;
 6239    hi = (hi + Math.imul(ah3, bh9)) | 0;
 6240    var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 6241    c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
 6242    w12 &= 0x3ffffff;
 6243    /* k = 13 */
 6244    lo = Math.imul(al9, bl4);
 6245    mid = Math.imul(al9, bh4);
 6246    mid = (mid + Math.imul(ah9, bl4)) | 0;
 6247    hi = Math.imul(ah9, bh4);
 6248    lo = (lo + Math.imul(al8, bl5)) | 0;
 6249    mid = (mid + Math.imul(al8, bh5)) | 0;
 6250    mid = (mid + Math.imul(ah8, bl5)) | 0;
 6251    hi = (hi + Math.imul(ah8, bh5)) | 0;
 6252    lo = (lo + Math.imul(al7, bl6)) | 0;
 6253    mid = (mid + Math.imul(al7, bh6)) | 0;
 6254    mid = (mid + Math.imul(ah7, bl6)) | 0;
 6255    hi = (hi + Math.imul(ah7, bh6)) | 0;
 6256    lo = (lo + Math.imul(al6, bl7)) | 0;
 6257    mid = (mid + Math.imul(al6, bh7)) | 0;
 6258    mid = (mid + Math.imul(ah6, bl7)) | 0;
 6259    hi = (hi + Math.imul(ah6, bh7)) | 0;
 6260    lo = (lo + Math.imul(al5, bl8)) | 0;
 6261    mid = (mid + Math.imul(al5, bh8)) | 0;
 6262    mid = (mid + Math.imul(ah5, bl8)) | 0;
 6263    hi = (hi + Math.imul(ah5, bh8)) | 0;
 6264    lo = (lo + Math.imul(al4, bl9)) | 0;
 6265    mid = (mid + Math.imul(al4, bh9)) | 0;
 6266    mid = (mid + Math.imul(ah4, bl9)) | 0;
 6267    hi = (hi + Math.imul(ah4, bh9)) | 0;
 6268    var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 6269    c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
 6270    w13 &= 0x3ffffff;
 6271    /* k = 14 */
 6272    lo = Math.imul(al9, bl5);
 6273    mid = Math.imul(al9, bh5);
 6274    mid = (mid + Math.imul(ah9, bl5)) | 0;
 6275    hi = Math.imul(ah9, bh5);
 6276    lo = (lo + Math.imul(al8, bl6)) | 0;
 6277    mid = (mid + Math.imul(al8, bh6)) | 0;
 6278    mid = (mid + Math.imul(ah8, bl6)) | 0;
 6279    hi = (hi + Math.imul(ah8, bh6)) | 0;
 6280    lo = (lo + Math.imul(al7, bl7)) | 0;
 6281    mid = (mid + Math.imul(al7, bh7)) | 0;
 6282    mid = (mid + Math.imul(ah7, bl7)) | 0;
 6283    hi = (hi + Math.imul(ah7, bh7)) | 0;
 6284    lo = (lo + Math.imul(al6, bl8)) | 0;
 6285    mid = (mid + Math.imul(al6, bh8)) | 0;
 6286    mid = (mid + Math.imul(ah6, bl8)) | 0;
 6287    hi = (hi + Math.imul(ah6, bh8)) | 0;
 6288    lo = (lo + Math.imul(al5, bl9)) | 0;
 6289    mid = (mid + Math.imul(al5, bh9)) | 0;
 6290    mid = (mid + Math.imul(ah5, bl9)) | 0;
 6291    hi = (hi + Math.imul(ah5, bh9)) | 0;
 6292    var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 6293    c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
 6294    w14 &= 0x3ffffff;
 6295    /* k = 15 */
 6296    lo = Math.imul(al9, bl6);
 6297    mid = Math.imul(al9, bh6);
 6298    mid = (mid + Math.imul(ah9, bl6)) | 0;
 6299    hi = Math.imul(ah9, bh6);
 6300    lo = (lo + Math.imul(al8, bl7)) | 0;
 6301    mid = (mid + Math.imul(al8, bh7)) | 0;
 6302    mid = (mid + Math.imul(ah8, bl7)) | 0;
 6303    hi = (hi + Math.imul(ah8, bh7)) | 0;
 6304    lo = (lo + Math.imul(al7, bl8)) | 0;
 6305    mid = (mid + Math.imul(al7, bh8)) | 0;
 6306    mid = (mid + Math.imul(ah7, bl8)) | 0;
 6307    hi = (hi + Math.imul(ah7, bh8)) | 0;
 6308    lo = (lo + Math.imul(al6, bl9)) | 0;
 6309    mid = (mid + Math.imul(al6, bh9)) | 0;
 6310    mid = (mid + Math.imul(ah6, bl9)) | 0;
 6311    hi = (hi + Math.imul(ah6, bh9)) | 0;
 6312    var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 6313    c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
 6314    w15 &= 0x3ffffff;
 6315    /* k = 16 */
 6316    lo = Math.imul(al9, bl7);
 6317    mid = Math.imul(al9, bh7);
 6318    mid = (mid + Math.imul(ah9, bl7)) | 0;
 6319    hi = Math.imul(ah9, bh7);
 6320    lo = (lo + Math.imul(al8, bl8)) | 0;
 6321    mid = (mid + Math.imul(al8, bh8)) | 0;
 6322    mid = (mid + Math.imul(ah8, bl8)) | 0;
 6323    hi = (hi + Math.imul(ah8, bh8)) | 0;
 6324    lo = (lo + Math.imul(al7, bl9)) | 0;
 6325    mid = (mid + Math.imul(al7, bh9)) | 0;
 6326    mid = (mid + Math.imul(ah7, bl9)) | 0;
 6327    hi = (hi + Math.imul(ah7, bh9)) | 0;
 6328    var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 6329    c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
 6330    w16 &= 0x3ffffff;
 6331    /* k = 17 */
 6332    lo = Math.imul(al9, bl8);
 6333    mid = Math.imul(al9, bh8);
 6334    mid = (mid + Math.imul(ah9, bl8)) | 0;
 6335    hi = Math.imul(ah9, bh8);
 6336    lo = (lo + Math.imul(al8, bl9)) | 0;
 6337    mid = (mid + Math.imul(al8, bh9)) | 0;
 6338    mid = (mid + Math.imul(ah8, bl9)) | 0;
 6339    hi = (hi + Math.imul(ah8, bh9)) | 0;
 6340    var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 6341    c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
 6342    w17 &= 0x3ffffff;
 6343    /* k = 18 */
 6344    lo = Math.imul(al9, bl9);
 6345    mid = Math.imul(al9, bh9);
 6346    mid = (mid + Math.imul(ah9, bl9)) | 0;
 6347    hi = Math.imul(ah9, bh9);
 6348    var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
 6349    c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
 6350    w18 &= 0x3ffffff;
 6351    o[0] = w0;
 6352    o[1] = w1;
 6353    o[2] = w2;
 6354    o[3] = w3;
 6355    o[4] = w4;
 6356    o[5] = w5;
 6357    o[6] = w6;
 6358    o[7] = w7;
 6359    o[8] = w8;
 6360    o[9] = w9;
 6361    o[10] = w10;
 6362    o[11] = w11;
 6363    o[12] = w12;
 6364    o[13] = w13;
 6365    o[14] = w14;
 6366    o[15] = w15;
 6367    o[16] = w16;
 6368    o[17] = w17;
 6369    o[18] = w18;
 6370    if (c !== 0) {
 6371      o[19] = c;
 6372      out.length++;
 6373    }
 6374    return out;
 6375  };
 6376
 6377  // Polyfill comb
 6378  if (!Math.imul) {
 6379    comb10MulTo = smallMulTo;
 6380  }
 6381
 6382  function bigMulTo (self, num, out) {
 6383    out.negative = num.negative ^ self.negative;
 6384    out.length = self.length + num.length;
 6385
 6386    var carry = 0;
 6387    var hncarry = 0;
 6388    for (var k = 0; k < out.length - 1; k++) {
 6389      // Sum all words with the same `i + j = k` and accumulate `ncarry`,
 6390      // note that ncarry could be >= 0x3ffffff
 6391      var ncarry = hncarry;
 6392      hncarry = 0;
 6393      var rword = carry & 0x3ffffff;
 6394      var maxJ = Math.min(k, num.length - 1);
 6395      for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
 6396        var i = k - j;
 6397        var a = self.words[i] | 0;
 6398        var b = num.words[j] | 0;
 6399        var r = a * b;
 6400
 6401        var lo = r & 0x3ffffff;
 6402        ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
 6403        lo = (lo + rword) | 0;
 6404        rword = lo & 0x3ffffff;
 6405        ncarry = (ncarry + (lo >>> 26)) | 0;
 6406
 6407        hncarry += ncarry >>> 26;
 6408        ncarry &= 0x3ffffff;
 6409      }
 6410      out.words[k] = rword;
 6411      carry = ncarry;
 6412      ncarry = hncarry;
 6413    }
 6414    if (carry !== 0) {
 6415      out.words[k] = carry;
 6416    } else {
 6417      out.length--;
 6418    }
 6419
 6420    return out.strip();
 6421  }
 6422
 6423  function jumboMulTo (self, num, out) {
 6424    var fftm = new FFTM();
 6425    return fftm.mulp(self, num, out);
 6426  }
 6427
 6428  BN.prototype.mulTo = function mulTo (num, out) {
 6429    var res;
 6430    var len = this.length + num.length;
 6431    if (this.length === 10 && num.length === 10) {
 6432      res = comb10MulTo(this, num, out);
 6433    } else if (len < 63) {
 6434      res = smallMulTo(this, num, out);
 6435    } else if (len < 1024) {
 6436      res = bigMulTo(this, num, out);
 6437    } else {
 6438      res = jumboMulTo(this, num, out);
 6439    }
 6440
 6441    return res;
 6442  };
 6443
 6444  // Cooley-Tukey algorithm for FFT
 6445  // slightly revisited to rely on looping instead of recursion
 6446
 6447  function FFTM (x, y) {
 6448    this.x = x;
 6449    this.y = y;
 6450  }
 6451
 6452  FFTM.prototype.makeRBT = function makeRBT (N) {
 6453    var t = new Array(N);
 6454    var l = BN.prototype._countBits(N) - 1;
 6455    for (var i = 0; i < N; i++) {
 6456      t[i] = this.revBin(i, l, N);
 6457    }
 6458
 6459    return t;
 6460  };
 6461
 6462  // Returns binary-reversed representation of `x`
 6463  FFTM.prototype.revBin = function revBin (x, l, N) {
 6464    if (x === 0 || x === N - 1) return x;
 6465
 6466    var rb = 0;
 6467    for (var i = 0; i < l; i++) {
 6468      rb |= (x & 1) << (l - i - 1);
 6469      x >>= 1;
 6470    }
 6471
 6472    return rb;
 6473  };
 6474
 6475  // Performs "tweedling" phase, therefore 'emulating'
 6476  // behaviour of the recursive algorithm
 6477  FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
 6478    for (var i = 0; i < N; i++) {
 6479      rtws[i] = rws[rbt[i]];
 6480      itws[i] = iws[rbt[i]];
 6481    }
 6482  };
 6483
 6484  FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
 6485    this.permute(rbt, rws, iws, rtws, itws, N);
 6486
 6487    for (var s = 1; s < N; s <<= 1) {
 6488      var l = s << 1;
 6489
 6490      var rtwdf = Math.cos(2 * Math.PI / l);
 6491      var itwdf = Math.sin(2 * Math.PI / l);
 6492
 6493      for (var p = 0; p < N; p += l) {
 6494        var rtwdf_ = rtwdf;
 6495        var itwdf_ = itwdf;
 6496
 6497        for (var j = 0; j < s; j++) {
 6498          var re = rtws[p + j];
 6499          var ie = itws[p + j];
 6500
 6501          var ro = rtws[p + j + s];
 6502          var io = itws[p + j + s];
 6503
 6504          var rx = rtwdf_ * ro - itwdf_ * io;
 6505
 6506          io = rtwdf_ * io + itwdf_ * ro;
 6507          ro = rx;
 6508
 6509          rtws[p + j] = re + ro;
 6510          itws[p + j] = ie + io;
 6511
 6512          rtws[p + j + s] = re - ro;
 6513          itws[p + j + s] = ie - io;
 6514
 6515          /* jshint maxdepth : false */
 6516          if (j !== l) {
 6517            rx = rtwdf * rtwdf_ - itwdf * itwdf_;
 6518
 6519            itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
 6520            rtwdf_ = rx;
 6521          }
 6522        }
 6523      }
 6524    }
 6525  };
 6526
 6527  FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
 6528    var N = Math.max(m, n) | 1;
 6529    var odd = N & 1;
 6530    var i = 0;
 6531    for (N = N / 2 | 0; N; N = N >>> 1) {
 6532      i++;
 6533    }
 6534
 6535    return 1 << i + 1 + odd;
 6536  };
 6537
 6538  FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
 6539    if (N <= 1) return;
 6540
 6541    for (var i = 0; i < N / 2; i++) {
 6542      var t = rws[i];
 6543
 6544      rws[i] = rws[N - i - 1];
 6545      rws[N - i - 1] = t;
 6546
 6547      t = iws[i];
 6548
 6549      iws[i] = -iws[N - i - 1];
 6550      iws[N - i - 1] = -t;
 6551    }
 6552  };
 6553
 6554  FFTM.prototype.normalize13b = function normalize13b (ws, N) {
 6555    var carry = 0;
 6556    for (var i = 0; i < N / 2; i++) {
 6557      var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
 6558        Math.round(ws[2 * i] / N) +
 6559        carry;
 6560
 6561      ws[i] = w & 0x3ffffff;
 6562
 6563      if (w < 0x4000000) {
 6564        carry = 0;
 6565      } else {
 6566        carry = w / 0x4000000 | 0;
 6567      }
 6568    }
 6569
 6570    return ws;
 6571  };
 6572
 6573  FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
 6574    var carry = 0;
 6575    for (var i = 0; i < len; i++) {
 6576      carry = carry + (ws[i] | 0);
 6577
 6578      rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
 6579      rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
 6580    }
 6581
 6582    // Pad with zeroes
 6583    for (i = 2 * len; i < N; ++i) {
 6584      rws[i] = 0;
 6585    }
 6586
 6587    assert(carry === 0);
 6588    assert((carry & ~0x1fff) === 0);
 6589  };
 6590
 6591  FFTM.prototype.stub = function stub (N) {
 6592    var ph = new Array(N);
 6593    for (var i = 0; i < N; i++) {
 6594      ph[i] = 0;
 6595    }
 6596
 6597    return ph;
 6598  };
 6599
 6600  FFTM.prototype.mulp = function mulp (x, y, out) {
 6601    var N = 2 * this.guessLen13b(x.length, y.length);
 6602
 6603    var rbt = this.makeRBT(N);
 6604
 6605    var _ = this.stub(N);
 6606
 6607    var rws = new Array(N);
 6608    var rwst = new Array(N);
 6609    var iwst = new Array(N);
 6610
 6611    var nrws = new Array(N);
 6612    var nrwst = new Array(N);
 6613    var niwst = new Array(N);
 6614
 6615    var rmws = out.words;
 6616    rmws.length = N;
 6617
 6618    this.convert13b(x.words, x.length, rws, N);
 6619    this.convert13b(y.words, y.length, nrws, N);
 6620
 6621    this.transform(rws, _, rwst, iwst, N, rbt);
 6622    this.transform(nrws, _, nrwst, niwst, N, rbt);
 6623
 6624    for (var i = 0; i < N; i++) {
 6625      var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
 6626      iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
 6627      rwst[i] = rx;
 6628    }
 6629
 6630    this.conjugate(rwst, iwst, N);
 6631    this.transform(rwst, iwst, rmws, _, N, rbt);
 6632    this.conjugate(rmws, _, N);
 6633    this.normalize13b(rmws, N);
 6634
 6635    out.negative = x.negative ^ y.negative;
 6636    out.length = x.length + y.length;
 6637    return out.strip();
 6638  };
 6639
 6640  // Multiply `this` by `num`
 6641  BN.prototype.mul = function mul (num) {
 6642    var out = new BN(null);
 6643    out.words = new Array(this.length + num.length);
 6644    return this.mulTo(num, out);
 6645  };
 6646
 6647  // Multiply employing FFT
 6648  BN.prototype.mulf = function mulf (num) {
 6649    var out = new BN(null);
 6650    out.words = new Array(this.length + num.length);
 6651    return jumboMulTo(this, num, out);
 6652  };
 6653
 6654  // In-place Multiplication
 6655  BN.prototype.imul = function imul (num) {
 6656    return this.clone().mulTo(num, this);
 6657  };
 6658
 6659  BN.prototype.imuln = function imuln (num) {
 6660    assert(typeof num === 'number');
 6661    assert(num < 0x4000000);
 6662
 6663    // Carry
 6664    var carry = 0;
 6665    for (var i = 0; i < this.length; i++) {
 6666      var w = (this.words[i] | 0) * num;
 6667      var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
 6668      carry >>= 26;
 6669      carry += (w / 0x4000000) | 0;
 6670      // NOTE: lo is 27bit maximum
 6671      carry += lo >>> 26;
 6672      this.words[i] = lo & 0x3ffffff;
 6673    }
 6674
 6675    if (carry !== 0) {
 6676      this.words[i] = carry;
 6677      this.length++;
 6678    }
 6679
 6680    return this;
 6681  };
 6682
 6683  BN.prototype.muln = function muln (num) {
 6684    return this.clone().imuln(num);
 6685  };
 6686
 6687  // `this` * `this`
 6688  BN.prototype.sqr = function sqr () {
 6689    return this.mul(this);
 6690  };
 6691
 6692  // `this` * `this` in-place
 6693  BN.prototype.isqr = function isqr () {
 6694    return this.imul(this.clone());
 6695  };
 6696
 6697  // Math.pow(`this`, `num`)
 6698  BN.prototype.pow = function pow (num) {
 6699    var w = toBitArray(num);
 6700    if (w.length === 0) return new BN(1);
 6701
 6702    // Skip leading zeroes
 6703    var res = this;
 6704    for (var i = 0; i < w.length; i++, res = res.sqr()) {
 6705      if (w[i] !== 0) break;
 6706    }
 6707
 6708    if (++i < w.length) {
 6709      for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
 6710        if (w[i] === 0) continue;
 6711
 6712        res = res.mul(q);
 6713      }
 6714    }
 6715
 6716    return res;
 6717  };
 6718
 6719  // Shift-left in-place
 6720  BN.prototype.iushln = function iushln (bits) {
 6721    assert(typeof bits === 'number' && bits >= 0);
 6722    var r = bits % 26;
 6723    var s = (bits - r) / 26;
 6724    var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
 6725    var i;
 6726
 6727    if (r !== 0) {
 6728      var carry = 0;
 6729
 6730      for (i = 0; i < this.length; i++) {
 6731        var newCarry = this.words[i] & carryMask;
 6732        var c = ((this.words[i] | 0) - newCarry) << r;
 6733        this.words[i] = c | carry;
 6734        carry = newCarry >>> (26 - r);
 6735      }
 6736
 6737      if (carry) {
 6738        this.words[i] = carry;
 6739        this.length++;
 6740      }
 6741    }
 6742
 6743    if (s !== 0) {
 6744      for (i = this.length - 1; i >= 0; i--) {
 6745        this.words[i + s] = this.words[i];
 6746      }
 6747
 6748      for (i = 0; i < s; i++) {
 6749        this.words[i] = 0;
 6750      }
 6751
 6752      this.length += s;
 6753    }
 6754
 6755    return this.strip();
 6756  };
 6757
 6758  BN.prototype.ishln = function ishln (bits) {
 6759    // TODO(indutny): implement me
 6760    assert(this.negative === 0);
 6761    return this.iushln(bits);
 6762  };
 6763
 6764  // Shift-right in-place
 6765  // NOTE: `hint` is a lowest bit before trailing zeroes
 6766  // NOTE: if `extended` is present - it will be filled with destroyed bits
 6767  BN.prototype.iushrn = function iushrn (bits, hint, extended) {
 6768    assert(typeof bits === 'number' && bits >= 0);
 6769    var h;
 6770    if (hint) {
 6771      h = (hint - (hint % 26)) / 26;
 6772    } else {
 6773      h = 0;
 6774    }
 6775
 6776    var r = bits % 26;
 6777    var s = Math.min((bits - r) / 26, this.length);
 6778    var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
 6779    var maskedWords = extended;
 6780
 6781    h -= s;
 6782    h = Math.max(0, h);
 6783
 6784    // Extended mode, copy masked part
 6785    if (maskedWords) {
 6786      for (var i = 0; i < s; i++) {
 6787        maskedWords.words[i] = this.words[i];
 6788      }
 6789      maskedWords.length = s;
 6790    }
 6791
 6792    if (s === 0) {
 6793      // No-op, we should not move anything at all
 6794    } else if (this.length > s) {
 6795      this.length -= s;
 6796      for (i = 0; i < this.length; i++) {
 6797        this.words[i] = this.words[i + s];
 6798      }
 6799    } else {
 6800      this.words[0] = 0;
 6801      this.length = 1;
 6802    }
 6803
 6804    var carry = 0;
 6805    for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
 6806      var word = this.words[i] | 0;
 6807      this.words[i] = (carry << (26 - r)) | (word >>> r);
 6808      carry = word & mask;
 6809    }
 6810
 6811    // Push carried bits as a mask
 6812    if (maskedWords && carry !== 0) {
 6813      maskedWords.words[maskedWords.length++] = carry;
 6814    }
 6815
 6816    if (this.length === 0) {
 6817      this.words[0] = 0;
 6818      this.length = 1;
 6819    }
 6820
 6821    return this.strip();
 6822  };
 6823
 6824  BN.prototype.ishrn = function ishrn (bits, hint, extended) {
 6825    // TODO(indutny): implement me
 6826    assert(this.negative === 0);
 6827    return this.iushrn(bits, hint, extended);
 6828  };
 6829
 6830  // Shift-left
 6831  BN.prototype.shln = function shln (bits) {
 6832    return this.clone().ishln(bits);
 6833  };
 6834
 6835  BN.prototype.ushln = function ushln (bits) {
 6836    return this.clone().iushln(bits);
 6837  };
 6838
 6839  // Shift-right
 6840  BN.prototype.shrn = function shrn (bits) {
 6841    return this.clone().ishrn(bits);
 6842  };
 6843
 6844  BN.prototype.ushrn = function ushrn (bits) {
 6845    return this.clone().iushrn(bits);
 6846  };
 6847
 6848  // Test if n bit is set
 6849  BN.prototype.testn = function testn (bit) {
 6850    assert(typeof bit === 'number' && bit >= 0);
 6851    var r = bit % 26;
 6852    var s = (bit - r) / 26;
 6853    var q = 1 << r;
 6854
 6855    // Fast case: bit is much higher than all existing words
 6856    if (this.length <= s) return false;
 6857
 6858    // Check bit and return
 6859    var w = this.words[s];
 6860
 6861    return !!(w & q);
 6862  };
 6863
 6864  // Return only lowers bits of number (in-place)
 6865  BN.prototype.imaskn = function imaskn (bits) {
 6866    assert(typeof bits === 'number' && bits >= 0);
 6867    var r = bits % 26;
 6868    var s = (bits - r) / 26;
 6869
 6870    assert(this.negative === 0, 'imaskn works only with positive numbers');
 6871
 6872    if (this.length <= s) {
 6873      return this;
 6874    }
 6875
 6876    if (r !== 0) {
 6877      s++;
 6878    }
 6879    this.length = Math.min(s, this.length);
 6880
 6881    if (r !== 0) {
 6882      var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
 6883      this.words[this.length - 1] &= mask;
 6884    }
 6885
 6886    return this.strip();
 6887  };
 6888
 6889  // Return only lowers bits of number
 6890  BN.prototype.maskn = function maskn (bits) {
 6891    return this.clone().imaskn(bits);
 6892  };
 6893
 6894  // Add plain number `num` to `this`
 6895  BN.prototype.iaddn = function iaddn (num) {
 6896    assert(typeof num === 'number');
 6897    assert(num < 0x4000000);
 6898    if (num < 0) return this.isubn(-num);
 6899
 6900    // Possible sign change
 6901    if (this.negative !== 0) {
 6902      if (this.length === 1 && (this.words[0] | 0) < num) {
 6903        this.words[0] = num - (this.words[0] | 0);
 6904        this.negative = 0;
 6905        return this;
 6906      }
 6907
 6908      this.negative = 0;
 6909      this.isubn(num);
 6910      this.negative = 1;
 6911      return this;
 6912    }
 6913
 6914    // Add without checks
 6915    return this._iaddn(num);
 6916  };
 6917
 6918  BN.prototype._iaddn = function _iaddn (num) {
 6919    this.words[0] += num;
 6920
 6921    // Carry
 6922    for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
 6923      this.words[i] -= 0x4000000;
 6924      if (i === this.length - 1) {
 6925        this.words[i + 1] = 1;
 6926      } else {
 6927        this.words[i + 1]++;
 6928      }
 6929    }
 6930    this.length = Math.max(this.length, i + 1);
 6931
 6932    return this;
 6933  };
 6934
 6935  // Subtract plain number `num` from `this`
 6936  BN.prototype.isubn = function isubn (num) {
 6937    assert(typeof num === 'number');
 6938    assert(num < 0x4000000);
 6939    if (num < 0) return this.iaddn(-num);
 6940
 6941    if (this.negative !== 0) {
 6942      this.negative = 0;
 6943      this.iaddn(num);
 6944      this.negative = 1;
 6945      return this;
 6946    }
 6947
 6948    this.words[0] -= num;
 6949
 6950    if (this.length === 1 && this.words[0] < 0) {
 6951      this.words[0] = -this.words[0];
 6952      this.negative = 1;
 6953    } else {
 6954      // Carry
 6955      for (var i = 0; i < this.length && this.words[i] < 0; i++) {
 6956        this.words[i] += 0x4000000;
 6957        this.words[i + 1] -= 1;
 6958      }
 6959    }
 6960
 6961    return this.strip();
 6962  };
 6963
 6964  BN.prototype.addn = function addn (num) {
 6965    return this.clone().iaddn(num);
 6966  };
 6967
 6968  BN.prototype.subn = function subn (num) {
 6969    return this.clone().isubn(num);
 6970  };
 6971
 6972  BN.prototype.iabs = function iabs () {
 6973    this.negative = 0;
 6974
 6975    return this;
 6976  };
 6977
 6978  BN.prototype.abs = function abs () {
 6979    return this.clone().iabs();
 6980  };
 6981
 6982  BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
 6983    var len = num.length + shift;
 6984    var i;
 6985
 6986    this._expand(len);
 6987
 6988    var w;
 6989    var carry = 0;
 6990    for (i = 0; i < num.length; i++) {
 6991      w = (this.words[i + shift] | 0) + carry;
 6992      var right = (num.words[i] | 0) * mul;
 6993      w -= right & 0x3ffffff;
 6994      carry = (w >> 26) - ((right / 0x4000000) | 0);
 6995      this.words[i + shift] = w & 0x3ffffff;
 6996    }
 6997    for (; i < this.length - shift; i++) {
 6998      w = (this.words[i + shift] | 0) + carry;
 6999      carry = w >> 26;
 7000      this.words[i + shift] = w & 0x3ffffff;
 7001    }
 7002
 7003    if (carry === 0) return this.strip();
 7004
 7005    // Subtraction overflow
 7006    assert(carry === -1);
 7007    carry = 0;
 7008    for (i = 0; i < this.length; i++) {
 7009      w = -(this.words[i] | 0) + carry;
 7010      carry = w >> 26;
 7011      this.words[i] = w & 0x3ffffff;
 7012    }
 7013    this.negative = 1;
 7014
 7015    return this.strip();
 7016  };
 7017
 7018  BN.prototype._wordDiv = function _wordDiv (num, mode) {
 7019    var shift = this.length - num.length;
 7020
 7021    var a = this.clone();
 7022    var b = num;
 7023
 7024    // Normalize
 7025    var bhi = b.words[b.length - 1] | 0;
 7026    var bhiBits = this._countBits(bhi);
 7027    shift = 26 - bhiBits;
 7028    if (shift !== 0) {
 7029      b = b.ushln(shift);
 7030      a.iushln(shift);
 7031      bhi = b.words[b.length - 1] | 0;
 7032    }
 7033
 7034    // Initialize quotient
 7035    var m = a.length - b.length;
 7036    var q;
 7037
 7038    if (mode !== 'mod') {
 7039      q = new BN(null);
 7040      q.length = m + 1;
 7041      q.words = new Array(q.length);
 7042      for (var i = 0; i < q.length; i++) {
 7043        q.words[i] = 0;
 7044      }
 7045    }
 7046
 7047    var diff = a.clone()._ishlnsubmul(b, 1, m);
 7048    if (diff.negative === 0) {
 7049      a = diff;
 7050      if (q) {
 7051        q.words[m] = 1;
 7052      }
 7053    }
 7054
 7055    for (var j = m - 1; j >= 0; j--) {
 7056      var qj = (a.words[b.length + j] | 0) * 0x4000000 +
 7057        (a.words[b.length + j - 1] | 0);
 7058
 7059      // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
 7060      // (0x7ffffff)
 7061      qj = Math.min((qj / bhi) | 0, 0x3ffffff);
 7062
 7063      a._ishlnsubmul(b, qj, j);
 7064      while (a.negative !== 0) {
 7065        qj--;
 7066        a.negative = 0;
 7067        a._ishlnsubmul(b, 1, j);
 7068        if (!a.isZero()) {
 7069          a.negative ^= 1;
 7070        }
 7071      }
 7072      if (q) {
 7073        q.words[j] = qj;
 7074      }
 7075    }
 7076    if (q) {
 7077      q.strip();
 7078    }
 7079    a.strip();
 7080
 7081    // Denormalize
 7082    if (mode !== 'div' && shift !== 0) {
 7083      a.iushrn(shift);
 7084    }
 7085
 7086    return {
 7087      div: q || null,
 7088      mod: a
 7089    };
 7090  };
 7091
 7092  // NOTE: 1) `mode` can be set to `mod` to request mod only,
 7093  //       to `div` to request div only, or be absent to
 7094  //       request both div & mod
 7095  //       2) `positive` is true if unsigned mod is requested
 7096  BN.prototype.divmod = function divmod (num, mode, positive) {
 7097    assert(!num.isZero());
 7098
 7099    if (this.isZero()) {
 7100      return {
 7101        div: new BN(0),
 7102        mod: new BN(0)
 7103      };
 7104    }
 7105
 7106    var div, mod, res;
 7107    if (this.negative !== 0 && num.negative === 0) {
 7108      res = this.neg().divmod(num, mode);
 7109
 7110      if (mode !== 'mod') {
 7111        div = res.div.neg();
 7112      }
 7113
 7114      if (mode !== 'div') {
 7115        mod = res.mod.neg();
 7116        if (positive && mod.negative !== 0) {
 7117          mod.iadd(num);
 7118        }
 7119      }
 7120
 7121      return {
 7122        div: div,
 7123        mod: mod
 7124      };
 7125    }
 7126
 7127    if (this.negative === 0 && num.negative !== 0) {
 7128      res = this.divmod(num.neg(), mode);
 7129
 7130      if (mode !== 'mod') {
 7131        div = res.div.neg();
 7132      }
 7133
 7134      return {
 7135        div: div,
 7136        mod: res.mod
 7137      };
 7138    }
 7139
 7140    if ((this.negative & num.negative) !== 0) {
 7141      res = this.neg().divmod(num.neg(), mode);
 7142
 7143      if (mode !== 'div') {
 7144        mod = res.mod.neg();
 7145        if (positive && mod.negative !== 0) {
 7146          mod.isub(num);
 7147        }
 7148      }
 7149
 7150      return {
 7151        div: res.div,
 7152        mod: mod
 7153      };
 7154    }
 7155
 7156    // Both numbers are positive at this point
 7157
 7158    // Strip both numbers to approximate shift value
 7159    if (num.length > this.length || this.cmp(num) < 0) {
 7160      return {
 7161        div: new BN(0),
 7162        mod: this
 7163      };
 7164    }
 7165
 7166    // Very short reduction
 7167    if (num.length === 1) {
 7168      if (mode === 'div') {
 7169        return {
 7170          div: this.divn(num.words[0]),
 7171          mod: null
 7172        };
 7173      }
 7174
 7175      if (mode === 'mod') {
 7176        return {
 7177          div: null,
 7178          mod: new BN(this.modn(num.words[0]))
 7179        };
 7180      }
 7181
 7182      return {
 7183        div: this.divn(num.words[0]),
 7184        mod: new BN(this.modn(num.words[0]))
 7185      };
 7186    }
 7187
 7188    return this._wordDiv(num, mode);
 7189  };
 7190
 7191  // Find `this` / `num`
 7192  BN.prototype.div = function div (num) {
 7193    return this.divmod(num, 'div', false).div;
 7194  };
 7195
 7196  // Find `this` % `num`
 7197  BN.prototype.mod = function mod (num) {
 7198    return this.divmod(num, 'mod', false).mod;
 7199  };
 7200
 7201  BN.prototype.umod = function umod (num) {
 7202    return this.divmod(num, 'mod', true).mod;
 7203  };
 7204
 7205  // Find Round(`this` / `num`)
 7206  BN.prototype.divRound = function divRound (num) {
 7207    var dm = this.divmod(num);
 7208
 7209    // Fast case - exact division
 7210    if (dm.mod.isZero()) return dm.div;
 7211
 7212    var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
 7213
 7214    var half = num.ushrn(1);
 7215    var r2 = num.andln(1);
 7216    var cmp = mod.cmp(half);
 7217
 7218    // Round down
 7219    if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
 7220
 7221    // Round up
 7222    return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
 7223  };
 7224
 7225  BN.prototype.modn = function modn (num) {
 7226    assert(num <= 0x3ffffff);
 7227    var p = (1 << 26) % num;
 7228
 7229    var acc = 0;
 7230    for (var i = this.length - 1; i >= 0; i--) {
 7231      acc = (p * acc + (this.words[i] | 0)) % num;
 7232    }
 7233
 7234    return acc;
 7235  };
 7236
 7237  // In-place division by number
 7238  BN.prototype.idivn = function idivn (num) {
 7239    assert(num <= 0x3ffffff);
 7240
 7241    var carry = 0;
 7242    for (var i = this.length - 1; i >= 0; i--) {
 7243      var w = (this.words[i] | 0) + carry * 0x4000000;
 7244      this.words[i] = (w / num) | 0;
 7245      carry = w % num;
 7246    }
 7247
 7248    return this.strip();
 7249  };
 7250
 7251  BN.prototype.divn = function divn (num) {
 7252    return this.clone().idivn(num);
 7253  };
 7254
 7255  BN.prototype.egcd = function egcd (p) {
 7256    assert(p.negative === 0);
 7257    assert(!p.isZero());
 7258
 7259    var x = this;
 7260    var y = p.clone();
 7261
 7262    if (x.negative !== 0) {
 7263      x = x.umod(p);
 7264    } else {
 7265      x = x.clone();
 7266    }
 7267
 7268    // A * x + B * y = x
 7269    var A = new BN(1);
 7270    var B = new BN(0);
 7271
 7272    // C * x + D * y = y
 7273    var C = new BN(0);
 7274    var D = new BN(1);
 7275
 7276    var g = 0;
 7277
 7278    while (x.isEven() && y.isEven()) {
 7279      x.iushrn(1);
 7280      y.iushrn(1);
 7281      ++g;
 7282    }
 7283
 7284    var yp = y.clone();
 7285    var xp = x.clone();
 7286
 7287    while (!x.isZero()) {
 7288      for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
 7289      if (i > 0) {
 7290        x.iushrn(i);
 7291        while (i-- > 0) {
 7292          if (A.isOdd() || B.isOdd()) {
 7293            A.iadd(yp);
 7294            B.isub(xp);
 7295          }
 7296
 7297          A.iushrn(1);
 7298          B.iushrn(1);
 7299        }
 7300      }
 7301
 7302      for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
 7303      if (j > 0) {
 7304        y.iushrn(j);
 7305        while (j-- > 0) {
 7306          if (C.isOdd() || D.isOdd()) {
 7307            C.iadd(yp);
 7308            D.isub(xp);
 7309          }
 7310
 7311          C.iushrn(1);
 7312          D.iushrn(1);
 7313        }
 7314      }
 7315
 7316      if (x.cmp(y) >= 0) {
 7317        x.isub(y);
 7318        A.isub(C);
 7319        B.isub(D);
 7320      } else {
 7321        y.isub(x);
 7322        C.isub(A);
 7323        D.isub(B);
 7324      }
 7325    }
 7326
 7327    return {
 7328      a: C,
 7329      b: D,
 7330      gcd: y.iushln(g)
 7331    };
 7332  };
 7333
 7334  // This is reduced incarnation of the binary EEA
 7335  // above, designated to invert members of the
 7336  // _prime_ fields F(p) at a maximal speed
 7337  BN.prototype._invmp = function _invmp (p) {
 7338    assert(p.negative === 0);
 7339    assert(!p.isZero());
 7340
 7341    var a = this;
 7342    var b = p.clone();
 7343
 7344    if (a.negative !== 0) {
 7345      a = a.umod(p);
 7346    } else {
 7347      a = a.clone();
 7348    }
 7349
 7350    var x1 = new BN(1);
 7351    var x2 = new BN(0);
 7352
 7353    var delta = b.clone();
 7354
 7355    while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
 7356      for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
 7357      if (i > 0) {
 7358        a.iushrn(i);
 7359        while (i-- > 0) {
 7360          if (x1.isOdd()) {
 7361            x1.iadd(delta);
 7362          }
 7363
 7364          x1.iushrn(1);
 7365        }
 7366      }
 7367
 7368      for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
 7369      if (j > 0) {
 7370        b.iushrn(j);
 7371        while (j-- > 0) {
 7372          if (x2.isOdd()) {
 7373            x2.iadd(delta);
 7374          }
 7375
 7376          x2.iushrn(1);
 7377        }
 7378      }
 7379
 7380      if (a.cmp(b) >= 0) {
 7381        a.isub(b);
 7382        x1.isub(x2);
 7383      } else {
 7384        b.isub(a);
 7385        x2.isub(x1);
 7386      }
 7387    }
 7388
 7389    var res;
 7390    if (a.cmpn(1) === 0) {
 7391      res = x1;
 7392    } else {
 7393      res = x2;
 7394    }
 7395
 7396    if (res.cmpn(0) < 0) {
 7397      res.iadd(p);
 7398    }
 7399
 7400    return res;
 7401  };
 7402
 7403  BN.prototype.gcd = function gcd (num) {
 7404    if (this.isZero()) return num.abs();
 7405    if (num.isZero()) return this.abs();
 7406
 7407    var a = this.clone();
 7408    var b = num.clone();
 7409    a.negative = 0;
 7410    b.negative = 0;
 7411
 7412    // Remove common factor of two
 7413    for (var shift = 0; a.isEven() && b.isEven(); shift++) {
 7414      a.iushrn(1);
 7415      b.iushrn(1);
 7416    }
 7417
 7418    do {
 7419      while (a.isEven()) {
 7420        a.iushrn(1);
 7421      }
 7422      while (b.isEven()) {
 7423        b.iushrn(1);
 7424      }
 7425
 7426      var r = a.cmp(b);
 7427      if (r < 0) {
 7428        // Swap `a` and `b` to make `a` always bigger than `b`
 7429        var t = a;
 7430        a = b;
 7431        b = t;
 7432      } else if (r === 0 || b.cmpn(1) === 0) {
 7433        break;
 7434      }
 7435
 7436      a.isub(b);
 7437    } while (true);
 7438
 7439    return b.iushln(shift);
 7440  };
 7441
 7442  // Invert number in the field F(num)
 7443  BN.prototype.invm = function invm (num) {
 7444    return this.egcd(num).a.umod(num);
 7445  };
 7446
 7447  BN.prototype.isEven = function isEven () {
 7448    return (this.words[0] & 1) === 0;
 7449  };
 7450
 7451  BN.prototype.isOdd = function isOdd () {
 7452    return (this.words[0] & 1) === 1;
 7453  };
 7454
 7455  // And first word and num
 7456  BN.prototype.andln = function andln (num) {
 7457    return this.words[0] & num;
 7458  };
 7459
 7460  // Increment at the bit position in-line
 7461  BN.prototype.bincn = function bincn (bit) {
 7462    assert(typeof bit === 'number');
 7463    var r = bit % 26;
 7464    var s = (bit - r) / 26;
 7465    var q = 1 << r;
 7466
 7467    // Fast case: bit is much higher than all existing words
 7468    if (this.length <= s) {
 7469      this._expand(s + 1);
 7470      this.words[s] |= q;
 7471      return this;
 7472    }
 7473
 7474    // Add bit and propagate, if needed
 7475    var carry = q;
 7476    for (var i = s; carry !== 0 && i < this.length; i++) {
 7477      var w = this.words[i] | 0;
 7478      w += carry;
 7479      carry = w >>> 26;
 7480      w &= 0x3ffffff;
 7481      this.words[i] = w;
 7482    }
 7483    if (carry !== 0) {
 7484      this.words[i] = carry;
 7485      this.length++;
 7486    }
 7487    return this;
 7488  };
 7489
 7490  BN.prototype.isZero = function isZero () {
 7491    return this.length === 1 && this.words[0] === 0;
 7492  };
 7493
 7494  BN.prototype.cmpn = function cmpn (num) {
 7495    var negative = num < 0;
 7496
 7497    if (this.negative !== 0 && !negative) return -1;
 7498    if (this.negative === 0 && negative) return 1;
 7499
 7500    this.strip();
 7501
 7502    var res;
 7503    if (this.length > 1) {
 7504      res = 1;
 7505    } else {
 7506      if (negative) {
 7507        num = -num;
 7508      }
 7509
 7510      assert(num <= 0x3ffffff, 'Number is too big');
 7511
 7512      var w = this.words[0] | 0;
 7513      res = w === num ? 0 : w < num ? -1 : 1;
 7514    }
 7515    if (this.negative !== 0) return -res | 0;
 7516    return res;
 7517  };
 7518
 7519  // Compare two numbers and return:
 7520  // 1 - if `this` > `num`
 7521  // 0 - if `this` == `num`
 7522  // -1 - if `this` < `num`
 7523  BN.prototype.cmp = function cmp (num) {
 7524    if (this.negative !== 0 && num.negative === 0) return -1;
 7525    if (this.negative === 0 && num.negative !== 0) return 1;
 7526
 7527    var res = this.ucmp(num);
 7528    if (this.negative !== 0) return -res | 0;
 7529    return res;
 7530  };
 7531
 7532  // Unsigned comparison
 7533  BN.prototype.ucmp = function ucmp (num) {
 7534    // At this point both numbers have the same sign
 7535    if (this.length > num.length) return 1;
 7536    if (this.length < num.length) return -1;
 7537
 7538    var res = 0;
 7539    for (var i = this.length - 1; i >= 0; i--) {
 7540      var a = this.words[i] | 0;
 7541      var b = num.words[i] | 0;
 7542
 7543      if (a === b) continue;
 7544      if (a < b) {
 7545        res = -1;
 7546      } else if (a > b) {
 7547        res = 1;
 7548      }
 7549      break;
 7550    }
 7551    return res;
 7552  };
 7553
 7554  BN.prototype.gtn = function gtn (num) {
 7555    return this.cmpn(num) === 1;
 7556  };
 7557
 7558  BN.prototype.gt = function gt (num) {
 7559    return this.cmp(num) === 1;
 7560  };
 7561
 7562  BN.prototype.gten = function gten (num) {
 7563    return this.cmpn(num) >= 0;
 7564  };
 7565
 7566  BN.prototype.gte = function gte (num) {
 7567    return this.cmp(num) >= 0;
 7568  };
 7569
 7570  BN.prototype.ltn = function ltn (num) {
 7571    return this.cmpn(num) === -1;
 7572  };
 7573
 7574  BN.prototype.lt = function lt (num) {
 7575    return this.cmp(num) === -1;
 7576  };
 7577
 7578  BN.prototype.lten = function lten (num) {
 7579    return this.cmpn(num) <= 0;
 7580  };
 7581
 7582  BN.prototype.lte = function lte (num) {
 7583    return this.cmp(num) <= 0;
 7584  };
 7585
 7586  BN.prototype.eqn = function eqn (num) {
 7587    return this.cmpn(num) === 0;
 7588  };
 7589
 7590  BN.prototype.eq = function eq (num) {
 7591    return this.cmp(num) === 0;
 7592  };
 7593
 7594  //
 7595  // A reduce context, could be using montgomery or something better, depending
 7596  // on the `m` itself.
 7597  //
 7598  BN.red = function red (num) {
 7599    return new Red(num);
 7600  };
 7601
 7602  BN.prototype.toRed = function toRed (ctx) {
 7603    assert(!this.red, 'Already a number in reduction context');
 7604    assert(this.negative === 0, 'red works only with positives');
 7605    return ctx.convertTo(this)._forceRed(ctx);
 7606  };
 7607
 7608  BN.prototype.fromRed = function fromRed () {
 7609    assert(this.red, 'fromRed works only with numbers in reduction context');
 7610    return this.red.convertFrom(this);
 7611  };
 7612
 7613  BN.prototype._forceRed = function _forceRed (ctx) {
 7614    this.red = ctx;
 7615    return this;
 7616  };
 7617
 7618  BN.prototype.forceRed = function forceRed (ctx) {
 7619    assert(!this.red, 'Already a number in reduction context');
 7620    return this._forceRed(ctx);
 7621  };
 7622
 7623  BN.prototype.redAdd = function redAdd (num) {
 7624    assert(this.red, 'redAdd works only with red numbers');
 7625    return this.red.add(this, num);
 7626  };
 7627
 7628  BN.prototype.redIAdd = function redIAdd (num) {
 7629    assert(this.red, 'redIAdd works only with red numbers');
 7630    return this.red.iadd(this, num);
 7631  };
 7632
 7633  BN.prototype.redSub = function redSub (num) {
 7634    assert(this.red, 'redSub works only with red numbers');
 7635    return this.red.sub(this, num);
 7636  };
 7637
 7638  BN.prototype.redISub = function redISub (num) {
 7639    assert(this.red, 'redISub works only with red numbers');
 7640    return this.red.isub(this, num);
 7641  };
 7642
 7643  BN.prototype.redShl = function redShl (num) {
 7644    assert(this.red, 'redShl works only with red numbers');
 7645    return this.red.shl(this, num);
 7646  };
 7647
 7648  BN.prototype.redMul = function redMul (num) {
 7649    assert(this.red, 'redMul works only with red numbers');
 7650    this.red._verify2(this, num);
 7651    return this.red.mul(this, num);
 7652  };
 7653
 7654  BN.prototype.redIMul = function redIMul (num) {
 7655    assert(this.red, 'redMul works only with red numbers');
 7656    this.red._verify2(this, num);
 7657    return this.red.imul(this, num);
 7658  };
 7659
 7660  BN.prototype.redSqr = function redSqr () {
 7661    assert(this.red, 'redSqr works only with red numbers');
 7662    this.red._verify1(this);
 7663    return this.red.sqr(this);
 7664  };
 7665
 7666  BN.prototype.redISqr = function redISqr () {
 7667    assert(this.red, 'redISqr works only with red numbers');
 7668    this.red._verify1(this);
 7669    return this.red.isqr(this);
 7670  };
 7671
 7672  // Square root over p
 7673  BN.prototype.redSqrt = function redSqrt () {
 7674    assert(this.red, 'redSqrt works only with red numbers');
 7675    this.red._verify1(this);
 7676    return this.red.sqrt(this);
 7677  };
 7678
 7679  BN.prototype.redInvm = function redInvm () {
 7680    assert(this.red, 'redInvm works only with red numbers');
 7681    this.red._verify1(this);
 7682    return this.red.invm(this);
 7683  };
 7684
 7685  // Return negative clone of `this` % `red modulo`
 7686  BN.prototype.redNeg = function redNeg () {
 7687    assert(this.red, 'redNeg works only with red numbers');
 7688    this.red._verify1(this);
 7689    return this.red.neg(this);
 7690  };
 7691
 7692  BN.prototype.redPow = function redPow (num) {
 7693    assert(this.red && !num.red, 'redPow(normalNum)');
 7694    this.red._verify1(this);
 7695    return this.red.pow(this, num);
 7696  };
 7697
 7698  // Prime numbers with efficient reduction
 7699  var primes = {
 7700    k256: null,
 7701    p224: null,
 7702    p192: null,
 7703    p25519: null
 7704  };
 7705
 7706  // Pseudo-Mersenne prime
 7707  function MPrime (name, p) {
 7708    // P = 2 ^ N - K
 7709    this.name = name;
 7710    this.p = new BN(p, 16);
 7711    this.n = this.p.bitLength();
 7712    this.k = new BN(1).iushln(this.n).isub(this.p);
 7713
 7714    this.tmp = this._tmp();
 7715  }
 7716
 7717  MPrime.prototype._tmp = function _tmp () {
 7718    var tmp = new BN(null);
 7719    tmp.words = new Array(Math.ceil(this.n / 13));
 7720    return tmp;
 7721  };
 7722
 7723  MPrime.prototype.ireduce = function ireduce (num) {
 7724    // Assumes that `num` is less than `P^2`
 7725    // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
 7726    var r = num;
 7727    var rlen;
 7728
 7729    do {
 7730      this.split(r, this.tmp);
 7731      r = this.imulK(r);
 7732      r = r.iadd(this.tmp);
 7733      rlen = r.bitLength();
 7734    } while (rlen > this.n);
 7735
 7736    var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
 7737    if (cmp === 0) {
 7738      r.words[0] = 0;
 7739      r.length = 1;
 7740    } else if (cmp > 0) {
 7741      r.isub(this.p);
 7742    } else {
 7743      r.strip();
 7744    }
 7745
 7746    return r;
 7747  };
 7748
 7749  MPrime.prototype.split = function split (input, out) {
 7750    input.iushrn(this.n, 0, out);
 7751  };
 7752
 7753  MPrime.prototype.imulK = function imulK (num) {
 7754    return num.imul(this.k);
 7755  };
 7756
 7757  function K256 () {
 7758    MPrime.call(
 7759      this,
 7760      'k256',
 7761      'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
 7762  }
 7763  inherits(K256, MPrime);
 7764
 7765  K256.prototype.split = function split (input, output) {
 7766    // 256 = 9 * 26 + 22
 7767    var mask = 0x3fffff;
 7768
 7769    var outLen = Math.min(input.length, 9);
 7770    for (var i = 0; i < outLen; i++) {
 7771      output.words[i] = input.words[i];
 7772    }
 7773    output.length = outLen;
 7774
 7775    if (input.length <= 9) {
 7776      input.words[0] = 0;
 7777      input.length = 1;
 7778      return;
 7779    }
 7780
 7781    // Shift by 9 limbs
 7782    var prev = input.words[9];
 7783    output.words[output.length++] = prev & mask;
 7784
 7785    for (i = 10; i < input.length; i++) {
 7786      var next = input.words[i] | 0;
 7787      input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
 7788      prev = next;
 7789    }
 7790    prev >>>= 22;
 7791    input.words[i - 10] = prev;
 7792    if (prev === 0 && input.length > 10) {
 7793      input.length -= 10;
 7794    } else {
 7795      input.length -= 9;
 7796    }
 7797  };
 7798
 7799  K256.prototype.imulK = function imulK (num) {
 7800    // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
 7801    num.words[num.length] = 0;
 7802    num.words[num.length + 1] = 0;
 7803    num.length += 2;
 7804
 7805    // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
 7806    var lo = 0;
 7807    for (var i = 0; i < num.length; i++) {
 7808      var w = num.words[i] | 0;
 7809      lo += w * 0x3d1;
 7810      num.words[i] = lo & 0x3ffffff;
 7811      lo = w * 0x40 + ((lo / 0x4000000) | 0);
 7812    }
 7813
 7814    // Fast length reduction
 7815    if (num.words[num.length - 1] === 0) {
 7816      num.length--;
 7817      if (num.words[num.length - 1] === 0) {
 7818        num.length--;
 7819      }
 7820    }
 7821    return num;
 7822  };
 7823
 7824  function P224 () {
 7825    MPrime.call(
 7826      this,
 7827      'p224',
 7828      'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
 7829  }
 7830  inherits(P224, MPrime);
 7831
 7832  function P192 () {
 7833    MPrime.call(
 7834      this,
 7835      'p192',
 7836      'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
 7837  }
 7838  inherits(P192, MPrime);
 7839
 7840  function P25519 () {
 7841    // 2 ^ 255 - 19
 7842    MPrime.call(
 7843      this,
 7844      '25519',
 7845      '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
 7846  }
 7847  inherits(P25519, MPrime);
 7848
 7849  P25519.prototype.imulK = function imulK (num) {
 7850    // K = 0x13
 7851    var carry = 0;
 7852    for (var i = 0; i < num.length; i++) {
 7853      var hi = (num.words[i] | 0) * 0x13 + carry;
 7854      var lo = hi & 0x3ffffff;
 7855      hi >>>= 26;
 7856
 7857      num.words[i] = lo;
 7858      carry = hi;
 7859    }
 7860    if (carry !== 0) {
 7861      num.words[num.length++] = carry;
 7862    }
 7863    return num;
 7864  };
 7865
 7866  // Exported mostly for testing purposes, use plain name instead
 7867  BN._prime = function prime (name) {
 7868    // Cached version of prime
 7869    if (primes[name]) return primes[name];
 7870
 7871    var prime;
 7872    if (name === 'k256') {
 7873      prime = new K256();
 7874    } else if (name === 'p224') {
 7875      prime = new P224();
 7876    } else if (name === 'p192') {
 7877      prime = new P192();
 7878    } else if (name === 'p25519') {
 7879      prime = new P25519();
 7880    } else {
 7881      throw new Error('Unknown prime ' + name);
 7882    }
 7883    primes[name] = prime;
 7884
 7885    return prime;
 7886  };
 7887
 7888  //
 7889  // Base reduction engine
 7890  //
 7891  function Red (m) {
 7892    if (typeof m === 'string') {
 7893      var prime = BN._prime(m);
 7894      this.m = prime.p;
 7895      this.prime = prime;
 7896    } else {
 7897      assert(m.gtn(1), 'modulus must be greater than 1');
 7898      this.m = m;
 7899      this.prime = null;
 7900    }
 7901  }
 7902
 7903  Red.prototype._verify1 = function _verify1 (a) {
 7904    assert(a.negative === 0, 'red works only with positives');
 7905    assert(a.red, 'red works only with red numbers');
 7906  };
 7907
 7908  Red.prototype._verify2 = function _verify2 (a, b) {
 7909    assert((a.negative | b.negative) === 0, 'red works only with positives');
 7910    assert(a.red && a.red === b.red,
 7911      'red works only with red numbers');
 7912  };
 7913
 7914  Red.prototype.imod = function imod (a) {
 7915    if (this.prime) return this.prime.ireduce(a)._forceRed(this);
 7916    return a.umod(this.m)._forceRed(this);
 7917  };
 7918
 7919  Red.prototype.neg = function neg (a) {
 7920    if (a.isZero()) {
 7921      return a.clone();
 7922    }
 7923
 7924    return this.m.sub(a)._forceRed(this);
 7925  };
 7926
 7927  Red.prototype.add = function add (a, b) {
 7928    this._verify2(a, b);
 7929
 7930    var res = a.add(b);
 7931    if (res.cmp(this.m) >= 0) {
 7932      res.isub(this.m);
 7933    }
 7934    return res._forceRed(this);
 7935  };
 7936
 7937  Red.prototype.iadd = function iadd (a, b) {
 7938    this._verify2(a, b);
 7939
 7940    var res = a.iadd(b);
 7941    if (res.cmp(this.m) >= 0) {
 7942      res.isub(this.m);
 7943    }
 7944    return res;
 7945  };
 7946
 7947  Red.prototype.sub = function sub (a, b) {
 7948    this._verify2(a, b);
 7949
 7950    var res = a.sub(b);
 7951    if (res.cmpn(0) < 0) {
 7952      res.iadd(this.m);
 7953    }
 7954    return res._forceRed(this);
 7955  };
 7956
 7957  Red.prototype.isub = function isub (a, b) {
 7958    this._verify2(a, b);
 7959
 7960    var res = a.isub(b);
 7961    if (res.cmpn(0) < 0) {
 7962      res.iadd(this.m);
 7963    }
 7964    return res;
 7965  };
 7966
 7967  Red.prototype.shl = function shl (a, num) {
 7968    this._verify1(a);
 7969    return this.imod(a.ushln(num));
 7970  };
 7971
 7972  Red.prototype.imul = function imul (a, b) {
 7973    this._verify2(a, b);
 7974    return this.imod(a.imul(b));
 7975  };
 7976
 7977  Red.prototype.mul = function mul (a, b) {
 7978    this._verify2(a, b);
 7979    return this.imod(a.mul(b));
 7980  };
 7981
 7982  Red.prototype.isqr = function isqr (a) {
 7983    return this.imul(a, a.clone());
 7984  };
 7985
 7986  Red.prototype.sqr = function sqr (a) {
 7987    return this.mul(a, a);
 7988  };
 7989
 7990  Red.prototype.sqrt = function sqrt (a) {
 7991    if (a.isZero()) return a.clone();
 7992
 7993    var mod3 = this.m.andln(3);
 7994    assert(mod3 % 2 === 1);
 7995
 7996    // Fast case
 7997    if (mod3 === 3) {
 7998      var pow = this.m.add(new BN(1)).iushrn(2);
 7999      return this.pow(a, pow);
 8000    }
 8001
 8002    // Tonelli-Shanks algorithm (Totally unoptimized and slow)
 8003    //
 8004    // Find Q and S, that Q * 2 ^ S = (P - 1)
 8005    var q = this.m.subn(1);
 8006    var s = 0;
 8007    while (!q.isZero() && q.andln(1) === 0) {
 8008      s++;
 8009      q.iushrn(1);
 8010    }
 8011    assert(!q.isZero());
 8012
 8013    var one = new BN(1).toRed(this);
 8014    var nOne = one.redNeg();
 8015
 8016    // Find quadratic non-residue
 8017    // NOTE: Max is such because of generalized Riemann hypothesis.
 8018    var lpow = this.m.subn(1).iushrn(1);
 8019    var z = this.m.bitLength();
 8020    z = new BN(2 * z * z).toRed(this);
 8021
 8022    while (this.pow(z, lpow).cmp(nOne) !== 0) {
 8023      z.redIAdd(nOne);
 8024    }
 8025
 8026    var c = this.pow(z, q);
 8027    var r = this.pow(a, q.addn(1).iushrn(1));
 8028    var t = this.pow(a, q);
 8029    var m = s;
 8030    while (t.cmp(one) !== 0) {
 8031      var tmp = t;
 8032      for (var i = 0; tmp.cmp(one) !== 0; i++) {
 8033        tmp = tmp.redSqr();
 8034      }
 8035      assert(i < m);
 8036      var b = this.pow(c, new BN(1).iushln(m - i - 1));
 8037
 8038      r = r.redMul(b);
 8039      c = b.redSqr();
 8040      t = t.redMul(c);
 8041      m = i;
 8042    }
 8043
 8044    return r;
 8045  };
 8046
 8047  Red.prototype.invm = function invm (a) {
 8048    var inv = a._invmp(this.m);
 8049    if (inv.negative !== 0) {
 8050      inv.negative = 0;
 8051      return this.imod(inv).redNeg();
 8052    } else {
 8053      return this.imod(inv);
 8054    }
 8055  };
 8056
 8057  Red.prototype.pow = function pow (a, num) {
 8058    if (num.isZero()) return new BN(1).toRed(this);
 8059    if (num.cmpn(1) === 0) return a.clone();
 8060
 8061    var windowSize = 4;
 8062    var wnd = new Array(1 << windowSize);
 8063    wnd[0] = new BN(1).toRed(this);
 8064    wnd[1] = a;
 8065    for (var i = 2; i < wnd.length; i++) {
 8066      wnd[i] = this.mul(wnd[i - 1], a);
 8067    }
 8068
 8069    var res = wnd[0];
 8070    var current = 0;
 8071    var currentLen = 0;
 8072    var start = num.bitLength() % 26;
 8073    if (start === 0) {
 8074      start = 26;
 8075    }
 8076
 8077    for (i = num.length - 1; i >= 0; i--) {
 8078      var word = num.words[i];
 8079      for (var j = start - 1; j >= 0; j--) {
 8080        var bit = (word >> j) & 1;
 8081        if (res !== wnd[0]) {
 8082          res = this.sqr(res);
 8083        }
 8084
 8085        if (bit === 0 && current === 0) {
 8086          currentLen = 0;
 8087          continue;
 8088        }
 8089
 8090        current <<= 1;
 8091        current |= bit;
 8092        currentLen++;
 8093        if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
 8094
 8095        res = this.mul(res, wnd[current]);
 8096        currentLen = 0;
 8097        current = 0;
 8098      }
 8099      start = 26;
 8100    }
 8101
 8102    return res;
 8103  };
 8104
 8105  Red.prototype.convertTo = function convertTo (num) {
 8106    var r = num.umod(this.m);
 8107
 8108    return r === num ? r.clone() : r;
 8109  };
 8110
 8111  Red.prototype.convertFrom = function convertFrom (num) {
 8112    var res = num.clone();
 8113    res.red = null;
 8114    return res;
 8115  };
 8116
 8117  //
 8118  // Montgomery method engine
 8119  //
 8120
 8121  BN.mont = function mont (num) {
 8122    return new Mont(num);
 8123  };
 8124
 8125  function Mont (m) {
 8126    Red.call(this, m);
 8127
 8128    this.shift = this.m.bitLength();
 8129    if (this.shift % 26 !== 0) {
 8130      this.shift += 26 - (this.shift % 26);
 8131    }
 8132
 8133    this.r = new BN(1).iushln(this.shift);
 8134    this.r2 = this.imod(this.r.sqr());
 8135    this.rinv = this.r._invmp(this.m);
 8136
 8137    this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
 8138    this.minv = this.minv.umod(this.r);
 8139    this.minv = this.r.sub(this.minv);
 8140  }
 8141  inherits(Mont, Red);
 8142
 8143  Mont.prototype.convertTo = function convertTo (num) {
 8144    return this.imod(num.ushln(this.shift));
 8145  };
 8146
 8147  Mont.prototype.convertFrom = function convertFrom (num) {
 8148    var r = this.imod(num.mul(this.rinv));
 8149    r.red = null;
 8150    return r;
 8151  };
 8152
 8153  Mont.prototype.imul = function imul (a, b) {
 8154    if (a.isZero() || b.isZero()) {
 8155      a.words[0] = 0;
 8156      a.length = 1;
 8157      return a;
 8158    }
 8159
 8160    var t = a.imul(b);
 8161    var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
 8162    var u = t.isub(c).iushrn(this.shift);
 8163    var res = u;
 8164
 8165    if (u.cmp(this.m) >= 0) {
 8166      res = u.isub(this.m);
 8167    } else if (u.cmpn(0) < 0) {
 8168      res = u.iadd(this.m);
 8169    }
 8170
 8171    return res._forceRed(this);
 8172  };
 8173
 8174  Mont.prototype.mul = function mul (a, b) {
 8175    if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
 8176
 8177    var t = a.mul(b);
 8178    var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
 8179    var u = t.isub(c).iushrn(this.shift);
 8180    var res = u;
 8181    if (u.cmp(this.m) >= 0) {
 8182      res = u.isub(this.m);
 8183    } else if (u.cmpn(0) < 0) {
 8184      res = u.iadd(this.m);
 8185    }
 8186
 8187    return res._forceRed(this);
 8188  };
 8189
 8190  Mont.prototype.invm = function invm (a) {
 8191    // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
 8192    var res = this.imod(a._invmp(this.m).mul(this.r2));
 8193    return res._forceRed(this);
 8194  };
 8195})(typeof module === 'undefined' || module, this);
 8196
 8197},{"buffer":"buffer"}],18:[function(require,module,exports){
 8198var r;
 8199
 8200module.exports = function rand(len) {
 8201  if (!r)
 8202    r = new Rand(null);
 8203
 8204  return r.generate(len);
 8205};
 8206
 8207function Rand(rand) {
 8208  this.rand = rand;
 8209}
 8210module.exports.Rand = Rand;
 8211
 8212Rand.prototype.generate = function generate(len) {
 8213  return this._rand(len);
 8214};
 8215
 8216// Emulate crypto API using randy
 8217Rand.prototype._rand = function _rand(n) {
 8218  if (this.rand.getBytes)
 8219    return this.rand.getBytes(n);
 8220
 8221  var res = new Uint8Array(n);
 8222  for (var i = 0; i < res.length; i++)
 8223    res[i] = this.rand.getByte();
 8224  return res;
 8225};
 8226
 8227if (typeof self === 'object') {
 8228  if (self.crypto && self.crypto.getRandomValues) {
 8229    // Modern browsers
 8230    Rand.prototype._rand = function _rand(n) {
 8231      var arr = new Uint8Array(n);
 8232      self.crypto.getRandomValues(arr);
 8233      return arr;
 8234    };
 8235  } else if (self.msCrypto && self.msCrypto.getRandomValues) {
 8236    // IE
 8237    Rand.prototype._rand = function _rand(n) {
 8238      var arr = new Uint8Array(n);
 8239      self.msCrypto.getRandomValues(arr);
 8240      return arr;
 8241    };
 8242
 8243  // Safari's WebWorkers do not have `crypto`
 8244  } else if (typeof window === 'object') {
 8245    // Old junk
 8246    Rand.prototype._rand = function() {
 8247      throw new Error('Not implemented yet');
 8248    };
 8249  }
 8250} else {
 8251  // Node.js or Web worker with no crypto support
 8252  try {
 8253    var crypto = require('crypto');
 8254    if (typeof crypto.randomBytes !== 'function')
 8255      throw new Error('Not supported');
 8256
 8257    Rand.prototype._rand = function _rand(n) {
 8258      return crypto.randomBytes(n);
 8259    };
 8260  } catch (e) {
 8261  }
 8262}
 8263
 8264},{"crypto":"crypto"}],19:[function(require,module,exports){
 8265'use strict';
 8266
 8267var elliptic = exports;
 8268
 8269elliptic.utils = require('./elliptic/utils');
 8270elliptic.rand = require('brorand');
 8271elliptic.curve = require('./elliptic/curve');
 8272elliptic.curves = require('./elliptic/curves');
 8273
 8274// Protocols
 8275elliptic.ec = require('./elliptic/ec');
 8276elliptic.eddsa = require('./elliptic/eddsa');
 8277
 8278},{"./elliptic/curve":22,"./elliptic/curves":25,"./elliptic/ec":26,"./elliptic/eddsa":29,"./elliptic/utils":33,"brorand":18}],20:[function(require,module,exports){
 8279'use strict';
 8280
 8281var BN = require('bn.js');
 8282var elliptic = require('../../elliptic');
 8283var utils = elliptic.utils;
 8284var getNAF = utils.getNAF;
 8285var getJSF = utils.getJSF;
 8286var assert = utils.assert;
 8287
 8288function BaseCurve(type, conf) {
 8289  this.type = type;
 8290  this.p = new BN(conf.p, 16);
 8291
 8292  // Use Montgomery, when there is no fast reduction for the prime
 8293  this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
 8294
 8295  // Useful for many curves
 8296  this.zero = new BN(0).toRed(this.red);
 8297  this.one = new BN(1).toRed(this.red);
 8298  this.two = new BN(2).toRed(this.red);
 8299
 8300  // Curve configuration, optional
 8301  this.n = conf.n && new BN(conf.n, 16);
 8302  this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
 8303
 8304  // Temporary arrays
 8305  this._wnafT1 = new Array(4);
 8306  this._wnafT2 = new Array(4);
 8307  this._wnafT3 = new Array(4);
 8308  this._wnafT4 = new Array(4);
 8309
 8310  // Generalized Greg Maxwell's trick
 8311  var adjustCount = this.n && this.p.div(this.n);
 8312  if (!adjustCount || adjustCount.cmpn(100) > 0) {
 8313    this.redN = null;
 8314  } else {
 8315    this._maxwellTrick = true;
 8316    this.redN = this.n.toRed(this.red);
 8317  }
 8318}
 8319module.exports = BaseCurve;
 8320
 8321BaseCurve.prototype.point = function point() {
 8322  throw new Error('Not implemented');
 8323};
 8324
 8325BaseCurve.prototype.validate = function validate() {
 8326  throw new Error('Not implemented');
 8327};
 8328
 8329BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
 8330  assert(p.precomputed);
 8331  var doubles = p._getDoubles();
 8332
 8333  var naf = getNAF(k, 1);
 8334  var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
 8335  I /= 3;
 8336
 8337  // Translate into more windowed form
 8338  var repr = [];
 8339  for (var j = 0; j < naf.length; j += doubles.step) {
 8340    var nafW = 0;
 8341    for (var k = j + doubles.step - 1; k >= j; k--)
 8342      nafW = (nafW << 1) + naf[k];
 8343    repr.push(nafW);
 8344  }
 8345
 8346  var a = this.jpoint(null, null, null);
 8347  var b = this.jpoint(null, null, null);
 8348  for (var i = I; i > 0; i--) {
 8349    for (var j = 0; j < repr.length; j++) {
 8350      var nafW = repr[j];
 8351      if (nafW === i)
 8352        b = b.mixedAdd(doubles.points[j]);
 8353      else if (nafW === -i)
 8354        b = b.mixedAdd(doubles.points[j].neg());
 8355    }
 8356    a = a.add(b);
 8357  }
 8358  return a.toP();
 8359};
 8360
 8361BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
 8362  var w = 4;
 8363
 8364  // Precompute window
 8365  var nafPoints = p._getNAFPoints(w);
 8366  w = nafPoints.wnd;
 8367  var wnd = nafPoints.points;
 8368
 8369  // Get NAF form
 8370  var naf = getNAF(k, w);
 8371
 8372  // Add `this`*(N+1) for every w-NAF index
 8373  var acc = this.jpoint(null, null, null);
 8374  for (var i = naf.length - 1; i >= 0; i--) {
 8375    // Count zeroes
 8376    for (var k = 0; i >= 0 && naf[i] === 0; i--)
 8377      k++;
 8378    if (i >= 0)
 8379      k++;
 8380    acc = acc.dblp(k);
 8381
 8382    if (i < 0)
 8383      break;
 8384    var z = naf[i];
 8385    assert(z !== 0);
 8386    if (p.type === 'affine') {
 8387      // J +- P
 8388      if (z > 0)
 8389        acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
 8390      else
 8391        acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
 8392    } else {
 8393      // J +- J
 8394      if (z > 0)
 8395        acc = acc.add(wnd[(z - 1) >> 1]);
 8396      else
 8397        acc = acc.add(wnd[(-z - 1) >> 1].neg());
 8398    }
 8399  }
 8400  return p.type === 'affine' ? acc.toP() : acc;
 8401};
 8402
 8403BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
 8404                                                       points,
 8405                                                       coeffs,
 8406                                                       len,
 8407                                                       jacobianResult) {
 8408  var wndWidth = this._wnafT1;
 8409  var wnd = this._wnafT2;
 8410  var naf = this._wnafT3;
 8411
 8412  // Fill all arrays
 8413  var max = 0;
 8414  for (var i = 0; i < len; i++) {
 8415    var p = points[i];
 8416    var nafPoints = p._getNAFPoints(defW);
 8417    wndWidth[i] = nafPoints.wnd;
 8418    wnd[i] = nafPoints.points;
 8419  }
 8420
 8421  // Comb small window NAFs
 8422  for (var i = len - 1; i >= 1; i -= 2) {
 8423    var a = i - 1;
 8424    var b = i;
 8425    if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
 8426      naf[a] = getNAF(coeffs[a], wndWidth[a]);
 8427      naf[b] = getNAF(coeffs[b], wndWidth[b]);
 8428      max = Math.max(naf[a].length, max);
 8429      max = Math.max(naf[b].length, max);
 8430      continue;
 8431    }
 8432
 8433    var comb = [
 8434      points[a], /* 1 */
 8435      null, /* 3 */
 8436      null, /* 5 */
 8437      points[b] /* 7 */
 8438    ];
 8439
 8440    // Try to avoid Projective points, if possible
 8441    if (points[a].y.cmp(points[b].y) === 0) {
 8442      comb[1] = points[a].add(points[b]);
 8443      comb[2] = points[a].toJ().mixedAdd(points[b].neg());
 8444    } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
 8445      comb[1] = points[a].toJ().mixedAdd(points[b]);
 8446      comb[2] = points[a].add(points[b].neg());
 8447    } else {
 8448      comb[1] = points[a].toJ().mixedAdd(points[b]);
 8449      comb[2] = points[a].toJ().mixedAdd(points[b].neg());
 8450    }
 8451
 8452    var index = [
 8453      -3, /* -1 -1 */
 8454      -1, /* -1 0 */
 8455      -5, /* -1 1 */
 8456      -7, /* 0 -1 */
 8457      0, /* 0 0 */
 8458      7, /* 0 1 */
 8459      5, /* 1 -1 */
 8460      1, /* 1 0 */
 8461      3  /* 1 1 */
 8462    ];
 8463
 8464    var jsf = getJSF(coeffs[a], coeffs[b]);
 8465    max = Math.max(jsf[0].length, max);
 8466    naf[a] = new Array(max);
 8467    naf[b] = new Array(max);
 8468    for (var j = 0; j < max; j++) {
 8469      var ja = jsf[0][j] | 0;
 8470      var jb = jsf[1][j] | 0;
 8471
 8472      naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
 8473      naf[b][j] = 0;
 8474      wnd[a] = comb;
 8475    }
 8476  }
 8477
 8478  var acc = this.jpoint(null, null, null);
 8479  var tmp = this._wnafT4;
 8480  for (var i = max; i >= 0; i--) {
 8481    var k = 0;
 8482
 8483    while (i >= 0) {
 8484      var zero = true;
 8485      for (var j = 0; j < len; j++) {
 8486        tmp[j] = naf[j][i] | 0;
 8487        if (tmp[j] !== 0)
 8488          zero = false;
 8489      }
 8490      if (!zero)
 8491        break;
 8492      k++;
 8493      i--;
 8494    }
 8495    if (i >= 0)
 8496      k++;
 8497    acc = acc.dblp(k);
 8498    if (i < 0)
 8499      break;
 8500
 8501    for (var j = 0; j < len; j++) {
 8502      var z = tmp[j];
 8503      var p;
 8504      if (z === 0)
 8505        continue;
 8506      else if (z > 0)
 8507        p = wnd[j][(z - 1) >> 1];
 8508      else if (z < 0)
 8509        p = wnd[j][(-z - 1) >> 1].neg();
 8510
 8511      if (p.type === 'affine')
 8512        acc = acc.mixedAdd(p);
 8513      else
 8514        acc = acc.add(p);
 8515    }
 8516  }
 8517  // Zeroify references
 8518  for (var i = 0; i < len; i++)
 8519    wnd[i] = null;
 8520
 8521  if (jacobianResult)
 8522    return acc;
 8523  else
 8524    return acc.toP();
 8525};
 8526
 8527function BasePoint(curve, type) {
 8528  this.curve = curve;
 8529  this.type = type;
 8530  this.precomputed = null;
 8531}
 8532BaseCurve.BasePoint = BasePoint;
 8533
 8534BasePoint.prototype.eq = function eq(/*other*/) {
 8535  throw new Error('Not implemented');
 8536};
 8537
 8538BasePoint.prototype.validate = function validate() {
 8539  return this.curve.validate(this);
 8540};
 8541
 8542BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
 8543  bytes = utils.toArray(bytes, enc);
 8544
 8545  var len = this.p.byteLength();
 8546
 8547  // uncompressed, hybrid-odd, hybrid-even
 8548  if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
 8549      bytes.length - 1 === 2 * len) {
 8550    if (bytes[0] === 0x06)
 8551      assert(bytes[bytes.length - 1] % 2 === 0);
 8552    else if (bytes[0] === 0x07)
 8553      assert(bytes[bytes.length - 1] % 2 === 1);
 8554
 8555    var res =  this.point(bytes.slice(1, 1 + len),
 8556                          bytes.slice(1 + len, 1 + 2 * len));
 8557
 8558    return res;
 8559  } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
 8560              bytes.length - 1 === len) {
 8561    return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
 8562  }
 8563  throw new Error('Unknown point format');
 8564};
 8565
 8566BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
 8567  return this.encode(enc, true);
 8568};
 8569
 8570BasePoint.prototype._encode = function _encode(compact) {
 8571  var len = this.curve.p.byteLength();
 8572  var x = this.getX().toArray('be', len);
 8573
 8574  if (compact)
 8575    return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
 8576
 8577  return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
 8578};
 8579
 8580BasePoint.prototype.encode = function encode(enc, compact) {
 8581  return utils.encode(this._encode(compact), enc);
 8582};
 8583
 8584BasePoint.prototype.precompute = function precompute(power) {
 8585  if (this.precomputed)
 8586    return this;
 8587
 8588  var precomputed = {
 8589    doubles: null,
 8590    naf: null,
 8591    beta: null
 8592  };
 8593  precomputed.naf = this._getNAFPoints(8);
 8594  precomputed.doubles = this._getDoubles(4, power);
 8595  precomputed.beta = this._getBeta();
 8596  this.precomputed = precomputed;
 8597
 8598  return this;
 8599};
 8600
 8601BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
 8602  if (!this.precomputed)
 8603    return false;
 8604
 8605  var doubles = this.precomputed.doubles;
 8606  if (!doubles)
 8607    return false;
 8608
 8609  return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
 8610};
 8611
 8612BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
 8613  if (this.precomputed && this.precomputed.doubles)
 8614    return this.precomputed.doubles;
 8615
 8616  var doubles = [ this ];
 8617  var acc = this;
 8618  for (var i = 0; i < power; i += step) {
 8619    for (var j = 0; j < step; j++)
 8620      acc = acc.dbl();
 8621    doubles.push(acc);
 8622  }
 8623  return {
 8624    step: step,
 8625    points: doubles
 8626  };
 8627};
 8628
 8629BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
 8630  if (this.precomputed && this.precomputed.naf)
 8631    return this.precomputed.naf;
 8632
 8633  var res = [ this ];
 8634  var max = (1 << wnd) - 1;
 8635  var dbl = max === 1 ? null : this.dbl();
 8636  for (var i = 1; i < max; i++)
 8637    res[i] = res[i - 1].add(dbl);
 8638  return {
 8639    wnd: wnd,
 8640    points: res
 8641  };
 8642};
 8643
 8644BasePoint.prototype._getBeta = function _getBeta() {
 8645  return null;
 8646};
 8647
 8648BasePoint.prototype.dblp = function dblp(k) {
 8649  var r = this;
 8650  for (var i = 0; i < k; i++)
 8651    r = r.dbl();
 8652  return r;
 8653};
 8654
 8655},{"../../elliptic":19,"bn.js":17}],21:[function(require,module,exports){
 8656'use strict';
 8657
 8658var curve = require('../curve');
 8659var elliptic = require('../../elliptic');
 8660var BN = require('bn.js');
 8661var inherits = require('inherits');
 8662var Base = curve.base;
 8663
 8664var assert = elliptic.utils.assert;
 8665
 8666function EdwardsCurve(conf) {
 8667  // NOTE: Important as we are creating point in Base.call()
 8668  this.twisted = (conf.a | 0) !== 1;
 8669  this.mOneA = this.twisted && (conf.a | 0) === -1;
 8670  this.extended = this.mOneA;
 8671
 8672  Base.call(this, 'edwards', conf);
 8673
 8674  this.a = new BN(conf.a, 16).umod(this.red.m);
 8675  this.a = this.a.toRed(this.red);
 8676  this.c = new BN(conf.c, 16).toRed(this.red);
 8677  this.c2 = this.c.redSqr();
 8678  this.d = new BN(conf.d, 16).toRed(this.red);
 8679  this.dd = this.d.redAdd(this.d);
 8680
 8681  assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
 8682  this.oneC = (conf.c | 0) === 1;
 8683}
 8684inherits(EdwardsCurve, Base);
 8685module.exports = EdwardsCurve;
 8686
 8687EdwardsCurve.prototype._mulA = function _mulA(num) {
 8688  if (this.mOneA)
 8689    return num.redNeg();
 8690  else
 8691    return this.a.redMul(num);
 8692};
 8693
 8694EdwardsCurve.prototype._mulC = function _mulC(num) {
 8695  if (this.oneC)
 8696    return num;
 8697  else
 8698    return this.c.redMul(num);
 8699};
 8700
 8701// Just for compatibility with Short curve
 8702EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
 8703  return this.point(x, y, z, t);
 8704};
 8705
 8706EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
 8707  x = new BN(x, 16);
 8708  if (!x.red)
 8709    x = x.toRed(this.red);
 8710
 8711  var x2 = x.redSqr();
 8712  var rhs = this.c2.redSub(this.a.redMul(x2));
 8713  var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
 8714
 8715  var y2 = rhs.redMul(lhs.redInvm());
 8716  var y = y2.redSqrt();
 8717  if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
 8718    throw new Error('invalid point');
 8719
 8720  var isOdd = y.fromRed().isOdd();
 8721  if (odd && !isOdd || !odd && isOdd)
 8722    y = y.redNeg();
 8723
 8724  return this.point(x, y);
 8725};
 8726
 8727EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
 8728  y = new BN(y, 16);
 8729  if (!y.red)
 8730    y = y.toRed(this.red);
 8731
 8732  // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
 8733  var y2 = y.redSqr();
 8734  var lhs = y2.redSub(this.c2);
 8735  var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
 8736  var x2 = lhs.redMul(rhs.redInvm());
 8737
 8738  if (x2.cmp(this.zero) === 0) {
 8739    if (odd)
 8740      throw new Error('invalid point');
 8741    else
 8742      return this.point(this.zero, y);
 8743  }
 8744
 8745  var x = x2.redSqrt();
 8746  if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
 8747    throw new Error('invalid point');
 8748
 8749  if (x.fromRed().isOdd() !== odd)
 8750    x = x.redNeg();
 8751
 8752  return this.point(x, y);
 8753};
 8754
 8755EdwardsCurve.prototype.validate = function validate(point) {
 8756  if (point.isInfinity())
 8757    return true;
 8758
 8759  // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
 8760  point.normalize();
 8761
 8762  var x2 = point.x.redSqr();
 8763  var y2 = point.y.redSqr();
 8764  var lhs = x2.redMul(this.a).redAdd(y2);
 8765  var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
 8766
 8767  return lhs.cmp(rhs) === 0;
 8768};
 8769
 8770function Point(curve, x, y, z, t) {
 8771  Base.BasePoint.call(this, curve, 'projective');
 8772  if (x === null && y === null && z === null) {
 8773    this.x = this.curve.zero;
 8774    this.y = this.curve.one;
 8775    this.z = this.curve.one;
 8776    this.t = this.curve.zero;
 8777    this.zOne = true;
 8778  } else {
 8779    this.x = new BN(x, 16);
 8780    this.y = new BN(y, 16);
 8781    this.z = z ? new BN(z, 16) : this.curve.one;
 8782    this.t = t && new BN(t, 16);
 8783    if (!this.x.red)
 8784      this.x = this.x.toRed(this.curve.red);
 8785    if (!this.y.red)
 8786      this.y = this.y.toRed(this.curve.red);
 8787    if (!this.z.red)
 8788      this.z = this.z.toRed(this.curve.red);
 8789    if (this.t && !this.t.red)
 8790      this.t = this.t.toRed(this.curve.red);
 8791    this.zOne = this.z === this.curve.one;
 8792
 8793    // Use extended coordinates
 8794    if (this.curve.extended && !this.t) {
 8795      this.t = this.x.redMul(this.y);
 8796      if (!this.zOne)
 8797        this.t = this.t.redMul(this.z.redInvm());
 8798    }
 8799  }
 8800}
 8801inherits(Point, Base.BasePoint);
 8802
 8803EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
 8804  return Point.fromJSON(this, obj);
 8805};
 8806
 8807EdwardsCurve.prototype.point = function point(x, y, z, t) {
 8808  return new Point(this, x, y, z, t);
 8809};
 8810
 8811Point.fromJSON = function fromJSON(curve, obj) {
 8812  return new Point(curve, obj[0], obj[1], obj[2]);
 8813};
 8814
 8815Point.prototype.inspect = function inspect() {
 8816  if (this.isInfinity())
 8817    return '<EC Point Infinity>';
 8818  return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
 8819      ' y: ' + this.y.fromRed().toString(16, 2) +
 8820      ' z: ' + this.z.fromRed().toString(16, 2) + '>';
 8821};
 8822
 8823Point.prototype.isInfinity = function isInfinity() {
 8824  // XXX This code assumes that zero is always zero in red
 8825  return this.x.cmpn(0) === 0 &&
 8826    (this.y.cmp(this.z) === 0 ||
 8827    (this.zOne && this.y.cmp(this.curve.c) === 0));
 8828};
 8829
 8830Point.prototype._extDbl = function _extDbl() {
 8831  // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
 8832  //     #doubling-dbl-2008-hwcd
 8833  // 4M + 4S
 8834
 8835  // A = X1^2
 8836  var a = this.x.redSqr();
 8837  // B = Y1^2
 8838  var b = this.y.redSqr();
 8839  // C = 2 * Z1^2
 8840  var c = this.z.redSqr();
 8841  c = c.redIAdd(c);
 8842  // D = a * A
 8843  var d = this.curve._mulA(a);
 8844  // E = (X1 + Y1)^2 - A - B
 8845  var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
 8846  // G = D + B
 8847  var g = d.redAdd(b);
 8848  // F = G - C
 8849  var f = g.redSub(c);
 8850  // H = D - B
 8851  var h = d.redSub(b);
 8852  // X3 = E * F
 8853  var nx = e.redMul(f);
 8854  // Y3 = G * H
 8855  var ny = g.redMul(h);
 8856  // T3 = E * H
 8857  var nt = e.redMul(h);
 8858  // Z3 = F * G
 8859  var nz = f.redMul(g);
 8860  return this.curve.point(nx, ny, nz, nt);
 8861};
 8862
 8863Point.prototype._projDbl = function _projDbl() {
 8864  // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
 8865  //     #doubling-dbl-2008-bbjlp
 8866  //     #doubling-dbl-2007-bl
 8867  // and others
 8868  // Generally 3M + 4S or 2M + 4S
 8869
 8870  // B = (X1 + Y1)^2
 8871  var b = this.x.redAdd(this.y).redSqr();
 8872  // C = X1^2
 8873  var c = this.x.redSqr();
 8874  // D = Y1^2
 8875  var d = this.y.redSqr();
 8876
 8877  var nx;
 8878  var ny;
 8879  var nz;
 8880  if (this.curve.twisted) {
 8881    // E = a * C
 8882    var e = this.curve._mulA(c);
 8883    // F = E + D
 8884    var f = e.redAdd(d);
 8885    if (this.zOne) {
 8886      // X3 = (B - C - D) * (F - 2)
 8887      nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
 8888      // Y3 = F * (E - D)
 8889      ny = f.redMul(e.redSub(d));
 8890      // Z3 = F^2 - 2 * F
 8891      nz = f.redSqr().redSub(f).redSub(f);
 8892    } else {
 8893      // H = Z1^2
 8894      var h = this.z.redSqr();
 8895      // J = F - 2 * H
 8896      var j = f.redSub(h).redISub(h);
 8897      // X3 = (B-C-D)*J
 8898      nx = b.redSub(c).redISub(d).redMul(j);
 8899      // Y3 = F * (E - D)
 8900      ny = f.redMul(e.redSub(d));
 8901      // Z3 = F * J
 8902      nz = f.redMul(j);
 8903    }
 8904  } else {
 8905    // E = C + D
 8906    var e = c.redAdd(d);
 8907    // H = (c * Z1)^2
 8908    var h = this.curve._mulC(this.z).redSqr();
 8909    // J = E - 2 * H
 8910    var j = e.redSub(h).redSub(h);
 8911    // X3 = c * (B - E) * J
 8912    nx = this.curve._mulC(b.redISub(e)).redMul(j);
 8913    // Y3 = c * E * (C - D)
 8914    ny = this.curve._mulC(e).redMul(c.redISub(d));
 8915    // Z3 = E * J
 8916    nz = e.redMul(j);
 8917  }
 8918  return this.curve.point(nx, ny, nz);
 8919};
 8920
 8921Point.prototype.dbl = function dbl() {
 8922  if (this.isInfinity())
 8923    return this;
 8924
 8925  // Double in extended coordinates
 8926  if (this.curve.extended)
 8927    return this._extDbl();
 8928  else
 8929    return this._projDbl();
 8930};
 8931
 8932Point.prototype._extAdd = function _extAdd(p) {
 8933  // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
 8934  //     #addition-add-2008-hwcd-3
 8935  // 8M
 8936
 8937  // A = (Y1 - X1) * (Y2 - X2)
 8938  var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
 8939  // B = (Y1 + X1) * (Y2 + X2)
 8940  var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
 8941  // C = T1 * k * T2
 8942  var c = this.t.redMul(this.curve.dd).redMul(p.t);
 8943  // D = Z1 * 2 * Z2
 8944  var d = this.z.redMul(p.z.redAdd(p.z));
 8945  // E = B - A
 8946  var e = b.redSub(a);
 8947  // F = D - C
 8948  var f = d.redSub(c);
 8949  // G = D + C
 8950  var g = d.redAdd(c);
 8951  // H = B + A
 8952  var h = b.redAdd(a);
 8953  // X3 = E * F
 8954  var nx = e.redMul(f);
 8955  // Y3 = G * H
 8956  var ny = g.redMul(h);
 8957  // T3 = E * H
 8958  var nt = e.redMul(h);
 8959  // Z3 = F * G
 8960  var nz = f.redMul(g);
 8961  return this.curve.point(nx, ny, nz, nt);
 8962};
 8963
 8964Point.prototype._projAdd = function _projAdd(p) {
 8965  // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
 8966  //     #addition-add-2008-bbjlp
 8967  //     #addition-add-2007-bl
 8968  // 10M + 1S
 8969
 8970  // A = Z1 * Z2
 8971  var a = this.z.redMul(p.z);
 8972  // B = A^2
 8973  var b = a.redSqr();
 8974  // C = X1 * X2
 8975  var c = this.x.redMul(p.x);
 8976  // D = Y1 * Y2
 8977  var d = this.y.redMul(p.y);
 8978  // E = d * C * D
 8979  var e = this.curve.d.redMul(c).redMul(d);
 8980  // F = B - E
 8981  var f = b.redSub(e);
 8982  // G = B + E
 8983  var g = b.redAdd(e);
 8984  // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
 8985  var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
 8986  var nx = a.redMul(f).redMul(tmp);
 8987  var ny;
 8988  var nz;
 8989  if (this.curve.twisted) {
 8990    // Y3 = A * G * (D - a * C)
 8991    ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
 8992    // Z3 = F * G
 8993    nz = f.redMul(g);
 8994  } else {
 8995    // Y3 = A * G * (D - C)
 8996    ny = a.redMul(g).redMul(d.redSub(c));
 8997    // Z3 = c * F * G
 8998    nz = this.curve._mulC(f).redMul(g);
 8999  }
 9000  return this.curve.point(nx, ny, nz);
 9001};
 9002
 9003Point.prototype.add = function add(p) {
 9004  if (this.isInfinity())
 9005    return p;
 9006  if (p.isInfinity())
 9007    return this;
 9008
 9009  if (this.curve.extended)
 9010    return this._extAdd(p);
 9011  else
 9012    return this._projAdd(p);
 9013};
 9014
 9015Point.prototype.mul = function mul(k) {
 9016  if (this._hasDoubles(k))
 9017    return this.curve._fixedNafMul(this, k);
 9018  else
 9019    return this.curve._wnafMul(this, k);
 9020};
 9021
 9022Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
 9023  return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
 9024};
 9025
 9026Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
 9027  return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
 9028};
 9029
 9030Point.prototype.normalize = function normalize() {
 9031  if (this.zOne)
 9032    return this;
 9033
 9034  // Normalize coordinates
 9035  var zi = this.z.redInvm();
 9036  this.x = this.x.redMul(zi);
 9037  this.y = this.y.redMul(zi);
 9038  if (this.t)
 9039    this.t = this.t.redMul(zi);
 9040  this.z = this.curve.one;
 9041  this.zOne = true;
 9042  return this;
 9043};
 9044
 9045Point.prototype.neg = function neg() {
 9046  return this.curve.point(this.x.redNeg(),
 9047                          this.y,
 9048                          this.z,
 9049                          this.t && this.t.redNeg());
 9050};
 9051
 9052Point.prototype.getX = function getX() {
 9053  this.normalize();
 9054  return this.x.fromRed();
 9055};
 9056
 9057Point.prototype.getY = function getY() {
 9058  this.normalize();
 9059  return this.y.fromRed();
 9060};
 9061
 9062Point.prototype.eq = function eq(other) {
 9063  return this === other ||
 9064         this.getX().cmp(other.getX()) === 0 &&
 9065         this.getY().cmp(other.getY()) === 0;
 9066};
 9067
 9068Point.prototype.eqXToP = function eqXToP(x) {
 9069  var rx = x.toRed(this.curve.red).redMul(this.z);
 9070  if (this.x.cmp(rx) === 0)
 9071    return true;
 9072
 9073  var xc = x.clone();
 9074  var t = this.curve.redN.redMul(this.z);
 9075  for (;;) {
 9076    xc.iadd(this.curve.n);
 9077    if (xc.cmp(this.curve.p) >= 0)
 9078      return false;
 9079
 9080    rx.redIAdd(t);
 9081    if (this.x.cmp(rx) === 0)
 9082      return true;
 9083  }
 9084};
 9085
 9086// Compatibility with BaseCurve
 9087Point.prototype.toP = Point.prototype.normalize;
 9088Point.prototype.mixedAdd = Point.prototype.add;
 9089
 9090},{"../../elliptic":19,"../curve":22,"bn.js":17,"inherits":48}],22:[function(require,module,exports){
 9091'use strict';
 9092
 9093var curve = exports;
 9094
 9095curve.base = require('./base');
 9096curve.short = require('./short');
 9097curve.mont = require('./mont');
 9098curve.edwards = require('./edwards');
 9099
 9100},{"./base":20,"./edwards":21,"./mont":23,"./short":24}],23:[function(require,module,exports){
 9101'use strict';
 9102
 9103var curve = require('../curve');
 9104var BN = require('bn.js');
 9105var inherits = require('inherits');
 9106var Base = curve.base;
 9107
 9108var elliptic = require('../../elliptic');
 9109var utils = elliptic.utils;
 9110
 9111function MontCurve(conf) {
 9112  Base.call(this, 'mont', conf);
 9113
 9114  this.a = new BN(conf.a, 16).toRed(this.red);
 9115  this.b = new BN(conf.b, 16).toRed(this.red);
 9116  this.i4 = new BN(4).toRed(this.red).redInvm();
 9117  this.two = new BN(2).toRed(this.red);
 9118  // Note: this implementation is according to the original paper
 9119  // by P. Montgomery, NOT the one by D. J. Bernstein.
 9120  this.a24 = this.i4.redMul(this.a.redAdd(this.two));
 9121}
 9122inherits(MontCurve, Base);
 9123module.exports = MontCurve;
 9124
 9125MontCurve.prototype.validate = function validate(point) {
 9126  var x = point.normalize().x;
 9127  var x2 = x.redSqr();
 9128  var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
 9129  var y = rhs.redSqrt();
 9130
 9131  return y.redSqr().cmp(rhs) === 0;
 9132};
 9133
 9134function Point(curve, x, z) {
 9135  Base.BasePoint.call(this, curve, 'projective');
 9136  if (x === null && z === null) {
 9137    this.x = this.curve.one;
 9138    this.z = this.curve.zero;
 9139  } else {
 9140    this.x = new BN(x, 16);
 9141    this.z = new BN(z, 16);
 9142    if (!this.x.red)
 9143      this.x = this.x.toRed(this.curve.red);
 9144    if (!this.z.red)
 9145      this.z = this.z.toRed(this.curve.red);
 9146  }
 9147}
 9148inherits(Point, Base.BasePoint);
 9149
 9150MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
 9151  var bytes = utils.toArray(bytes, enc);
 9152
 9153  // TODO Curve448
 9154  // Montgomery curve points must be represented in the compressed format
 9155  // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
 9156  if (bytes.length === 33 && bytes[0] === 0x40)
 9157    bytes = bytes.slice(1, 33).reverse(); // point must be little-endian
 9158  if (bytes.length !== 32)
 9159    throw new Error('Unknown point compression format');
 9160  return this.point(bytes, 1);
 9161};
 9162
 9163MontCurve.prototype.point = function point(x, z) {
 9164  return new Point(this, x, z);
 9165};
 9166
 9167MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
 9168  return Point.fromJSON(this, obj);
 9169};
 9170
 9171Point.prototype.precompute = function precompute() {
 9172  // No-op
 9173};
 9174
 9175Point.prototype._encode = function _encode(compact) {
 9176  var len = this.curve.p.byteLength();
 9177
 9178  // Note: the output should always be little-endian
 9179  // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
 9180  if (compact) {
 9181    return [ 0x40 ].concat(this.getX().toArray('le', len));
 9182  } else {
 9183    return this.getX().toArray('be', len);
 9184  }
 9185};
 9186
 9187Point.fromJSON = function fromJSON(curve, obj) {
 9188  return new Point(curve, obj[0], obj[1] || curve.one);
 9189};
 9190
 9191Point.prototype.inspect = function inspect() {
 9192  if (this.isInfinity())
 9193    return '<EC Point Infinity>';
 9194  return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
 9195      ' z: ' + this.z.fromRed().toString(16, 2) + '>';
 9196};
 9197
 9198Point.prototype.isInfinity = function isInfinity() {
 9199  // XXX This code assumes that zero is always zero in red
 9200  return this.z.cmpn(0) === 0;
 9201};
 9202
 9203Point.prototype.dbl = function dbl() {
 9204  // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
 9205  // 2M + 2S + 4A
 9206
 9207  // A = X1 + Z1
 9208  var a = this.x.redAdd(this.z);
 9209  // AA = A^2
 9210  var aa = a.redSqr();
 9211  // B = X1 - Z1
 9212  var b = this.x.redSub(this.z);
 9213  // BB = B^2
 9214  var bb = b.redSqr();
 9215  // C = AA - BB
 9216  var c = aa.redSub(bb);
 9217  // X3 = AA * BB
 9218  var nx = aa.redMul(bb);
 9219  // Z3 = C * (BB + A24 * C)
 9220  var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
 9221  return this.curve.point(nx, nz);
 9222};
 9223
 9224Point.prototype.add = function add() {
 9225  throw new Error('Not supported on Montgomery curve');
 9226};
 9227
 9228Point.prototype.diffAdd = function diffAdd(p, diff) {
 9229  // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
 9230  // 4M + 2S + 6A
 9231
 9232  // A = X2 + Z2
 9233  var a = this.x.redAdd(this.z);
 9234  // B = X2 - Z2
 9235  var b = this.x.redSub(this.z);
 9236  // C = X3 + Z3
 9237  var c = p.x.redAdd(p.z);
 9238  // D = X3 - Z3
 9239  var d = p.x.redSub(p.z);
 9240  // DA = D * A
 9241  var da = d.redMul(a);
 9242  // CB = C * B
 9243  var cb = c.redMul(b);
 9244  // X5 = Z1 * (DA + CB)^2
 9245  var nx = diff.z.redMul(da.redAdd(cb).redSqr());
 9246  // Z5 = X1 * (DA - CB)^2
 9247  var nz = diff.x.redMul(da.redISub(cb).redSqr());
 9248  return this.curve.point(nx, nz);
 9249};
 9250
 9251Point.prototype.mul = function mul(k) {
 9252  k = new BN(k, 16);
 9253
 9254  var t = k.clone();
 9255  var a = this; // (N / 2) * Q + Q
 9256  var b = this.curve.point(null, null); // (N / 2) * Q
 9257  var c = this; // Q
 9258
 9259  for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
 9260    bits.push(t.andln(1));
 9261
 9262  for (var i = bits.length - 1; i >= 0; i--) {
 9263    if (bits[i] === 0) {
 9264      // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
 9265      a = a.diffAdd(b, c);
 9266      // N * Q = 2 * ((N / 2) * Q + Q))
 9267      b = b.dbl();
 9268    } else {
 9269      // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
 9270      b = a.diffAdd(b, c);
 9271      // N * Q + Q = 2 * ((N / 2) * Q + Q)
 9272      a = a.dbl();
 9273    }
 9274  }
 9275  return b;
 9276};
 9277
 9278Point.prototype.mulAdd = function mulAdd() {
 9279  throw new Error('Not supported on Montgomery curve');
 9280};
 9281
 9282Point.prototype.jumlAdd = function jumlAdd() {
 9283  throw new Error('Not supported on Montgomery curve');
 9284};
 9285
 9286Point.prototype.eq = function eq(other) {
 9287  return this.getX().cmp(other.getX()) === 0;
 9288};
 9289
 9290Point.prototype.normalize = function normalize() {
 9291  this.x = this.x.redMul(this.z.redInvm());
 9292  this.z = this.curve.one;
 9293  return this;
 9294};
 9295
 9296Point.prototype.getX = function getX() {
 9297  // Normalize coordinates
 9298  this.normalize();
 9299
 9300  return this.x.fromRed();
 9301};
 9302
 9303},{"../../elliptic":19,"../curve":22,"bn.js":17,"inherits":48}],24:[function(require,module,exports){
 9304'use strict';
 9305
 9306var curve = require('../curve');
 9307var elliptic = require('../../elliptic');
 9308var BN = require('bn.js');
 9309var inherits = require('inherits');
 9310var Base = curve.base;
 9311
 9312var assert = elliptic.utils.assert;
 9313
 9314function ShortCurve(conf) {
 9315  Base.call(this, 'short', conf);
 9316
 9317  this.a = new BN(conf.a, 16).toRed(this.red);
 9318  this.b = new BN(conf.b, 16).toRed(this.red);
 9319  this.tinv = this.two.redInvm();
 9320
 9321  this.zeroA = this.a.fromRed().cmpn(0) === 0;
 9322  this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
 9323
 9324  // If the curve is endomorphic, precalculate beta and lambda
 9325  this.endo = this._getEndomorphism(conf);
 9326  this._endoWnafT1 = new Array(4);
 9327  this._endoWnafT2 = new Array(4);
 9328}
 9329inherits(ShortCurve, Base);
 9330module.exports = ShortCurve;
 9331
 9332ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
 9333  // No efficient endomorphism
 9334  if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
 9335    return;
 9336
 9337  // Compute beta and lambda, that lambda * P = (beta * Px; Py)
 9338  var beta;
 9339  var lambda;
 9340  if (conf.beta) {
 9341    beta = new BN(conf.beta, 16).toRed(this.red);
 9342  } else {
 9343    var betas = this._getEndoRoots(this.p);
 9344    // Choose the smallest beta
 9345    beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
 9346    beta = beta.toRed(this.red);
 9347  }
 9348  if (conf.lambda) {
 9349    lambda = new BN(conf.lambda, 16);
 9350  } else {
 9351    // Choose the lambda that is matching selected beta
 9352    var lambdas = this._getEndoRoots(this.n);
 9353    if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
 9354      lambda = lambdas[0];
 9355    } else {
 9356      lambda = lambdas[1];
 9357      assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
 9358    }
 9359  }
 9360
 9361  // Get basis vectors, used for balanced length-two representation
 9362  var basis;
 9363  if (conf.basis) {
 9364    basis = conf.basis.map(function(vec) {
 9365      return {
 9366        a: new BN(vec.a, 16),
 9367        b: new BN(vec.b, 16)
 9368      };
 9369    });
 9370  } else {
 9371    basis = this._getEndoBasis(lambda);
 9372  }
 9373
 9374  return {
 9375    beta: beta,
 9376    lambda: lambda,
 9377    basis: basis
 9378  };
 9379};
 9380
 9381ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
 9382  // Find roots of for x^2 + x + 1 in F
 9383  // Root = (-1 +- Sqrt(-3)) / 2
 9384  //
 9385  var red = num === this.p ? this.red : BN.mont(num);
 9386  var tinv = new BN(2).toRed(red).redInvm();
 9387  var ntinv = tinv.redNeg();
 9388
 9389  var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);
 9390
 9391  var l1 = ntinv.redAdd(s).fromRed();
 9392  var l2 = ntinv.redSub(s).fromRed();
 9393  return [ l1, l2 ];
 9394};
 9395
 9396ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
 9397  // aprxSqrt >= sqrt(this.n)
 9398  var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
 9399
 9400  // 3.74
 9401  // Run EGCD, until r(L + 1) < aprxSqrt
 9402  var u = lambda;
 9403  var v = this.n.clone();
 9404  var x1 = new BN(1);
 9405  var y1 = new BN(0);
 9406  var x2 = new BN(0);
 9407  var y2 = new BN(1);
 9408
 9409  // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
 9410  var a0;
 9411  var b0;
 9412  // First vector
 9413  var a1;
 9414  var b1;
 9415  // Second vector
 9416  var a2;
 9417  var b2;
 9418
 9419  var prevR;
 9420  var i = 0;
 9421  var r;
 9422  var x;
 9423  while (u.cmpn(0) !== 0) {
 9424    var q = v.div(u);
 9425    r = v.sub(q.mul(u));
 9426    x = x2.sub(q.mul(x1));
 9427    var y = y2.sub(q.mul(y1));
 9428
 9429    if (!a1 && r.cmp(aprxSqrt) < 0) {
 9430      a0 = prevR.neg();
 9431      b0 = x1;
 9432      a1 = r.neg();
 9433      b1 = x;
 9434    } else if (a1 && ++i === 2) {
 9435      break;
 9436    }
 9437    prevR = r;
 9438
 9439    v = u;
 9440    u = r;
 9441    x2 = x1;
 9442    x1 = x;
 9443    y2 = y1;
 9444    y1 = y;
 9445  }
 9446  a2 = r.neg();
 9447  b2 = x;
 9448
 9449  var len1 = a1.sqr().add(b1.sqr());
 9450  var len2 = a2.sqr().add(b2.sqr());
 9451  if (len2.cmp(len1) >= 0) {
 9452    a2 = a0;
 9453    b2 = b0;
 9454  }
 9455
 9456  // Normalize signs
 9457  if (a1.negative) {
 9458    a1 = a1.neg();
 9459    b1 = b1.neg();
 9460  }
 9461  if (a2.negative) {
 9462    a2 = a2.neg();
 9463    b2 = b2.neg();
 9464  }
 9465
 9466  return [
 9467    { a: a1, b: b1 },
 9468    { a: a2, b: b2 }
 9469  ];
 9470};
 9471
 9472ShortCurve.prototype._endoSplit = function _endoSplit(k) {
 9473  var basis = this.endo.basis;
 9474  var v1 = basis[0];
 9475  var v2 = basis[1];
 9476
 9477  var c1 = v2.b.mul(k).divRound(this.n);
 9478  var c2 = v1.b.neg().mul(k).divRound(this.n);
 9479
 9480  var p1 = c1.mul(v1.a);
 9481  var p2 = c2.mul(v2.a);
 9482  var q1 = c1.mul(v1.b);
 9483  var q2 = c2.mul(v2.b);
 9484
 9485  // Calculate answer
 9486  var k1 = k.sub(p1).sub(p2);
 9487  var k2 = q1.add(q2).neg();
 9488  return { k1: k1, k2: k2 };
 9489};
 9490
 9491ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
 9492  x = new BN(x, 16);
 9493  if (!x.red)
 9494    x = x.toRed(this.red);
 9495
 9496  var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
 9497  var y = y2.redSqrt();
 9498  if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
 9499    throw new Error('invalid point');
 9500
 9501  // XXX Is there any way to tell if the number is odd without converting it
 9502  // to non-red form?
 9503  var isOdd = y.fromRed().isOdd();
 9504  if (odd && !isOdd || !odd && isOdd)
 9505    y = y.redNeg();
 9506
 9507  return this.point(x, y);
 9508};
 9509
 9510ShortCurve.prototype.validate = function validate(point) {
 9511  if (point.inf)
 9512    return true;
 9513
 9514  var x = point.x;
 9515  var y = point.y;
 9516
 9517  var ax = this.a.redMul(x);
 9518  var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
 9519  return y.redSqr().redISub(rhs).cmpn(0) === 0;
 9520};
 9521
 9522ShortCurve.prototype._endoWnafMulAdd =
 9523    function _endoWnafMulAdd(points, coeffs, jacobianResult) {
 9524  var npoints = this._endoWnafT1;
 9525  var ncoeffs = this._endoWnafT2;
 9526  for (var i = 0; i < points.length; i++) {
 9527    var split = this._endoSplit(coeffs[i]);
 9528    var p = points[i];
 9529    var beta = p._getBeta();
 9530
 9531    if (split.k1.negative) {
 9532      split.k1.ineg();
 9533      p = p.neg(true);
 9534    }
 9535    if (split.k2.negative) {
 9536      split.k2.ineg();
 9537      beta = beta.neg(true);
 9538    }
 9539
 9540    npoints[i * 2] = p;
 9541    npoints[i * 2 + 1] = beta;
 9542    ncoeffs[i * 2] = split.k1;
 9543    ncoeffs[i * 2 + 1] = split.k2;
 9544  }
 9545  var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
 9546
 9547  // Clean-up references to points and coefficients
 9548  for (var j = 0; j < i * 2; j++) {
 9549    npoints[j] = null;
 9550    ncoeffs[j] = null;
 9551  }
 9552  return res;
 9553};
 9554
 9555function Point(curve, x, y, isRed) {
 9556  Base.BasePoint.call(this, curve, 'affine');
 9557  if (x === null && y === null) {
 9558    this.x = null;
 9559    this.y = null;
 9560    this.inf = true;
 9561  } else {
 9562    this.x = new BN(x, 16);
 9563    this.y = new BN(y, 16);
 9564    // Force redgomery representation when loading from JSON
 9565    if (isRed) {
 9566      this.x.forceRed(this.curve.red);
 9567      this.y.forceRed(this.curve.red);
 9568    }
 9569    if (!this.x.red)
 9570      this.x = this.x.toRed(this.curve.red);
 9571    if (!this.y.red)
 9572      this.y = this.y.toRed(this.curve.red);
 9573    this.inf = false;
 9574  }
 9575}
 9576inherits(Point, Base.BasePoint);
 9577
 9578ShortCurve.prototype.point = function point(x, y, isRed) {
 9579  return new Point(this, x, y, isRed);
 9580};
 9581
 9582ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
 9583  return Point.fromJSON(this, obj, red);
 9584};
 9585
 9586Point.prototype._getBeta = function _getBeta() {
 9587  if (!this.curve.endo)
 9588    return;
 9589
 9590  var pre = this.precomputed;
 9591  if (pre && pre.beta)
 9592    return pre.beta;
 9593
 9594  var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
 9595  if (pre) {
 9596    var curve = this.curve;
 9597    var endoMul = function(p) {
 9598      return curve.point(p.x.redMul(curve.endo.beta), p.y);
 9599    };
 9600    pre.beta = beta;
 9601    beta.precomputed = {
 9602      beta: null,
 9603      naf: pre.naf && {
 9604        wnd: pre.naf.wnd,
 9605        points: pre.naf.points.map(endoMul)
 9606      },
 9607      doubles: pre.doubles && {
 9608        step: pre.doubles.step,
 9609        points: pre.doubles.points.map(endoMul)
 9610      }
 9611    };
 9612  }
 9613  return beta;
 9614};
 9615
 9616Point.prototype.toJSON = function toJSON() {
 9617  if (!this.precomputed)
 9618    return [ this.x, this.y ];
 9619
 9620  return [ this.x, this.y, this.precomputed && {
 9621    doubles: this.precomputed.doubles && {
 9622      step: this.precomputed.doubles.step,
 9623      points: this.precomputed.doubles.points.slice(1)
 9624    },
 9625    naf: this.precomputed.naf && {
 9626      wnd: this.precomputed.naf.wnd,
 9627      points: this.precomputed.naf.points.slice(1)
 9628    }
 9629  } ];
 9630};
 9631
 9632Point.fromJSON = function fromJSON(curve, obj, red) {
 9633  if (typeof obj === 'string')
 9634    obj = JSON.parse(obj);
 9635  var res = curve.point(obj[0], obj[1], red);
 9636  if (!obj[2])
 9637    return res;
 9638
 9639  function obj2point(obj) {
 9640    return curve.point(obj[0], obj[1], red);
 9641  }
 9642
 9643  var pre = obj[2];
 9644  res.precomputed = {
 9645    beta: null,
 9646    doubles: pre.doubles && {
 9647      step: pre.doubles.step,
 9648      points: [ res ].concat(pre.doubles.points.map(obj2point))
 9649    },
 9650    naf: pre.naf && {
 9651      wnd: pre.naf.wnd,
 9652      points: [ res ].concat(pre.naf.points.map(obj2point))
 9653    }
 9654  };
 9655  return res;
 9656};
 9657
 9658Point.prototype.inspect = function inspect() {
 9659  if (this.isInfinity())
 9660    return '<EC Point Infinity>';
 9661  return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
 9662      ' y: ' + this.y.fromRed().toString(16, 2) + '>';
 9663};
 9664
 9665Point.prototype.isInfinity = function isInfinity() {
 9666  return this.inf;
 9667};
 9668
 9669Point.prototype.add = function add(p) {
 9670  // O + P = P
 9671  if (this.inf)
 9672    return p;
 9673
 9674  // P + O = P
 9675  if (p.inf)
 9676    return this;
 9677
 9678  // P + P = 2P
 9679  if (this.eq(p))
 9680    return this.dbl();
 9681
 9682  // P + (-P) = O
 9683  if (this.neg().eq(p))
 9684    return this.curve.point(null, null);
 9685
 9686  // P + Q = O
 9687  if (this.x.cmp(p.x) === 0)
 9688    return this.curve.point(null, null);
 9689
 9690  var c = this.y.redSub(p.y);
 9691  if (c.cmpn(0) !== 0)
 9692    c = c.redMul(this.x.redSub(p.x).redInvm());
 9693  var nx = c.redSqr().redISub(this.x).redISub(p.x);
 9694  var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
 9695  return this.curve.point(nx, ny);
 9696};
 9697
 9698Point.prototype.dbl = function dbl() {
 9699  if (this.inf)
 9700    return this;
 9701
 9702  // 2P = O
 9703  var ys1 = this.y.redAdd(this.y);
 9704  if (ys1.cmpn(0) === 0)
 9705    return this.curve.point(null, null);
 9706
 9707  var a = this.curve.a;
 9708
 9709  var x2 = this.x.redSqr();
 9710  var dyinv = ys1.redInvm();
 9711  var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
 9712
 9713  var nx = c.redSqr().redISub(this.x.redAdd(this.x));
 9714  var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
 9715  return this.curve.point(nx, ny);
 9716};
 9717
 9718Point.prototype.getX = function getX() {
 9719  return this.x.fromRed();
 9720};
 9721
 9722Point.prototype.getY = function getY() {
 9723  return this.y.fromRed();
 9724};
 9725
 9726Point.prototype.mul = function mul(k) {
 9727  k = new BN(k, 16);
 9728
 9729  if (this._hasDoubles(k))
 9730    return this.curve._fixedNafMul(this, k);
 9731  else if (this.curve.endo)
 9732    return this.curve._endoWnafMulAdd([ this ], [ k ]);
 9733  else
 9734    return this.curve._wnafMul(this, k);
 9735};
 9736
 9737Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
 9738  var points = [ this, p2 ];
 9739  var coeffs = [ k1, k2 ];
 9740  if (this.curve.endo)
 9741    return this.curve._endoWnafMulAdd(points, coeffs);
 9742  else
 9743    return this.curve._wnafMulAdd(1, points, coeffs, 2);
 9744};
 9745
 9746Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
 9747  var points = [ this, p2 ];
 9748  var coeffs = [ k1, k2 ];
 9749  if (this.curve.endo)
 9750    return this.curve._endoWnafMulAdd(points, coeffs, true);
 9751  else
 9752    return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
 9753};
 9754
 9755Point.prototype.eq = function eq(p) {
 9756  return this === p ||
 9757         this.inf === p.inf &&
 9758             (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
 9759};
 9760
 9761Point.prototype.neg = function neg(_precompute) {
 9762  if (this.inf)
 9763    return this;
 9764
 9765  var res = this.curve.point(this.x, this.y.redNeg());
 9766  if (_precompute && this.precomputed) {
 9767    var pre = this.precomputed;
 9768    var negate = function(p) {
 9769      return p.neg();
 9770    };
 9771    res.precomputed = {
 9772      naf: pre.naf && {
 9773        wnd: pre.naf.wnd,
 9774        points: pre.naf.points.map(negate)
 9775      },
 9776      doubles: pre.doubles && {
 9777        step: pre.doubles.step,
 9778        points: pre.doubles.points.map(negate)
 9779      }
 9780    };
 9781  }
 9782  return res;
 9783};
 9784
 9785Point.prototype.toJ = function toJ() {
 9786  if (this.inf)
 9787    return this.curve.jpoint(null, null, null);
 9788
 9789  var res = this.curve.jpoint(this.x, this.y, this.curve.one);
 9790  return res;
 9791};
 9792
 9793function JPoint(curve, x, y, z) {
 9794  Base.BasePoint.call(this, curve, 'jacobian');
 9795  if (x === null && y === null && z === null) {
 9796    this.x = this.curve.one;
 9797    this.y = this.curve.one;
 9798    this.z = new BN(0);
 9799  } else {
 9800    this.x = new BN(x, 16);
 9801    this.y = new BN(y, 16);
 9802    this.z = new BN(z, 16);
 9803  }
 9804  if (!this.x.red)
 9805    this.x = this.x.toRed(this.curve.red);
 9806  if (!this.y.red)
 9807    this.y = this.y.toRed(this.curve.red);
 9808  if (!this.z.red)
 9809    this.z = this.z.toRed(this.curve.red);
 9810
 9811  this.zOne = this.z === this.curve.one;
 9812}
 9813inherits(JPoint, Base.BasePoint);
 9814
 9815ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
 9816  return new JPoint(this, x, y, z);
 9817};
 9818
 9819JPoint.prototype.toP = function toP() {
 9820  if (this.isInfinity())
 9821    return this.curve.point(null, null);
 9822
 9823  var zinv = this.z.redInvm();
 9824  var zinv2 = zinv.redSqr();
 9825  var ax = this.x.redMul(zinv2);
 9826  var ay = this.y.redMul(zinv2).redMul(zinv);
 9827
 9828  return this.curve.point(ax, ay);
 9829};
 9830
 9831JPoint.prototype.neg = function neg() {
 9832  return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
 9833};
 9834
 9835JPoint.prototype.add = function add(p) {
 9836  // O + P = P
 9837  if (this.isInfinity())
 9838    return p;
 9839
 9840  // P + O = P
 9841  if (p.isInfinity())
 9842    return this;
 9843
 9844  // 12M + 4S + 7A
 9845  var pz2 = p.z.redSqr();
 9846  var z2 = this.z.redSqr();
 9847  var u1 = this.x.redMul(pz2);
 9848  var u2 = p.x.redMul(z2);
 9849  var s1 = this.y.redMul(pz2.redMul(p.z));
 9850  var s2 = p.y.redMul(z2.redMul(this.z));
 9851
 9852  var h = u1.redSub(u2);
 9853  var r = s1.redSub(s2);
 9854  if (h.cmpn(0) === 0) {
 9855    if (r.cmpn(0) !== 0)
 9856      return this.curve.jpoint(null, null, null);
 9857    else
 9858      return this.dbl();
 9859  }
 9860
 9861  var h2 = h.redSqr();
 9862  var h3 = h2.redMul(h);
 9863  var v = u1.redMul(h2);
 9864
 9865  var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
 9866  var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
 9867  var nz = this.z.redMul(p.z).redMul(h);
 9868
 9869  return this.curve.jpoint(nx, ny, nz);
 9870};
 9871
 9872JPoint.prototype.mixedAdd = function mixedAdd(p) {
 9873  // O + P = P
 9874  if (this.isInfinity())
 9875    return p.toJ();
 9876
 9877  // P + O = P
 9878  if (p.isInfinity())
 9879    return this;
 9880
 9881  // 8M + 3S + 7A
 9882  var z2 = this.z.redSqr();
 9883  var u1 = this.x;
 9884  var u2 = p.x.redMul(z2);
 9885  var s1 = this.y;
 9886  var s2 = p.y.redMul(z2).redMul(this.z);
 9887
 9888  var h = u1.redSub(u2);
 9889  var r = s1.redSub(s2);
 9890  if (h.cmpn(0) === 0) {
 9891    if (r.cmpn(0) !== 0)
 9892      return this.curve.jpoint(null, null, null);
 9893    else
 9894      return this.dbl();
 9895  }
 9896
 9897  var h2 = h.redSqr();
 9898  var h3 = h2.redMul(h);
 9899  var v = u1.redMul(h2);
 9900
 9901  var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
 9902  var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
 9903  var nz = this.z.redMul(h);
 9904
 9905  return this.curve.jpoint(nx, ny, nz);
 9906};
 9907
 9908JPoint.prototype.dblp = function dblp(pow) {
 9909  if (pow === 0)
 9910    return this;
 9911  if (this.isInfinity())
 9912    return this;
 9913  if (!pow)
 9914    return this.dbl();
 9915
 9916  if (this.curve.zeroA || this.curve.threeA) {
 9917    var r = this;
 9918    for (var i = 0; i < pow; i++)
 9919      r = r.dbl();
 9920    return r;
 9921  }
 9922
 9923  // 1M + 2S + 1A + N * (4S + 5M + 8A)
 9924  // N = 1 => 6M + 6S + 9A
 9925  var a = this.curve.a;
 9926  var tinv = this.curve.tinv;
 9927
 9928  var jx = this.x;
 9929  var jy = this.y;
 9930  var jz = this.z;
 9931  var jz4 = jz.redSqr().redSqr();
 9932
 9933  // Reuse results
 9934  var jyd = jy.redAdd(jy);
 9935  for (var i = 0; i < pow; i++) {
 9936    var jx2 = jx.redSqr();
 9937    var jyd2 = jyd.redSqr();
 9938    var jyd4 = jyd2.redSqr();
 9939    var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
 9940
 9941    var t1 = jx.redMul(jyd2);
 9942    var nx = c.redSqr().redISub(t1.redAdd(t1));
 9943    var t2 = t1.redISub(nx);
 9944    var dny = c.redMul(t2);
 9945    dny = dny.redIAdd(dny).redISub(jyd4);
 9946    var nz = jyd.redMul(jz);
 9947    if (i + 1 < pow)
 9948      jz4 = jz4.redMul(jyd4);
 9949
 9950    jx = nx;
 9951    jz = nz;
 9952    jyd = dny;
 9953  }
 9954
 9955  return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
 9956};
 9957
 9958JPoint.prototype.dbl = function dbl() {
 9959  if (this.isInfinity())
 9960    return this;
 9961
 9962  if (this.curve.zeroA)
 9963    return this._zeroDbl();
 9964  else if (this.curve.threeA)
 9965    return this._threeDbl();
 9966  else
 9967    return this._dbl();
 9968};
 9969
 9970JPoint.prototype._zeroDbl = function _zeroDbl() {
 9971  var nx;
 9972  var ny;
 9973  var nz;
 9974  // Z = 1
 9975  if (this.zOne) {
 9976    // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
 9977    //     #doubling-mdbl-2007-bl
 9978    // 1M + 5S + 14A
 9979
 9980    // XX = X1^2
 9981    var xx = this.x.redSqr();
 9982    // YY = Y1^2
 9983    var yy = this.y.redSqr();
 9984    // YYYY = YY^2
 9985    var yyyy = yy.redSqr();
 9986    // S = 2 * ((X1 + YY)^2 - XX - YYYY)
 9987    var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
 9988    s = s.redIAdd(s);
 9989    // M = 3 * XX + a; a = 0
 9990    var m = xx.redAdd(xx).redIAdd(xx);
 9991    // T = M ^ 2 - 2*S
 9992    var t = m.redSqr().redISub(s).redISub(s);
 9993
 9994    // 8 * YYYY
 9995    var yyyy8 = yyyy.redIAdd(yyyy);
 9996    yyyy8 = yyyy8.redIAdd(yyyy8);
 9997    yyyy8 = yyyy8.redIAdd(yyyy8);
 9998
 9999    // X3 = T
10000    nx = t;
10001    // Y3 = M * (S - T) - 8 * YYYY
10002    ny = m.redMul(s.redISub(t)).redISub(yyyy8);
10003    // Z3 = 2*Y1
10004    nz = this.y.redAdd(this.y);
10005  } else {
10006    // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
10007    //     #doubling-dbl-2009-l
10008    // 2M + 5S + 13A
10009
10010    // A = X1^2
10011    var a = this.x.redSqr();
10012    // B = Y1^2
10013    var b = this.y.redSqr();
10014    // C = B^2
10015    var c = b.redSqr();
10016    // D = 2 * ((X1 + B)^2 - A - C)
10017    var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
10018    d = d.redIAdd(d);
10019    // E = 3 * A
10020    var e = a.redAdd(a).redIAdd(a);
10021    // F = E^2
10022    var f = e.redSqr();
10023
10024    // 8 * C
10025    var c8 = c.redIAdd(c);
10026    c8 = c8.redIAdd(c8);
10027    c8 = c8.redIAdd(c8);
10028
10029    // X3 = F - 2 * D
10030    nx = f.redISub(d).redISub(d);
10031    // Y3 = E * (D - X3) - 8 * C
10032    ny = e.redMul(d.redISub(nx)).redISub(c8);
10033    // Z3 = 2 * Y1 * Z1
10034    nz = this.y.redMul(this.z);
10035    nz = nz.redIAdd(nz);
10036  }
10037
10038  return this.curve.jpoint(nx, ny, nz);
10039};
10040
10041JPoint.prototype._threeDbl = function _threeDbl() {
10042  var nx;
10043  var ny;
10044  var nz;
10045  // Z = 1
10046  if (this.zOne) {
10047    // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
10048    //     #doubling-mdbl-2007-bl
10049    // 1M + 5S + 15A
10050
10051    // XX = X1^2
10052    var xx = this.x.redSqr();
10053    // YY = Y1^2
10054    var yy = this.y.redSqr();
10055    // YYYY = YY^2
10056    var yyyy = yy.redSqr();
10057    // S = 2 * ((X1 + YY)^2 - XX - YYYY)
10058    var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
10059    s = s.redIAdd(s);
10060    // M = 3 * XX + a
10061    var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
10062    // T = M^2 - 2 * S
10063    var t = m.redSqr().redISub(s).redISub(s);
10064    // X3 = T
10065    nx = t;
10066    // Y3 = M * (S - T) - 8 * YYYY
10067    var yyyy8 = yyyy.redIAdd(yyyy);
10068    yyyy8 = yyyy8.redIAdd(yyyy8);
10069    yyyy8 = yyyy8.redIAdd(yyyy8);
10070    ny = m.redMul(s.redISub(t)).redISub(yyyy8);
10071    // Z3 = 2 * Y1
10072    nz = this.y.redAdd(this.y);
10073  } else {
10074    // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
10075    // 3M + 5S
10076
10077    // delta = Z1^2
10078    var delta = this.z.redSqr();
10079    // gamma = Y1^2
10080    var gamma = this.y.redSqr();
10081    // beta = X1 * gamma
10082    var beta = this.x.redMul(gamma);
10083    // alpha = 3 * (X1 - delta) * (X1 + delta)
10084    var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
10085    alpha = alpha.redAdd(alpha).redIAdd(alpha);
10086    // X3 = alpha^2 - 8 * beta
10087    var beta4 = beta.redIAdd(beta);
10088    beta4 = beta4.redIAdd(beta4);
10089    var beta8 = beta4.redAdd(beta4);
10090    nx = alpha.redSqr().redISub(beta8);
10091    // Z3 = (Y1 + Z1)^2 - gamma - delta
10092    nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
10093    // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
10094    var ggamma8 = gamma.redSqr();
10095    ggamma8 = ggamma8.redIAdd(ggamma8);
10096    ggamma8 = ggamma8.redIAdd(ggamma8);
10097    ggamma8 = ggamma8.redIAdd(ggamma8);
10098    ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
10099  }
10100
10101  return this.curve.jpoint(nx, ny, nz);
10102};
10103
10104JPoint.prototype._dbl = function _dbl() {
10105  var a = this.curve.a;
10106
10107  // 4M + 6S + 10A
10108  var jx = this.x;
10109  var jy = this.y;
10110  var jz = this.z;
10111  var jz4 = jz.redSqr().redSqr();
10112
10113  var jx2 = jx.redSqr();
10114  var jy2 = jy.redSqr();
10115
10116  var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
10117
10118  var jxd4 = jx.redAdd(jx);
10119  jxd4 = jxd4.redIAdd(jxd4);
10120  var t1 = jxd4.redMul(jy2);
10121  var nx = c.redSqr().redISub(t1.redAdd(t1));
10122  var t2 = t1.redISub(nx);
10123
10124  var jyd8 = jy2.redSqr();
10125  jyd8 = jyd8.redIAdd(jyd8);
10126  jyd8 = jyd8.redIAdd(jyd8);
10127  jyd8 = jyd8.redIAdd(jyd8);
10128  var ny = c.redMul(t2).redISub(jyd8);
10129  var nz = jy.redAdd(jy).redMul(jz);
10130
10131  return this.curve.jpoint(nx, ny, nz);
10132};
10133
10134JPoint.prototype.trpl = function trpl() {
10135  if (!this.curve.zeroA)
10136    return this.dbl().add(this);
10137
10138  // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
10139  // 5M + 10S + ...
10140
10141  // XX = X1^2
10142  var xx = this.x.redSqr();
10143  // YY = Y1^2
10144  var yy = this.y.redSqr();
10145  // ZZ = Z1^2
10146  var zz = this.z.redSqr();
10147  // YYYY = YY^2
10148  var yyyy = yy.redSqr();
10149  // M = 3 * XX + a * ZZ2; a = 0
10150  var m = xx.redAdd(xx).redIAdd(xx);
10151  // MM = M^2
10152  var mm = m.redSqr();
10153  // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
10154  var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
10155  e = e.redIAdd(e);
10156  e = e.redAdd(e).redIAdd(e);
10157  e = e.redISub(mm);
10158  // EE = E^2
10159  var ee = e.redSqr();
10160  // T = 16*YYYY
10161  var t = yyyy.redIAdd(yyyy);
10162  t = t.redIAdd(t);
10163  t = t.redIAdd(t);
10164  t = t.redIAdd(t);
10165  // U = (M + E)^2 - MM - EE - T
10166  var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
10167  // X3 = 4 * (X1 * EE - 4 * YY * U)
10168  var yyu4 = yy.redMul(u);
10169  yyu4 = yyu4.redIAdd(yyu4);
10170  yyu4 = yyu4.redIAdd(yyu4);
10171  var nx = this.x.redMul(ee).redISub(yyu4);
10172  nx = nx.redIAdd(nx);
10173  nx = nx.redIAdd(nx);
10174  // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
10175  var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
10176  ny = ny.redIAdd(ny);
10177  ny = ny.redIAdd(ny);
10178  ny = ny.redIAdd(ny);
10179  // Z3 = (Z1 + E)^2 - ZZ - EE
10180  var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
10181
10182  return this.curve.jpoint(nx, ny, nz);
10183};
10184
10185JPoint.prototype.mul = function mul(k, kbase) {
10186  k = new BN(k, kbase);
10187
10188  return this.curve._wnafMul(this, k);
10189};
10190
10191JPoint.prototype.eq = function eq(p) {
10192  if (p.type === 'affine')
10193    return this.eq(p.toJ());
10194
10195  if (this === p)
10196    return true;
10197
10198  // x1 * z2^2 == x2 * z1^2
10199  var z2 = this.z.redSqr();
10200  var pz2 = p.z.redSqr();
10201  if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
10202    return false;
10203
10204  // y1 * z2^3 == y2 * z1^3
10205  var z3 = z2.redMul(this.z);
10206  var pz3 = pz2.redMul(p.z);
10207  return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
10208};
10209
10210JPoint.prototype.eqXToP = function eqXToP(x) {
10211  var zs = this.z.redSqr();
10212  var rx = x.toRed(this.curve.red).redMul(zs);
10213  if (this.x.cmp(rx) === 0)
10214    return true;
10215
10216  var xc = x.clone();
10217  var t = this.curve.redN.redMul(zs);
10218  for (;;) {
10219    xc.iadd(this.curve.n);
10220    if (xc.cmp(this.curve.p) >= 0)
10221      return false;
10222
10223    rx.redIAdd(t);
10224    if (this.x.cmp(rx) === 0)
10225      return true;
10226  }
10227};
10228
10229JPoint.prototype.inspect = function inspect() {
10230  if (this.isInfinity())
10231    return '<EC JPoint Infinity>';
10232  return '<EC JPoint x: ' + this.x.toString(16, 2) +
10233      ' y: ' + this.y.toString(16, 2) +
10234      ' z: ' + this.z.toString(16, 2) + '>';
10235};
10236
10237JPoint.prototype.isInfinity = function isInfinity() {
10238  // XXX This code assumes that zero is always zero in red
10239  return this.z.cmpn(0) === 0;
10240};
10241
10242},{"../../elliptic":19,"../curve":22,"bn.js":17,"inherits":48}],25:[function(require,module,exports){
10243'use strict';
10244
10245var curves = exports;
10246
10247var hash = require('hash.js');
10248var elliptic = require('../elliptic');
10249
10250var assert = elliptic.utils.assert;
10251
10252function PresetCurve(options) {
10253  if (options.type === 'short')
10254    this.curve = new elliptic.curve.short(options);
10255  else if (options.type === 'edwards')
10256    this.curve = new elliptic.curve.edwards(options);
10257  else if (options.type === 'mont')
10258    this.curve = new elliptic.curve.mont(options);
10259  else throw new Error('Unknown curve type.');
10260  this.g = this.curve.g;
10261  this.n = this.curve.n;
10262  this.hash = options.hash;
10263
10264  assert(this.g.validate(), 'Invalid curve');
10265  assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O');
10266}
10267curves.PresetCurve = PresetCurve;
10268
10269function defineCurve(name, options) {
10270  Object.defineProperty(curves, name, {
10271    configurable: true,
10272    enumerable: true,
10273    get: function() {
10274      var curve = new PresetCurve(options);
10275      Object.defineProperty(curves, name, {
10276        configurable: true,
10277        enumerable: true,
10278        value: curve
10279      });
10280      return curve;
10281    }
10282  });
10283}
10284
10285defineCurve('p192', {
10286  type: 'short',
10287  prime: 'p192',
10288  p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
10289  a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
10290  b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
10291  n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
10292  hash: hash.sha256,
10293  gRed: false,
10294  g: [
10295    '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
10296    '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
10297  ]
10298});
10299
10300defineCurve('p224', {
10301  type: 'short',
10302  prime: 'p224',
10303  p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
10304  a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
10305  b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
10306  n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
10307  hash: hash.sha256,
10308  gRed: false,
10309  g: [
10310    'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
10311    'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
10312  ]
10313});
10314
10315defineCurve('p256', {
10316  type: 'short',
10317  prime: null,
10318  p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
10319  a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
10320  b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
10321  n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
10322  hash: hash.sha256,
10323  gRed: false,
10324  g: [
10325    '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
10326    '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
10327  ]
10328});
10329
10330defineCurve('p384', {
10331  type: 'short',
10332  prime: null,
10333  p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
10334     'fffffffe ffffffff 00000000 00000000 ffffffff',
10335  a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
10336     'fffffffe ffffffff 00000000 00000000 fffffffc',
10337  b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
10338     '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
10339  n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
10340     'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
10341  hash: hash.sha384,
10342  gRed: false,
10343  g: [
10344    'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
10345    '5502f25d bf55296c 3a545e38 72760ab7',
10346    '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
10347    '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
10348  ]
10349});
10350
10351defineCurve('p521', {
10352  type: 'short',
10353  prime: null,
10354  p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
10355     'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
10356     'ffffffff ffffffff ffffffff ffffffff ffffffff',
10357  a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
10358     'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
10359     'ffffffff ffffffff ffffffff ffffffff fffffffc',
10360  b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
10361     '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
10362     '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
10363  n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
10364     'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
10365     'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
10366  hash: hash.sha512,
10367  gRed: false,
10368  g: [
10369    '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
10370    '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
10371    'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
10372    '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
10373    '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
10374    '3fad0761 353c7086 a272c240 88be9476 9fd16650'
10375  ]
10376});
10377
10378// https://tools.ietf.org/html/rfc7748#section-4.1
10379defineCurve('curve25519', {
10380  type: 'mont',
10381  prime: 'p25519',
10382  p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
10383  a: '76d06',
10384  b: '1',
10385  n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
10386  cofactor: '8',
10387  hash: hash.sha256,
10388  gRed: false,
10389  g: [
10390    '9'
10391  ]
10392});
10393
10394defineCurve('ed25519', {
10395  type: 'edwards',
10396  prime: 'p25519',
10397  p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
10398  a: '-1',
10399  c: '1',
10400  // -121665 * (121666^(-1)) (mod P)
10401  d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
10402  n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
10403  cofactor: '8',
10404  hash: hash.sha256,
10405  gRed: false,
10406  g: [
10407    '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
10408    // 4/5
10409    '6666666666666666666666666666666666666666666666666666666666666658'
10410  ]
10411});
10412
10413// https://tools.ietf.org/html/rfc5639#section-3.4
10414defineCurve('brainpoolP256r1', {
10415  type: 'short',
10416  prime: null,
10417  p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377',
10418  a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9',
10419  b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6',
10420  n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7',
10421  hash: hash.sha256, // or 384, or 512
10422  gRed: false,
10423  g: [
10424    '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262',
10425    '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997'
10426  ]
10427});
10428
10429// https://tools.ietf.org/html/rfc5639#section-3.6
10430defineCurve('brainpoolP384r1', {
10431  type: 'short',
10432  prime: null,
10433  p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' +
10434    'ACD3A729 901D1A71 87470013 3107EC53',
10435  a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' +
10436    '8AA5814A 503AD4EB 04A8C7DD 22CE2826',
10437  b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' +
10438    '7CB43902 95DBC994 3AB78696 FA504C11',
10439  n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' +
10440    'CF3AB6AF 6B7FC310 3B883202 E9046565',
10441  hash: hash.sha384, // or 512
10442  gRed: false,
10443  g: [
10444    '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' +
10445      'E8E826E03436D646AAEF87B2E247D4AF1E',
10446    '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' +
10447      '280E4646217791811142820341263C5315'
10448  ]
10449});
10450
10451// https://tools.ietf.org/html/rfc5639#section-3.7
10452defineCurve('brainpoolP512r1', {
10453  type: 'short',
10454  prime: null,
10455  p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' +
10456    '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3',
10457  a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' +
10458    '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA',
10459  b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' +
10460    '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723',
10461  n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' +
10462    '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069',
10463  hash: hash.sha512,
10464  gRed: false,
10465  g: [
10466    '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' +
10467      '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822',
10468    '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' +
10469      '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892'
10470  ]
10471});
10472
10473// https://en.bitcoin.it/wiki/Secp256k1
10474var pre;
10475try {
10476  pre = require('./precomputed/secp256k1');
10477} catch (e) {
10478  pre = undefined;
10479}
10480
10481defineCurve('secp256k1', {
10482  type: 'short',
10483  prime: 'k256',
10484  p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
10485  a: '0',
10486  b: '7',
10487  n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
10488  h: '1',
10489  hash: hash.sha256,
10490
10491  // Precomputed endomorphism
10492  beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
10493  lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
10494  basis: [
10495    {
10496      a: '3086d221a7d46bcde86c90e49284eb15',
10497      b: '-e4437ed6010e88286f547fa90abfe4c3'
10498    },
10499    {
10500      a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
10501      b: '3086d221a7d46bcde86c90e49284eb15'
10502    }
10503  ],
10504
10505  gRed: false,
10506  g: [
10507    '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
10508    '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
10509    pre
10510  ]
10511});
10512
10513},{"../elliptic":19,"./precomputed/secp256k1":32,"hash.js":35}],26:[function(require,module,exports){
10514'use strict';
10515
10516var BN = require('bn.js');
10517var HmacDRBG = require('hmac-drbg');
10518var elliptic = require('../../elliptic');
10519var utils = elliptic.utils;
10520var assert = utils.assert;
10521
10522var KeyPair = require('./key');
10523var Signature = require('./signature');
10524
10525function EC(options) {
10526  if (!(this instanceof EC))
10527    return new EC(options);
10528
10529  // Shortcut `elliptic.ec(curve-name)`
10530  if (typeof options === 'string') {
10531    assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options);
10532
10533    options = elliptic.curves[options];
10534  }
10535
10536  // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
10537  if (options instanceof elliptic.curves.PresetCurve)
10538    options = { curve: options };
10539
10540  this.curve = options.curve.curve;
10541  this.n = this.curve.n;
10542  this.nh = this.n.ushrn(1);
10543  this.g = this.curve.g;
10544
10545  // Point on curve
10546  this.g = options.curve.g;
10547  this.g.precompute(options.curve.n.bitLength() + 1);
10548
10549  // Hash function for DRBG
10550  this.hash = options.hash || options.curve.hash;
10551}
10552module.exports = EC;
10553
10554EC.prototype.keyPair = function keyPair(options) {
10555  return new KeyPair(this, options);
10556};
10557
10558EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
10559  return KeyPair.fromPrivate(this, priv, enc);
10560};
10561
10562EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
10563  return KeyPair.fromPublic(this, pub, enc);
10564};
10565
10566EC.prototype.genKeyPair = function genKeyPair(options) {
10567  if (!options)
10568    options = {};
10569
10570  // Instantiate Hmac_DRBG
10571  var drbg = new HmacDRBG({
10572    hash: this.hash,
10573    pers: options.pers,
10574    persEnc: options.persEnc || 'utf8',
10575    entropy: options.entropy || elliptic.rand(this.hash.hmacStrength),
10576    entropyEnc: options.entropy && options.entropyEnc || 'utf8',
10577    nonce: this.n.toArray()
10578  });
10579
10580  // Key generation for curve25519 is simpler
10581  if (this.curve.type === 'mont') {
10582    var priv = new BN(drbg.generate(32));
10583    return this.keyFromPrivate(priv);
10584  }
10585
10586  var bytes = this.n.byteLength();
10587  var ns2 = this.n.sub(new BN(2));
10588  do {
10589    var priv = new BN(drbg.generate(bytes));
10590    if (priv.cmp(ns2) > 0)
10591      continue;
10592
10593    priv.iaddn(1);
10594    return this.keyFromPrivate(priv);
10595  } while (true);
10596};
10597
10598EC.prototype._truncateToN = function truncateToN(msg, truncOnly) {
10599  var delta = msg.byteLength() * 8 - this.n.bitLength();
10600  if (delta > 0)
10601    msg = msg.ushrn(delta);
10602  if (!truncOnly && msg.cmp(this.n) >= 0)
10603    return msg.sub(this.n);
10604  else
10605    return msg;
10606};
10607
10608EC.prototype.sign = function sign(msg, key, enc, options) {
10609  if (typeof enc === 'object') {
10610    options = enc;
10611    enc = null;
10612  }
10613  if (!options)
10614    options = {};
10615
10616  key = this.keyFromPrivate(key, enc);
10617  msg = this._truncateToN(new BN(msg, 16));
10618
10619  // Zero-extend key to provide enough entropy
10620  var bytes = this.n.byteLength();
10621  var bkey = key.getPrivate().toArray('be', bytes);
10622
10623  // Zero-extend nonce to have the same byte size as N
10624  var nonce = msg.toArray('be', bytes);
10625
10626  // Instantiate Hmac_DRBG
10627  var drbg = new HmacDRBG({
10628    hash: this.hash,
10629    entropy: bkey,
10630    nonce: nonce,
10631    pers: options.pers,
10632    persEnc: options.persEnc || 'utf8'
10633  });
10634
10635  // Number of bytes to generate
10636  var ns1 = this.n.sub(new BN(1));
10637
10638  for (var iter = 0; true; iter++) {
10639    var k = options.k ?
10640        options.k(iter) :
10641        new BN(drbg.generate(this.n.byteLength()));
10642    k = this._truncateToN(k, true);
10643    if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
10644      continue;
10645
10646    var kp = this.g.mul(k);
10647    if (kp.isInfinity())
10648      continue;
10649
10650    var kpX = kp.getX();
10651    var r = kpX.umod(this.n);
10652    if (r.cmpn(0) === 0)
10653      continue;
10654
10655    var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
10656    s = s.umod(this.n);
10657    if (s.cmpn(0) === 0)
10658      continue;
10659
10660    var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
10661                        (kpX.cmp(r) !== 0 ? 2 : 0);
10662
10663    // Use complement of `s`, if it is > `n / 2`
10664    if (options.canonical && s.cmp(this.nh) > 0) {
10665      s = this.n.sub(s);
10666      recoveryParam ^= 1;
10667    }
10668
10669    return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
10670  }
10671};
10672
10673EC.prototype.verify = function verify(msg, signature, key, enc) {
10674  msg = this._truncateToN(new BN(msg, 16));
10675  key = this.keyFromPublic(key, enc);
10676  signature = new Signature(signature, 'hex');
10677
10678  // Perform primitive values validation
10679  var r = signature.r;
10680  var s = signature.s;
10681  if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
10682    return false;
10683  if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
10684    return false;
10685
10686  // Validate signature
10687  var sinv = s.invm(this.n);
10688  var u1 = sinv.mul(msg).umod(this.n);
10689  var u2 = sinv.mul(r).umod(this.n);
10690
10691  if (!this.curve._maxwellTrick) {
10692    var p = this.g.mulAdd(u1, key.getPublic(), u2);
10693    if (p.isInfinity())
10694      return false;
10695
10696    return p.getX().umod(this.n).cmp(r) === 0;
10697  }
10698
10699  // NOTE: Greg Maxwell's trick, inspired by:
10700  // https://git.io/vad3K
10701
10702  var p = this.g.jmulAdd(u1, key.getPublic(), u2);
10703  if (p.isInfinity())
10704    return false;
10705
10706  // Compare `p.x` of Jacobian point with `r`,
10707  // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
10708  // inverse of `p.z^2`
10709  return p.eqXToP(r);
10710};
10711
10712EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
10713  assert((3 & j) === j, 'The recovery param is more than two bits');
10714  signature = new Signature(signature, enc);
10715
10716  var n = this.n;
10717  var e = new BN(msg);
10718  var r = signature.r;
10719  var s = signature.s;
10720
10721  // A set LSB signifies that the y-coordinate is odd
10722  var isYOdd = j & 1;
10723  var isSecondKey = j >> 1;
10724  if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
10725    throw new Error('Unable to find sencond key candinate');
10726
10727  // 1.1. Let x = r + jn.
10728  if (isSecondKey)
10729    r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
10730  else
10731    r = this.curve.pointFromX(r, isYOdd);
10732
10733  var rInv = signature.r.invm(n);
10734  var s1 = n.sub(e).mul(rInv).umod(n);
10735  var s2 = s.mul(rInv).umod(n);
10736
10737  // 1.6.1 Compute Q = r^-1 (sR -  eG)
10738  //               Q = r^-1 (sR + -eG)
10739  return this.g.mulAdd(s1, r, s2);
10740};
10741
10742EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
10743  signature = new Signature(signature, enc);
10744  if (signature.recoveryParam !== null)
10745    return signature.recoveryParam;
10746
10747  for (var i = 0; i < 4; i++) {
10748    var Qprime;
10749    try {
10750      Qprime = this.recoverPubKey(e, signature, i);
10751    } catch (e) {
10752      continue;
10753    }
10754
10755    if (Qprime.eq(Q))
10756      return i;
10757  }
10758  throw new Error('Unable to find valid recovery factor');
10759};
10760
10761},{"../../elliptic":19,"./key":27,"./signature":28,"bn.js":17,"hmac-drbg":47}],27:[function(require,module,exports){
10762'use strict';
10763
10764var BN = require('bn.js');
10765var elliptic = require('../../elliptic');
10766var utils = elliptic.utils;
10767var assert = utils.assert;
10768
10769function KeyPair(ec, options) {
10770  this.ec = ec;
10771  this.priv = null;
10772  this.pub = null;
10773
10774  // KeyPair(ec, { priv: ..., pub: ... })
10775  if (options.priv)
10776    this._importPrivate(options.priv, options.privEnc);
10777  if (options.pub)
10778    this._importPublic(options.pub, options.pubEnc);
10779}
10780module.exports = KeyPair;
10781
10782KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
10783  if (pub instanceof KeyPair)
10784    return pub;
10785
10786  return new KeyPair(ec, {
10787    pub: pub,
10788    pubEnc: enc
10789  });
10790};
10791
10792KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
10793  if (priv instanceof KeyPair)
10794    return priv;
10795
10796  return new KeyPair(ec, {
10797    priv: priv,
10798    privEnc: enc
10799  });
10800};
10801
10802// TODO: should not validate for X25519
10803KeyPair.prototype.validate = function validate() {
10804  var pub = this.getPublic();
10805
10806  if (pub.isInfinity())
10807    return { result: false, reason: 'Invalid public key' };
10808  if (!pub.validate())
10809    return { result: false, reason: 'Public key is not a point' };
10810  if (!pub.mul(this.ec.curve.n).isInfinity())
10811    return { result: false, reason: 'Public key * N != O' };
10812
10813  return { result: true, reason: null };
10814};
10815
10816KeyPair.prototype.getPublic = function getPublic(enc, compact) {
10817  if (!this.pub)
10818    this.pub = this.ec.g.mul(this.priv);
10819
10820  if (!enc)
10821    return this.pub;
10822
10823  return this.pub.encode(enc, compact);
10824};
10825
10826KeyPair.prototype.getPrivate = function getPrivate(enc) {
10827  if (enc === 'hex')
10828    return this.priv.toString(16, 2);
10829  else
10830    return this.priv;
10831};
10832
10833KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
10834  this.priv = new BN(key, enc || 16);
10835
10836  // For Curve25519/Curve448 we have a specific procedure.
10837  // TODO Curve448
10838  if (this.ec.curve.type === 'mont') {
10839    var one = this.ec.curve.one;
10840    var mask = one.ushln(255 - 3).sub(one).ushln(3);
10841    this.priv = this.priv.or(one.ushln(255 - 1));
10842    this.priv = this.priv.and(mask);
10843  } else
10844    // Ensure that the priv won't be bigger than n, otherwise we may fail
10845    // in fixed multiplication method
10846    this.priv = this.priv.umod(this.ec.curve.n);
10847};
10848
10849KeyPair.prototype._importPublic = function _importPublic(key, enc) {
10850  if (key.x || key.y) {
10851    // Montgomery points only have an `x` coordinate.
10852    // Weierstrass/Edwards points on the other hand have both `x` and
10853    // `y` coordinates.
10854    if (this.ec.curve.type === 'mont') {
10855      assert(key.x, 'Need x coordinate');
10856    } else if (this.ec.curve.type === 'short' ||
10857               this.ec.curve.type === 'edwards') {
10858      assert(key.x && key.y, 'Need both x and y coordinate');
10859    }
10860    this.pub = this.ec.curve.point(key.x, key.y);
10861    return;
10862  }
10863  this.pub = this.ec.curve.decodePoint(key, enc);
10864};
10865
10866// ECDH
10867KeyPair.prototype.derive = function derive(pub) {
10868  return pub.mul(this.priv).getX();
10869};
10870
10871// ECDSA
10872KeyPair.prototype.sign = function sign(msg, enc, options) {
10873  return this.ec.sign(msg, this, enc, options);
10874};
10875
10876KeyPair.prototype.verify = function verify(msg, signature) {
10877  return this.ec.verify(msg, signature, this);
10878};
10879
10880KeyPair.prototype.inspect = function inspect() {
10881  return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
10882         ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
10883};
10884
10885},{"../../elliptic":19,"bn.js":17}],28:[function(require,module,exports){
10886'use strict';
10887
10888var BN = require('bn.js');
10889
10890var elliptic = require('../../elliptic');
10891var utils = elliptic.utils;
10892var assert = utils.assert;
10893
10894function Signature(options, enc) {
10895  if (options instanceof Signature)
10896    return options;
10897
10898  if (this._importDER(options, enc))
10899    return;
10900
10901  assert(options.r && options.s, 'Signature without r or s');
10902  this.r = new BN(options.r, 16);
10903  this.s = new BN(options.s, 16);
10904  if (options.recoveryParam === undefined)
10905    this.recoveryParam = null;
10906  else
10907    this.recoveryParam = options.recoveryParam;
10908}
10909module.exports = Signature;
10910
10911function Position() {
10912  this.place = 0;
10913}
10914
10915function getLength(buf, p) {
10916  var initial = buf[p.place++];
10917  if (!(initial & 0x80)) {
10918    return initial;
10919  }
10920  var octetLen = initial & 0xf;
10921  var val = 0;
10922  for (var i = 0, off = p.place; i < octetLen; i++, off++) {
10923    val <<= 8;
10924    val |= buf[off];
10925  }
10926  p.place = off;
10927  return val;
10928}
10929
10930function rmPadding(buf) {
10931  var i = 0;
10932  var len = buf.length - 1;
10933  while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
10934    i++;
10935  }
10936  if (i === 0) {
10937    return buf;
10938  }
10939  return buf.slice(i);
10940}
10941
10942Signature.prototype._importDER = function _importDER(data, enc) {
10943  data = utils.toArray(data, enc);
10944  var p = new Position();
10945  if (data[p.place++] !== 0x30) {
10946    return false;
10947  }
10948  var len = getLength(data, p);
10949  if ((len + p.place) !== data.length) {
10950    return false;
10951  }
10952  if (data[p.place++] !== 0x02) {
10953    return false;
10954  }
10955  var rlen = getLength(data, p);
10956  var r = data.slice(p.place, rlen + p.place);
10957  p.place += rlen;
10958  if (data[p.place++] !== 0x02) {
10959    return false;
10960  }
10961  var slen = getLength(data, p);
10962  if (data.length !== slen + p.place) {
10963    return false;
10964  }
10965  var s = data.slice(p.place, slen + p.place);
10966  if (r[0] === 0 && (r[1] & 0x80)) {
10967    r = r.slice(1);
10968  }
10969  if (s[0] === 0 && (s[1] & 0x80)) {
10970    s = s.slice(1);
10971  }
10972
10973  this.r = new BN(r);
10974  this.s = new BN(s);
10975  this.recoveryParam = null;
10976
10977  return true;
10978};
10979
10980function constructLength(arr, len) {
10981  if (len < 0x80) {
10982    arr.push(len);
10983    return;
10984  }
10985  var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
10986  arr.push(octets | 0x80);
10987  while (--octets) {
10988    arr.push((len >>> (octets << 3)) & 0xff);
10989  }
10990  arr.push(len);
10991}
10992
10993Signature.prototype.toDER = function toDER(enc) {
10994  var r = this.r.toArray();
10995  var s = this.s.toArray();
10996
10997  // Pad values
10998  if (r[0] & 0x80)
10999    r = [ 0 ].concat(r);
11000  // Pad values
11001  if (s[0] & 0x80)
11002    s = [ 0 ].concat(s);
11003
11004  r = rmPadding(r);
11005  s = rmPadding(s);
11006
11007  while (!s[0] && !(s[1] & 0x80)) {
11008    s = s.slice(1);
11009  }
11010  var arr = [ 0x02 ];
11011  constructLength(arr, r.length);
11012  arr = arr.concat(r);
11013  arr.push(0x02);
11014  constructLength(arr, s.length);
11015  var backHalf = arr.concat(s);
11016  var res = [ 0x30 ];
11017  constructLength(res, backHalf.length);
11018  res = res.concat(backHalf);
11019  return utils.encode(res, enc);
11020};
11021
11022},{"../../elliptic":19,"bn.js":17}],29:[function(require,module,exports){
11023'use strict';
11024
11025var hash = require('hash.js');
11026var HmacDRBG = require('hmac-drbg');
11027var elliptic = require('../../elliptic');
11028var utils = elliptic.utils;
11029var assert = utils.assert;
11030var parseBytes = utils.parseBytes;
11031var KeyPair = require('./key');
11032var Signature = require('./signature');
11033
11034function EDDSA(curve) {
11035  assert(curve === 'ed25519', 'only tested with ed25519 so far');
11036
11037  if (!(this instanceof EDDSA))
11038    return new EDDSA(curve);
11039
11040  var curve = elliptic.curves[curve].curve;
11041  this.curve = curve;
11042  this.g = curve.g;
11043  this.g.precompute(curve.n.bitLength() + 1);
11044
11045  this.pointClass = curve.point().constructor;
11046  this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
11047  this.hash = hash.sha512;
11048}
11049
11050module.exports = EDDSA;
11051
11052/**
11053* @param {Array|String} message - message bytes
11054* @param {Array|String|KeyPair} secret - secret bytes or a keypair
11055* @returns {Signature} - signature
11056*/
11057EDDSA.prototype.sign = function sign(message, secret) {
11058  message = parseBytes(message);
11059  var key = this.keyFromSecret(secret);
11060  var r = this.hashInt(key.messagePrefix(), message);
11061  var R = this.g.mul(r);
11062  var Rencoded = this.encodePoint(R);
11063  var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
11064               .mul(key.priv());
11065  var S = r.add(s_).umod(this.curve.n);
11066  return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
11067};
11068
11069/**
11070* @param {Array} message - message bytes
11071* @param {Array|String|Signature} sig - sig bytes
11072* @param {Array|String|Point|KeyPair} pub - public key
11073* @returns {Boolean} - true if public key matches sig of message
11074*/
11075EDDSA.prototype.verify = function verify(message, sig, pub) {
11076  message = parseBytes(message);
11077  sig = this.makeSignature(sig);
11078  var key = this.keyFromPublic(pub);
11079  var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
11080  var SG = this.g.mul(sig.S());
11081  var RplusAh = sig.R().add(key.pub().mul(h));
11082  return RplusAh.eq(SG);
11083};
11084
11085EDDSA.prototype.hashInt = function hashInt() {
11086  var hash = this.hash();
11087  for (var i = 0; i < arguments.length; i++)
11088    hash.update(arguments[i]);
11089  return utils.intFromLE(hash.digest()).umod(this.curve.n);
11090};
11091
11092EDDSA.prototype.keyPair = function keyPair(options) {
11093  return new KeyPair(this, options);
11094};
11095
11096EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
11097  return KeyPair.fromPublic(this, pub);
11098};
11099
11100EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
11101  return KeyPair.fromSecret(this, secret);
11102};
11103
11104EDDSA.prototype.genKeyPair = function genKeyPair(options) {
11105  if (!options)
11106    options = {};
11107
11108  // Instantiate Hmac_DRBG
11109  var drbg = new HmacDRBG({
11110    hash: this.hash,
11111    pers: options.pers,
11112    persEnc: options.persEnc || 'utf8',
11113    entropy: options.entropy || elliptic.rand(this.hash.hmacStrength),
11114    entropyEnc: options.entropy && options.entropyEnc || 'utf8',
11115    nonce: this.curve.n.toArray()
11116  });
11117
11118  return this.keyFromSecret(drbg.generate(32));
11119};
11120
11121EDDSA.prototype.makeSignature = function makeSignature(sig) {
11122  if (sig instanceof Signature)
11123    return sig;
11124  return new Signature(this, sig);
11125};
11126
11127/**
11128* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
11129*
11130* EDDSA defines methods for encoding and decoding points and integers. These are
11131* helper convenience methods, that pass along to utility functions implied
11132* parameters.
11133*
11134*/
11135EDDSA.prototype.encodePoint = function encodePoint(point) {
11136  var enc = point.getY().toArray('le', this.encodingLength);
11137  enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
11138  return enc;
11139};
11140
11141EDDSA.prototype.decodePoint = function decodePoint(bytes) {
11142  bytes = utils.parseBytes(bytes);
11143
11144  var lastIx = bytes.length - 1;
11145  var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
11146  var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
11147
11148  var y = utils.intFromLE(normed);
11149  return this.curve.pointFromY(y, xIsOdd);
11150};
11151
11152EDDSA.prototype.encodeInt = function encodeInt(num) {
11153  return num.toArray('le', this.encodingLength);
11154};
11155
11156EDDSA.prototype.decodeInt = function decodeInt(bytes) {
11157  return utils.intFromLE(bytes);
11158};
11159
11160EDDSA.prototype.isPoint = function isPoint(val) {
11161  return val instanceof this.pointClass;
11162};
11163
11164},{"../../elliptic":19,"./key":30,"./signature":31,"hash.js":35,"hmac-drbg":47}],30:[function(require,module,exports){
11165'use strict';
11166
11167var elliptic = require('../../elliptic');
11168var utils = elliptic.utils;
11169var assert = utils.assert;
11170var parseBytes = utils.parseBytes;
11171var cachedProperty = utils.cachedProperty;
11172
11173/**
11174* @param {EDDSA} eddsa - instance
11175* @param {Object} params - public/private key parameters
11176*
11177* @param {Array<Byte>} [params.secret] - secret seed bytes
11178* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
11179* @param {Array<Byte>} [params.pub] - public key point encoded as bytes
11180*
11181*/
11182function KeyPair(eddsa, params) {
11183  this.eddsa = eddsa;
11184  if (params.hasOwnProperty('secret'))
11185    this._secret = parseBytes(params.secret);
11186  if (eddsa.isPoint(params.pub))
11187    this._pub = params.pub;
11188  else {
11189    this._pubBytes = parseBytes(params.pub);
11190    if (this._pubBytes && this._pubBytes.length === 33 &&
11191        this._pubBytes[0] === 0x40)
11192      this._pubBytes = this._pubBytes.slice(1, 33);
11193    if (this._pubBytes && this._pubBytes.length !== 32)
11194      throw new Error('Unknown point compression format');
11195  }
11196}
11197
11198KeyPair.fromPublic = function fromPublic(eddsa, pub) {
11199  if (pub instanceof KeyPair)
11200    return pub;
11201  return new KeyPair(eddsa, { pub: pub });
11202};
11203
11204KeyPair.fromSecret = function fromSecret(eddsa, secret) {
11205  if (secret instanceof KeyPair)
11206    return secret;
11207  return new KeyPair(eddsa, { secret: secret });
11208};
11209
11210KeyPair.prototype.secret = function secret() {
11211  return this._secret;
11212};
11213
11214cachedProperty(KeyPair, 'pubBytes', function pubBytes() {
11215  return this.eddsa.encodePoint(this.pub());
11216});
11217
11218cachedProperty(KeyPair, 'pub', function pub() {
11219  if (this._pubBytes)
11220    return this.eddsa.decodePoint(this._pubBytes);
11221  return this.eddsa.g.mul(this.priv());
11222});
11223
11224cachedProperty(KeyPair, 'privBytes', function privBytes() {
11225  var eddsa = this.eddsa;
11226  var hash = this.hash();
11227  var lastIx = eddsa.encodingLength - 1;
11228
11229  // https://tools.ietf.org/html/rfc8032#section-5.1.5
11230  var a = hash.slice(0, eddsa.encodingLength);
11231  a[0] &= 248;
11232  a[lastIx] &= 127;
11233  a[lastIx] |= 64;
11234
11235  return a;
11236});
11237
11238cachedProperty(KeyPair, 'priv', function priv() {
11239  return this.eddsa.decodeInt(this.privBytes());
11240});
11241
11242cachedProperty(KeyPair, 'hash', function hash() {
11243  return this.eddsa.hash().update(this.secret()).digest();
11244});
11245
11246cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {
11247  return this.hash().slice(this.eddsa.encodingLength);
11248});
11249
11250KeyPair.prototype.sign = function sign(message) {
11251  assert(this._secret, 'KeyPair can only verify');
11252  return this.eddsa.sign(message, this);
11253};
11254
11255KeyPair.prototype.verify = function verify(message, sig) {
11256  return this.eddsa.verify(message, sig, this);
11257};
11258
11259KeyPair.prototype.getSecret = function getSecret(enc) {
11260  assert(this._secret, 'KeyPair is public only');
11261  return utils.encode(this.secret(), enc);
11262};
11263
11264KeyPair.prototype.getPublic = function getPublic(enc, compact) {
11265  return utils.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc);
11266};
11267
11268module.exports = KeyPair;
11269
11270},{"../../elliptic":19}],31:[function(require,module,exports){
11271'use strict';
11272
11273var BN = require('bn.js');
11274var elliptic = require('../../elliptic');
11275var utils = elliptic.utils;
11276var assert = utils.assert;
11277var cachedProperty = utils.cachedProperty;
11278var parseBytes = utils.parseBytes;
11279
11280/**
11281* @param {EDDSA} eddsa - eddsa instance
11282* @param {Array<Bytes>|Object} sig -
11283* @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
11284* @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
11285* @param {Array<Bytes>} [sig.Rencoded] - R point encoded
11286* @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
11287*/
11288function Signature(eddsa, sig) {
11289  this.eddsa = eddsa;
11290
11291  if (typeof sig !== 'object')
11292    sig = parseBytes(sig);
11293
11294  if (Array.isArray(sig)) {
11295    sig = {
11296      R: sig.slice(0, eddsa.encodingLength),
11297      S: sig.slice(eddsa.encodingLength)
11298    };
11299  }
11300
11301  assert(sig.R && sig.S, 'Signature without R or S');
11302
11303  if (eddsa.isPoint(sig.R))
11304    this._R = sig.R;
11305  if (sig.S instanceof BN)
11306    this._S = sig.S;
11307
11308  this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
11309  this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
11310}
11311
11312cachedProperty(Signature, 'S', function S() {
11313  return this.eddsa.decodeInt(this.Sencoded());
11314});
11315
11316cachedProperty(Signature, 'R', function R() {
11317  return this.eddsa.decodePoint(this.Rencoded());
11318});
11319
11320cachedProperty(Signature, 'Rencoded', function Rencoded() {
11321  return this.eddsa.encodePoint(this.R());
11322});
11323
11324cachedProperty(Signature, 'Sencoded', function Sencoded() {
11325  return this.eddsa.encodeInt(this.S());
11326});
11327
11328Signature.prototype.toBytes = function toBytes() {
11329  return this.Rencoded().concat(this.Sencoded());
11330};
11331
11332Signature.prototype.toHex = function toHex() {
11333  return utils.encode(this.toBytes(), 'hex').toUpperCase();
11334};
11335
11336module.exports = Signature;
11337
11338},{"../../elliptic":19,"bn.js":17}],32:[function(require,module,exports){
11339module.exports = {
11340  doubles: {
11341    step: 4,
11342    points: [
11343      [
11344        'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
11345        'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
11346      ],
11347      [
11348        '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
11349        '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
11350      ],
11351      [
11352        '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
11353        'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
11354      ],
11355      [
11356        '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
11357        '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
11358      ],
11359      [
11360        '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
11361        '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
11362      ],
11363      [
11364        '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
11365        '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
11366      ],
11367      [
11368        'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
11369        '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
11370      ],
11371      [
11372        '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
11373        'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
11374      ],
11375      [
11376        'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
11377        '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
11378      ],
11379      [
11380        'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
11381        'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
11382      ],
11383      [
11384        'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
11385        '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
11386      ],
11387      [
11388        '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
11389        '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
11390      ],
11391      [
11392        '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
11393        '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
11394      ],
11395      [
11396        '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
11397        '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
11398      ],
11399      [
11400        '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
11401        '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
11402      ],
11403      [
11404        '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
11405        '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
11406      ],
11407      [
11408        '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
11409        '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
11410      ],
11411      [
11412        '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
11413        '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
11414      ],
11415      [
11416        '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
11417        'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
11418      ],
11419      [
11420        'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
11421        '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
11422      ],
11423      [
11424        'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
11425        '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
11426      ],
11427      [
11428        '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
11429        '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
11430      ],
11431      [
11432        '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
11433        '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
11434      ],
11435      [
11436        'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
11437        '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
11438      ],
11439      [
11440        '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
11441        'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
11442      ],
11443      [
11444        'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
11445        '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
11446      ],
11447      [
11448        'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
11449        'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
11450      ],
11451      [
11452        'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
11453        '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
11454      ],
11455      [
11456        'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
11457        'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
11458      ],
11459      [
11460        'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
11461        '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
11462      ],
11463      [
11464        '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
11465        'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
11466      ],
11467      [
11468        '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
11469        '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
11470      ],
11471      [
11472        'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
11473        '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
11474      ],
11475      [
11476        '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
11477        'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
11478      ],
11479      [
11480        'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
11481        '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
11482      ],
11483      [
11484        'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
11485        '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
11486      ],
11487      [
11488        'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
11489        'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
11490      ],
11491      [
11492        '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
11493        '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
11494      ],
11495      [
11496        '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
11497        '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
11498      ],
11499      [
11500        '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
11501        'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
11502      ],
11503      [
11504        '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
11505        '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
11506      ],
11507      [
11508        'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
11509        '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
11510      ],
11511      [
11512        '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
11513        '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
11514      ],
11515      [
11516        '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
11517        'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
11518      ],
11519      [
11520        '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
11521        '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
11522      ],
11523      [
11524        'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
11525        '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
11526      ],
11527      [
11528        '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
11529        'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
11530      ],
11531      [
11532        'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
11533        'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
11534      ],
11535      [
11536        'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
11537        '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
11538      ],
11539      [
11540        '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
11541        'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
11542      ],
11543      [
11544        '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
11545        'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
11546      ],
11547      [
11548        'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
11549        '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
11550      ],
11551      [
11552        'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
11553        '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
11554      ],
11555      [
11556        'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
11557        '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
11558      ],
11559      [
11560        '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
11561        'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
11562      ],
11563      [
11564        '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
11565        '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
11566      ],
11567      [
11568        'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
11569        'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
11570      ],
11571      [
11572        '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
11573        'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
11574      ],
11575      [
11576        '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
11577        '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
11578      ],
11579      [
11580        '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
11581        '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
11582      ],
11583      [
11584        'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
11585        'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
11586      ],
11587      [
11588        '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
11589        '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
11590      ],
11591      [
11592        '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
11593        '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
11594      ],
11595      [
11596        'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
11597        '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
11598      ],
11599      [
11600        'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
11601        'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
11602      ]
11603    ]
11604  },
11605  naf: {
11606    wnd: 7,
11607    points: [
11608      [
11609        'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
11610        '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
11611      ],
11612      [
11613        '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
11614        'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
11615      ],
11616      [
11617        '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
11618        '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
11619      ],
11620      [
11621        'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
11622        'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
11623      ],
11624      [
11625        '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
11626        'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
11627      ],
11628      [
11629        'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
11630        'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
11631      ],
11632      [
11633        'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
11634        '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
11635      ],
11636      [
11637        'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
11638        '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
11639      ],
11640      [
11641        '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
11642        '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
11643      ],
11644      [
11645        '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
11646        '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
11647      ],
11648      [
11649        '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
11650        '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
11651      ],
11652      [
11653        '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
11654        '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
11655      ],
11656      [
11657        'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
11658        'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
11659      ],
11660      [
11661        'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
11662        '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
11663      ],
11664      [
11665        '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
11666        'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
11667      ],
11668      [
11669        '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
11670        'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
11671      ],
11672      [
11673        '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
11674        '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
11675      ],
11676      [
11677        '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
11678        '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
11679      ],
11680      [
11681        '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
11682        '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
11683      ],
11684      [
11685        '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
11686        'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
11687      ],
11688      [
11689        'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
11690        'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
11691      ],
11692      [
11693        '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
11694        '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
11695      ],
11696      [
11697        '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
11698        '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
11699      ],
11700      [
11701        'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
11702        'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
11703      ],
11704      [
11705        '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
11706        '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
11707      ],
11708      [
11709        'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
11710        'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
11711      ],
11712      [
11713        'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
11714        'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
11715      ],
11716      [
11717        '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
11718        '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
11719      ],
11720      [
11721        '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
11722        '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
11723      ],
11724      [
11725        '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
11726        '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
11727      ],
11728      [
11729        'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
11730        '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
11731      ],
11732      [
11733        '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
11734        '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
11735      ],
11736      [
11737        'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
11738        '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
11739      ],
11740      [
11741        '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
11742        'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
11743      ],
11744      [
11745        '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
11746        'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
11747      ],
11748      [
11749        'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
11750        'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
11751      ],
11752      [
11753        '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
11754        '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
11755      ],
11756      [
11757        '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
11758        'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
11759      ],
11760      [
11761        'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
11762        'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
11763      ],
11764      [
11765        '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
11766        '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
11767      ],
11768      [
11769        '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
11770        'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
11771      ],
11772      [
11773        '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
11774        '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
11775      ],
11776      [
11777        '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
11778        'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
11779      ],
11780      [
11781        'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
11782        '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
11783      ],
11784      [
11785        '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
11786        '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
11787      ],
11788      [
11789        '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
11790        'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
11791      ],
11792      [
11793        '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
11794        'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
11795      ],
11796      [
11797        'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
11798        'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
11799      ],
11800      [
11801        'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
11802        'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
11803      ],
11804      [
11805        '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
11806        '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
11807      ],
11808      [
11809        '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
11810        '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
11811      ],
11812      [
11813        'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
11814        '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
11815      ],
11816      [
11817        'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
11818        'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
11819      ],
11820      [
11821        '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
11822        '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
11823      ],
11824      [
11825        '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
11826        '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
11827      ],
11828      [
11829        'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
11830        '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
11831      ],
11832      [
11833        '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
11834        '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
11835      ],
11836      [
11837        'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
11838        'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
11839      ],
11840      [
11841        '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
11842        'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
11843      ],
11844      [
11845        '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
11846        '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
11847      ],
11848      [
11849        'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
11850        '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
11851      ],
11852      [
11853        'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
11854        '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
11855      ],
11856      [
11857        '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
11858        '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
11859      ],
11860      [
11861        '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
11862        '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
11863      ],
11864      [
11865        '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
11866        'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
11867      ],
11868      [
11869        '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
11870        'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
11871      ],
11872      [
11873        '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
11874        '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
11875      ],
11876      [
11877        '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
11878        '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
11879      ],
11880      [
11881        '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
11882        '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
11883      ],
11884      [
11885        '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
11886        'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
11887      ],
11888      [
11889        'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
11890        'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
11891      ],
11892      [
11893        '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
11894        'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
11895      ],
11896      [
11897        'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
11898        '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
11899      ],
11900      [
11901        'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
11902        '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
11903      ],
11904      [
11905        'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
11906        '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
11907      ],
11908      [
11909        'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
11910        '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
11911      ],
11912      [
11913        '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
11914        'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
11915      ],
11916      [
11917        '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
11918        '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
11919      ],
11920      [
11921        '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
11922        'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
11923      ],
11924      [
11925        'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
11926        'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
11927      ],
11928      [
11929        'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
11930        '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
11931      ],
11932      [
11933        'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
11934        'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
11935      ],
11936      [
11937        'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
11938        '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
11939      ],
11940      [
11941        '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
11942        '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
11943      ],
11944      [
11945        'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
11946        '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
11947      ],
11948      [
11949        'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
11950        '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
11951      ],
11952      [
11953        '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
11954        '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
11955      ],
11956      [
11957        '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
11958        'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
11959      ],
11960      [
11961        'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
11962        '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
11963      ],
11964      [
11965        'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
11966        '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
11967      ],
11968      [
11969        'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
11970        '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
11971      ],
11972      [
11973        '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
11974        '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
11975      ],
11976      [
11977        'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
11978        'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
11979      ],
11980      [
11981        '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
11982        'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
11983      ],
11984      [
11985        'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
11986        'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
11987      ],
11988      [
11989        'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
11990        '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
11991      ],
11992      [
11993        '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
11994        'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
11995      ],
11996      [
11997        'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
11998        '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
11999      ],
12000      [
12001        'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
12002        '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
12003      ],
12004      [
12005        'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
12006        '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
12007      ],
12008      [
12009        '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
12010        'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
12011      ],
12012      [
12013        '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
12014        'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
12015      ],
12016      [
12017        'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
12018        '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
12019      ],
12020      [
12021        '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
12022        'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
12023      ],
12024      [
12025        '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
12026        '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
12027      ],
12028      [
12029        '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
12030        'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
12031      ],
12032      [
12033        'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
12034        'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
12035      ],
12036      [
12037        '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
12038        'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
12039      ],
12040      [
12041        '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
12042        '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
12043      ],
12044      [
12045        '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
12046        'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
12047      ],
12048      [
12049        '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
12050        '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
12051      ],
12052      [
12053        'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
12054        'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
12055      ],
12056      [
12057        '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
12058        '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
12059      ],
12060      [
12061        'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
12062        '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
12063      ],
12064      [
12065        '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
12066        '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
12067      ],
12068      [
12069        'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
12070        'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
12071      ],
12072      [
12073        'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
12074        '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
12075      ],
12076      [
12077        'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
12078        'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
12079      ],
12080      [
12081        '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
12082        'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
12083      ],
12084      [
12085        '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
12086        '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
12087      ],
12088      [
12089        '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
12090        'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
12091      ],
12092      [
12093        '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
12094        '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
12095      ],
12096      [
12097        '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
12098        '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
12099      ],
12100      [
12101        '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
12102        'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
12103      ],
12104      [
12105        '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
12106        '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
12107      ],
12108      [
12109        '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
12110        '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
12111      ],
12112      [
12113        '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
12114        '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
12115      ]
12116    ]
12117  }
12118};
12119
12120},{}],33:[function(require,module,exports){
12121'use strict';
12122
12123var utils = exports;
12124var BN = require('bn.js');
12125var minAssert = require('minimalistic-assert');
12126var minUtils = require('minimalistic-crypto-utils');
12127
12128utils.assert = minAssert;
12129utils.toArray = minUtils.toArray;
12130utils.zero2 = minUtils.zero2;
12131utils.toHex = minUtils.toHex;
12132utils.encode = minUtils.encode;
12133
12134// Represent num in a w-NAF form
12135function getNAF(num, w) {
12136  var naf = [];
12137  var ws = 1 << (w + 1);
12138  var k = num.clone();
12139  while (k.cmpn(1) >= 0) {
12140    var z;
12141    if (k.isOdd()) {
12142      var mod = k.andln(ws - 1);
12143      if (mod > (ws >> 1) - 1)
12144        z = (ws >> 1) - mod;
12145      else
12146        z = mod;
12147      k.isubn(z);
12148    } else {
12149      z = 0;
12150    }
12151    naf.push(z);
12152
12153    // Optimization, shift by word if possible
12154    var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
12155    for (var i = 1; i < shift; i++)
12156      naf.push(0);
12157    k.iushrn(shift);
12158  }
12159
12160  return naf;
12161}
12162utils.getNAF = getNAF;
12163
12164// Represent k1, k2 in a Joint Sparse Form
12165function getJSF(k1, k2) {
12166  var jsf = [
12167    [],
12168    []
12169  ];
12170
12171  k1 = k1.clone();
12172  k2 = k2.clone();
12173  var d1 = 0;
12174  var d2 = 0;
12175  while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
12176
12177    // First phase
12178    var m14 = (k1.andln(3) + d1) & 3;
12179    var m24 = (k2.andln(3) + d2) & 3;
12180    if (m14 === 3)
12181      m14 = -1;
12182    if (m24 === 3)
12183      m24 = -1;
12184    var u1;
12185    if ((m14 & 1) === 0) {
12186      u1 = 0;
12187    } else {
12188      var m8 = (k1.andln(7) + d1) & 7;
12189      if ((m8 === 3 || m8 === 5) && m24 === 2)
12190        u1 = -m14;
12191      else
12192        u1 = m14;
12193    }
12194    jsf[0].push(u1);
12195
12196    var u2;
12197    if ((m24 & 1) === 0) {
12198      u2 = 0;
12199    } else {
12200      var m8 = (k2.andln(7) + d2) & 7;
12201      if ((m8 === 3 || m8 === 5) && m14 === 2)
12202        u2 = -m24;
12203      else
12204        u2 = m24;
12205    }
12206    jsf[1].push(u2);
12207
12208    // Second phase
12209    if (2 * d1 === u1 + 1)
12210      d1 = 1 - d1;
12211    if (2 * d2 === u2 + 1)
12212      d2 = 1 - d2;
12213    k1.iushrn(1);
12214    k2.iushrn(1);
12215  }
12216
12217  return jsf;
12218}
12219utils.getJSF = getJSF;
12220
12221function cachedProperty(obj, name, computer) {
12222  var key = '_' + name;
12223  obj.prototype[name] = function cachedProperty() {
12224    return this[key] !== undefined ? this[key] :
12225           this[key] = computer.call(this);
12226  };
12227}
12228utils.cachedProperty = cachedProperty;
12229
12230function parseBytes(bytes) {
12231  return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
12232                                     bytes;
12233}
12234utils.parseBytes = parseBytes;
12235
12236function intFromLE(bytes) {
12237  return new BN(bytes, 'hex', 'le');
12238}
12239utils.intFromLE = intFromLE;
12240
12241
12242},{"bn.js":17,"minimalistic-assert":49,"minimalistic-crypto-utils":50}],34:[function(require,module,exports){
12243
12244// email-addresses.js - RFC 5322 email address parser
12245// v 3.0.1
12246//
12247// http://tools.ietf.org/html/rfc5322
12248//
12249// This library does not validate email addresses.
12250// emailAddresses attempts to parse addresses using the (fairly liberal)
12251// grammar specified in RFC 5322.
12252//
12253// email-addresses returns {
12254//     ast: <an abstract syntax tree based on rfc5322>,
12255//     addresses: [{
12256//            node: <node in ast for this address>,
12257//            name: <display-name>,
12258//            address: <addr-spec>,
12259//            local: <local-part>,
12260//            domain: <domain>
12261//         }, ...]
12262// }
12263//
12264// emailAddresses.parseOneAddress and emailAddresses.parseAddressList
12265// work as you might expect. Try it out.
12266//
12267// Many thanks to Dominic Sayers and his documentation on the is_email function,
12268// http://code.google.com/p/isemail/ , which helped greatly in writing this parser.
12269
12270(function (global) {
12271"use strict";
12272
12273function parse5322(opts) {
12274
12275    // tokenizing functions
12276
12277    function inStr() { return pos < len; }
12278    function curTok() { return parseString[pos]; }
12279    function getPos() { return pos; }
12280    function setPos(i) { pos = i; }
12281    function nextTok() { pos += 1; }
12282    function initialize() {
12283        pos = 0;
12284        len = parseString.length;
12285    }
12286
12287    // parser helper functions
12288
12289    function o(name, value) {
12290        return {
12291            name: name,
12292            tokens: value || "",
12293            semantic: value || "",
12294            children: []
12295        };
12296    }
12297
12298    function wrap(name, ast) {
12299        var n;
12300        if (ast === null) { return null; }
12301        n = o(name);
12302        n.tokens = ast.tokens;
12303        n.semantic = ast.semantic;
12304        n.children.push(ast);
12305        return n;
12306    }
12307
12308    function add(parent, child) {
12309        if (child !== null) {
12310            parent.tokens += child.tokens;
12311            parent.semantic += child.semantic;
12312        }
12313        parent.children.push(child);
12314        return parent;
12315    }
12316
12317    function compareToken(fxnCompare) {
12318        var tok;
12319        if (!inStr()) { return null; }
12320        tok = curTok();
12321        if (fxnCompare(tok)) {
12322            nextTok();
12323            return o('token', tok);
12324        }
12325        return null;
12326    }
12327
12328    function literal(lit) {
12329        return function literalFunc() {
12330            return wrap('literal', compareToken(function (tok) {
12331                return tok === lit;
12332            }));
12333        };
12334    }
12335
12336    function and() {
12337        var args = arguments;
12338        return function andFunc() {
12339            var i, s, result, start;
12340            start = getPos();
12341            s = o('and');
12342            for (i = 0; i < args.length; i += 1) {
12343                result = args[i]();
12344                if (result === null) {
12345                    setPos(start);
12346                    return null;
12347                }
12348                add(s, result);
12349            }
12350            return s;
12351        };
12352    }
12353
12354    function or() {
12355        var args = arguments;
12356        return function orFunc() {
12357            var i, result, start;
12358            start = getPos();
12359            for (i = 0; i < args.length; i += 1) {
12360                result = args[i]();
12361                if (result !== null) {
12362                    return result;
12363                }
12364                setPos(start);
12365            }
12366            return null;
12367        };
12368    }
12369
12370    function opt(prod) {
12371        return function optFunc() {
12372            var result, start;
12373            start = getPos();
12374            result = prod();
12375            if (result !== null) {
12376                return result;
12377            }
12378            else {
12379                setPos(start);
12380                return o('opt');
12381            }
12382        };
12383    }
12384
12385    function invis(prod) {
12386        return function invisFunc() {
12387            var result = prod();
12388            if (result !== null) {
12389                result.semantic = "";
12390            }
12391            return result;
12392        };
12393    }
12394
12395    function colwsp(prod) {
12396        return function collapseSemanticWhitespace() {
12397            var result = prod();
12398            if (result !== null && result.semantic.length > 0) {
12399                result.semantic = " ";
12400            }
12401            return result;
12402        };
12403    }
12404
12405    function star(prod, minimum) {
12406        return function starFunc() {
12407            var s, result, count, start, min;
12408            start = getPos();
12409            s = o('star');
12410            count = 0;
12411            min = minimum === undefined ? 0 : minimum;
12412            while ((result = prod()) !== null) {
12413                count = count + 1;
12414                add(s, result);
12415            }
12416            if (count >= min) {
12417                return s;
12418            }
12419            else {
12420                setPos(start);
12421                return null;
12422            }
12423        };
12424    }
12425
12426    // One expects names to get normalized like this:
12427    // "  First  Last " -> "First Last"
12428    // "First Last" -> "First Last"
12429    // "First   Last" -> "First Last"
12430    function collapseWhitespace(s) {
12431        return s.replace(/([ \t]|\r\n)+/g, ' ').replace(/^\s*/, '').replace(/\s*$/, '');
12432    }
12433
12434    // UTF-8 pseudo-production (RFC 6532)
12435    // RFC 6532 extends RFC 5322 productions to include UTF-8
12436    // using the following productions:
12437    // UTF8-non-ascii  =   UTF8-2 / UTF8-3 / UTF8-4
12438    // UTF8-2          =   <Defined in Section 4 of RFC3629>
12439    // UTF8-3          =   <Defined in Section 4 of RFC3629>
12440    // UTF8-4          =   <Defined in Section 4 of RFC3629>
12441    //
12442    // For reference, the extended RFC 5322 productions are:
12443    // VCHAR   =/  UTF8-non-ascii
12444    // ctext   =/  UTF8-non-ascii
12445    // atext   =/  UTF8-non-ascii
12446    // qtext   =/  UTF8-non-ascii
12447    // dtext   =/  UTF8-non-ascii
12448    function isUTF8NonAscii(tok) {
12449        // In JavaScript, we just deal directly with Unicode code points,
12450        // so we aren't checking individual bytes for UTF-8 encoding.
12451        // Just check that the character is non-ascii.
12452        return tok.charCodeAt(0) >= 128;
12453    }
12454
12455
12456    // common productions (RFC 5234)
12457    // http://tools.ietf.org/html/rfc5234
12458    // B.1. Core Rules
12459
12460    // CR             =  %x0D
12461    //                         ; carriage return
12462    function cr() { return wrap('cr', literal('\r')()); }
12463
12464    // CRLF           =  CR LF
12465    //                         ; Internet standard newline
12466    function crlf() { return wrap('crlf', and(cr, lf)()); }
12467
12468    // DQUOTE         =  %x22
12469    //                         ; " (Double Quote)
12470    function dquote() { return wrap('dquote', literal('"')()); }
12471
12472    // HTAB           =  %x09
12473    //                         ; horizontal tab
12474    function htab() { return wrap('htab', literal('\t')()); }
12475
12476    // LF             =  %x0A
12477    //                         ; linefeed
12478    function lf() { return wrap('lf', literal('\n')()); }
12479
12480    // SP             =  %x20
12481    function sp() { return wrap('sp', literal(' ')()); }
12482
12483    // VCHAR          =  %x21-7E
12484    //                         ; visible (printing) characters
12485    function vchar() {
12486        return wrap('vchar', compareToken(function vcharFunc(tok) {
12487            var code = tok.charCodeAt(0);
12488            var accept = (0x21 <= code && code <= 0x7E);
12489            if (opts.rfc6532) {
12490                accept = accept || isUTF8NonAscii(tok);
12491            }
12492            return accept;
12493        }));
12494    }
12495
12496    // WSP            =  SP / HTAB
12497    //                         ; white space
12498    function wsp() { return wrap('wsp', or(sp, htab)()); }
12499
12500
12501    // email productions (RFC 5322)
12502    // http://tools.ietf.org/html/rfc5322
12503    // 3.2.1. Quoted characters
12504
12505    // quoted-pair     =   ("\" (VCHAR / WSP)) / obs-qp
12506    function quotedPair() {
12507        var qp = wrap('quoted-pair',
12508        or(
12509            and(literal('\\'), or(vchar, wsp)),
12510            obsQP
12511        )());
12512        if (qp === null) { return null; }
12513        // a quoted pair will be two characters, and the "\" character
12514        // should be semantically "invisible" (RFC 5322 3.2.1)
12515        qp.semantic = qp.semantic[1];
12516        return qp;
12517    }
12518
12519    // 3.2.2. Folding White Space and Comments
12520
12521    // FWS             =   ([*WSP CRLF] 1*WSP) /  obs-FWS
12522    function fws() {
12523        return wrap('fws', or(
12524            obsFws,
12525            and(
12526                opt(and(
12527                    star(wsp),
12528                    invis(crlf)
12529                   )),
12530                star(wsp, 1)
12531            )
12532        )());
12533    }
12534
12535    // ctext           =   %d33-39 /          ; Printable US-ASCII
12536    //                     %d42-91 /          ;  characters not including
12537    //                     %d93-126 /         ;  "(", ")", or "\"
12538    //                     obs-ctext
12539    function ctext() {
12540        return wrap('ctext', or(
12541            function ctextFunc1() {
12542                return compareToken(function ctextFunc2(tok) {
12543                    var code = tok.charCodeAt(0);
12544                    var accept =
12545                        (33 <= code && code <= 39) ||
12546                        (42 <= code && code <= 91) ||
12547                        (93 <= code && code <= 126);
12548                    if (opts.rfc6532) {
12549                        accept = accept || isUTF8NonAscii(tok);
12550                    }
12551                    return accept;
12552                });
12553            },
12554            obsCtext
12555        )());
12556    }
12557
12558    // ccontent        =   ctext / quoted-pair / comment
12559    function ccontent() {
12560        return wrap('ccontent', or(ctext, quotedPair, comment)());
12561    }
12562
12563    // comment         =   "(" *([FWS] ccontent) [FWS] ")"
12564    function comment() {
12565        return wrap('comment', and(
12566            literal('('),
12567            star(and(opt(fws), ccontent)),
12568            opt(fws),
12569            literal(')')
12570        )());
12571    }
12572
12573    // CFWS            =   (1*([FWS] comment) [FWS]) / FWS
12574    function cfws() {
12575        return wrap('cfws', or(
12576            and(
12577                star(
12578                    and(opt(fws), comment),
12579                    1
12580                ),
12581                opt(fws)
12582            ),
12583            fws
12584        )());
12585    }
12586
12587    // 3.2.3. Atom
12588
12589    //atext           =   ALPHA / DIGIT /    ; Printable US-ASCII
12590    //                       "!" / "#" /        ;  characters not including
12591    //                       "$" / "%" /        ;  specials.  Used for atoms.
12592    //                       "&" / "'" /
12593    //                       "*" / "+" /
12594    //                       "-" / "/" /
12595    //                       "=" / "?" /
12596    //                       "^" / "_" /
12597    //                       "`" / "{" /
12598    //                       "|" / "}" /
12599    //                       "~"
12600    function atext() {
12601        return wrap('atext', compareToken(function atextFunc(tok) {
12602            var accept =
12603                ('a' <= tok && tok <= 'z') ||
12604                ('A' <= tok && tok <= 'Z') ||
12605                ('0' <= tok && tok <= '9') ||
12606                (['!', '#', '$', '%', '&', '\'', '*', '+', '-', '/',
12607                  '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0);
12608            if (opts.rfc6532) {
12609                accept = accept || isUTF8NonAscii(tok);
12610            }
12611            return accept;
12612        }));
12613    }
12614
12615    // atom            =   [CFWS] 1*atext [CFWS]
12616    function atom() {
12617        return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))());
12618    }
12619
12620    // dot-atom-text   =   1*atext *("." 1*atext)
12621    function dotAtomText() {
12622        var s, maybeText;
12623        s = wrap('dot-atom-text', star(atext, 1)());
12624        if (s === null) { return s; }
12625        maybeText = star(and(literal('.'), star(atext, 1)))();
12626        if (maybeText !== null) {
12627            add(s, maybeText);
12628        }
12629        return s;
12630    }
12631
12632    // dot-atom        =   [CFWS] dot-atom-text [CFWS]
12633    function dotAtom() {
12634        return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))());
12635    }
12636
12637    // 3.2.4. Quoted Strings
12638
12639    //  qtext           =   %d33 /             ; Printable US-ASCII
12640    //                      %d35-91 /          ;  characters not including
12641    //                      %d93-126 /         ;  "\" or the quote character
12642    //                      obs-qtext
12643    function qtext() {
12644        return wrap('qtext', or(
12645            function qtextFunc1() {
12646                return compareToken(function qtextFunc2(tok) {
12647                    var code = tok.charCodeAt(0);
12648                    var accept =
12649                        (33 === code) ||
12650                        (35 <= code && code <= 91) ||
12651                        (93 <= code && code <= 126);
12652                    if (opts.rfc6532) {
12653                        accept = accept || isUTF8NonAscii(tok);
12654                    }
12655                    return accept;
12656                });
12657            },
12658            obsQtext
12659        )());
12660    }
12661
12662    // qcontent        =   qtext / quoted-pair
12663    function qcontent() {
12664        return wrap('qcontent', or(qtext, quotedPair)());
12665    }
12666
12667    //  quoted-string   =   [CFWS]
12668    //                      DQUOTE *([FWS] qcontent) [FWS] DQUOTE
12669    //                      [CFWS]
12670    function quotedString() {
12671        return wrap('quoted-string', and(
12672            invis(opt(cfws)),
12673            invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote),
12674            invis(opt(cfws))
12675        )());
12676    }
12677
12678    // 3.2.5 Miscellaneous Tokens
12679
12680    // word            =   atom / quoted-string
12681    function word() {
12682        return wrap('word', or(atom, quotedString)());
12683    }
12684
12685    // phrase          =   1*word / obs-phrase
12686    function phrase() {
12687        return wrap('phrase', or(obsPhrase, star(word, 1))());
12688    }
12689
12690    // 3.4. Address Specification
12691    //   address         =   mailbox / group
12692    function address() {
12693        return wrap('address', or(mailbox, group)());
12694    }
12695
12696    //   mailbox         =   name-addr / addr-spec
12697    function mailbox() {
12698        return wrap('mailbox', or(nameAddr, addrSpec)());
12699    }
12700
12701    //   name-addr       =   [display-name] angle-addr
12702    function nameAddr() {
12703        return wrap('name-addr', and(opt(displayName), angleAddr)());
12704    }
12705
12706    //   angle-addr      =   [CFWS] "<" addr-spec ">" [CFWS] /
12707    //                       obs-angle-addr
12708    function angleAddr() {
12709        return wrap('angle-addr', or(
12710            and(
12711                invis(opt(cfws)),
12712                literal('<'),
12713                addrSpec,
12714                literal('>'),
12715                invis(opt(cfws))
12716            ),
12717            obsAngleAddr
12718        )());
12719    }
12720
12721    //   group           =   display-name ":" [group-list] ";" [CFWS]
12722    function group() {
12723        return wrap('group', and(
12724            displayName,
12725            literal(':'),
12726            opt(groupList),
12727            literal(';'),
12728            invis(opt(cfws))
12729        )());
12730    }
12731
12732    //   display-name    =   phrase
12733    function displayName() {
12734        return wrap('display-name', function phraseFixedSemantic() {
12735            var result = phrase();
12736            if (result !== null) {
12737                result.semantic = collapseWhitespace(result.semantic);
12738            }
12739            return result;
12740        }());
12741    }
12742
12743    //   mailbox-list    =   (mailbox *("," mailbox)) / obs-mbox-list
12744    function mailboxList() {
12745        return wrap('mailbox-list', or(
12746            and(
12747                mailbox,
12748                star(and(literal(','), mailbox))
12749            ),
12750            obsMboxList
12751        )());
12752    }
12753
12754    //   address-list    =   (address *("," address)) / obs-addr-list
12755    function addressList() {
12756        return wrap('address-list', or(
12757            and(
12758                address,
12759                star(and(literal(','), address))
12760            ),
12761            obsAddrList
12762        )());
12763    }
12764
12765    //   group-list      =   mailbox-list / CFWS / obs-group-list
12766    function groupList() {
12767        return wrap('group-list', or(
12768            mailboxList,
12769            invis(cfws),
12770            obsGroupList
12771        )());
12772    }
12773
12774    // 3.4.1 Addr-Spec Specification
12775
12776    // local-part      =   dot-atom / quoted-string / obs-local-part
12777    function localPart() {
12778        // note: quoted-string, dotAtom are proper subsets of obs-local-part
12779        // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree
12780        return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)());
12781    }
12782
12783    //  dtext           =   %d33-90 /          ; Printable US-ASCII
12784    //                      %d94-126 /         ;  characters not including
12785    //                      obs-dtext          ;  "[", "]", or "\"
12786    function dtext() {
12787        return wrap('dtext', or(
12788            function dtextFunc1() {
12789                return compareToken(function dtextFunc2(tok) {
12790                    var code = tok.charCodeAt(0);
12791                    var accept =
12792                        (33 <= code && code <= 90) ||
12793                        (94 <= code && code <= 126);
12794                    if (opts.rfc6532) {
12795                        accept = accept || isUTF8NonAscii(tok);
12796                    }
12797                    return accept;
12798                });
12799            },
12800            obsDtext
12801            )()
12802        );
12803    }
12804
12805    // domain-literal  =   [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
12806    function domainLiteral() {
12807        return wrap('domain-literal', and(
12808            invis(opt(cfws)),
12809            literal('['),
12810            star(and(opt(fws), dtext)),
12811            opt(fws),
12812            literal(']'),
12813            invis(opt(cfws))
12814        )());
12815    }
12816
12817    // domain          =   dot-atom / domain-literal / obs-domain
12818    function domain() {
12819        return wrap('domain', function domainCheckTLD() {
12820            var result = or(obsDomain, dotAtom, domainLiteral)();
12821            if (opts.rejectTLD) {
12822                if (result.semantic.indexOf('.') < 0) {
12823                    return null;
12824                }
12825            }
12826            // strip all whitespace from domains
12827            if (result) {
12828                result.semantic = result.semantic.replace(/\s+/g, '');
12829            }
12830            return result;
12831        }());
12832    }
12833
12834    // addr-spec       =   local-part "@" domain
12835    function addrSpec() {
12836        return wrap('addr-spec', and(
12837            localPart, literal('@'), domain
12838        )());
12839    }
12840
12841    // 3.6.2 Originator Fields
12842    // Below we only parse the field body, not the name of the field
12843    // like "From:", "Sender:", or "Reply-To:". Other libraries that
12844    // parse email headers can parse those and defer to these productions
12845    // for the "RFC 5322" part.
12846
12847    // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
12848    // from = "From:" (mailbox-list / address-list) CRLF
12849    function fromSpec() {
12850        return wrap('from', or(
12851            mailboxList,
12852            addressList
12853        )());
12854    }
12855
12856    // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
12857    // sender = "Sender:" (mailbox / address) CRLF
12858    function senderSpec() {
12859        return wrap('sender', or(
12860            mailbox,
12861            address
12862        )());
12863    }
12864
12865    // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
12866    // reply-to = "Reply-To:" address-list CRLF
12867    function replyToSpec() {
12868        return wrap('reply-to', addressList());
12869    }
12870
12871    // 4.1. Miscellaneous Obsolete Tokens
12872
12873    //  obs-NO-WS-CTL   =   %d1-8 /            ; US-ASCII control
12874    //                      %d11 /             ;  characters that do not
12875    //                      %d12 /             ;  include the carriage
12876    //                      %d14-31 /          ;  return, line feed, and
12877    //                      %d127              ;  white space characters
12878    function obsNoWsCtl() {
12879        return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) {
12880            var code = tok.charCodeAt(0);
12881            return ((1 <= code && code <= 8) ||
12882                    (11 === code || 12 === code) ||
12883                    (14 <= code && code <= 31) ||
12884                    (127 === code));
12885        }));
12886    }
12887
12888    // obs-ctext       =   obs-NO-WS-CTL
12889    function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); }
12890
12891    // obs-qtext       =   obs-NO-WS-CTL
12892    function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); }
12893
12894    // obs-qp          =   "\" (%d0 / obs-NO-WS-CTL / LF / CR)
12895    function obsQP() {
12896        return opts.strict ? null : wrap('obs-qp', and(
12897            literal('\\'),
12898            or(literal('\0'), obsNoWsCtl, lf, cr)
12899        )());
12900    }
12901
12902    // obs-phrase      =   word *(word / "." / CFWS)
12903    function obsPhrase() {
12904        return opts.strict ? null : wrap('obs-phrase', and(
12905            word,
12906            star(or(word, literal('.'), colwsp(cfws)))
12907        )());
12908    }
12909
12910    // 4.2. Obsolete Folding White Space
12911
12912    // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908
12913    // obs-FWS         =   1*([CRLF] WSP)
12914    function obsFws() {
12915        return opts.strict ? null : wrap('obs-FWS', star(
12916            and(invis(opt(crlf)), wsp),
12917            1
12918        )());
12919    }
12920
12921    // 4.4. Obsolete Addressing
12922
12923    // obs-angle-addr  =   [CFWS] "<" obs-route addr-spec ">" [CFWS]
12924    function obsAngleAddr() {
12925        return opts.strict ? null : wrap('obs-angle-addr', and(
12926            invis(opt(cfws)),
12927            literal('<'),
12928            obsRoute,
12929            addrSpec,
12930            literal('>'),
12931            invis(opt(cfws))
12932        )());
12933    }
12934
12935    // obs-route       =   obs-domain-list ":"
12936    function obsRoute() {
12937        return opts.strict ? null : wrap('obs-route', and(
12938            obsDomainList,
12939            literal(':')
12940        )());
12941    }
12942
12943    //   obs-domain-list =   *(CFWS / ",") "@" domain
12944    //                       *("," [CFWS] ["@" domain])
12945    function obsDomainList() {
12946        return opts.strict ? null : wrap('obs-domain-list', and(
12947            star(or(invis(cfws), literal(','))),
12948            literal('@'),
12949            domain,
12950            star(and(
12951                literal(','),
12952                invis(opt(cfws)),
12953                opt(and(literal('@'), domain))
12954            ))
12955        )());
12956    }
12957
12958    // obs-mbox-list   =   *([CFWS] ",") mailbox *("," [mailbox / CFWS])
12959    function obsMboxList() {
12960        return opts.strict ? null : wrap('obs-mbox-list', and(
12961            star(and(
12962                invis(opt(cfws)),
12963                literal(',')
12964            )),
12965            mailbox,
12966            star(and(
12967                literal(','),
12968                opt(and(
12969                    mailbox,
12970                    invis(cfws)
12971                ))
12972            ))
12973        )());
12974    }
12975
12976    // obs-addr-list   =   *([CFWS] ",") address *("," [address / CFWS])
12977    function obsAddrList() {
12978        return opts.strict ? null : wrap('obs-addr-list', and(
12979            star(and(
12980                invis(opt(cfws)),
12981                literal(',')
12982            )),
12983            address,
12984            star(and(
12985                literal(','),
12986                opt(and(
12987                    address,
12988                    invis(cfws)
12989                ))
12990            ))
12991        )());
12992    }
12993
12994    // obs-group-list  =   1*([CFWS] ",") [CFWS]
12995    function obsGroupList() {
12996        return opts.strict ? null : wrap('obs-group-list', and(
12997            star(and(
12998                invis(opt(cfws)),
12999                literal(',')
13000            ), 1),
13001            invis(opt(cfws))
13002        )());
13003    }
13004
13005    // obs-local-part = word *("." word)
13006    function obsLocalPart() {
13007        return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))());
13008    }
13009
13010    // obs-domain       = atom *("." atom)
13011    function obsDomain() {
13012        return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))());
13013    }
13014
13015    // obs-dtext       =   obs-NO-WS-CTL / quoted-pair
13016    function obsDtext() {
13017        return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)());
13018    }
13019
13020    /////////////////////////////////////////////////////
13021
13022    // ast analysis
13023
13024    function findNode(name, root) {
13025        var i, stack, node;
13026        if (root === null || root === undefined) { return null; }
13027        stack = [root];
13028        while (stack.length > 0) {
13029            node = stack.pop();
13030            if (node.name === name) {
13031                return node;
13032            }
13033            for (i = node.children.length - 1; i >= 0; i -= 1) {
13034                stack.push(node.children[i]);
13035            }
13036        }
13037        return null;
13038    }
13039
13040    function findAllNodes(name, root) {
13041        var i, stack, node, result;
13042        if (root === null || root === undefined) { return null; }
13043        stack = [root];
13044        result = [];
13045        while (stack.length > 0) {
13046            node = stack.pop();
13047            if (node.name === name) {
13048                result.push(node);
13049            }
13050            for (i = node.children.length - 1; i >= 0; i -= 1) {
13051                stack.push(node.children[i]);
13052            }
13053        }
13054        return result;
13055    }
13056
13057    function findAllNodesNoChildren(names, root) {
13058        var i, stack, node, result, namesLookup;
13059        if (root === null || root === undefined) { return null; }
13060        stack = [root];
13061        result = [];
13062        namesLookup = {};
13063        for (i = 0; i < names.length; i += 1) {
13064            namesLookup[names[i]] = true;
13065        }
13066
13067        while (stack.length > 0) {
13068            node = stack.pop();
13069            if (node.name in namesLookup) {
13070                result.push(node);
13071                // don't look at children (hence findAllNodesNoChildren)
13072            } else {
13073                for (i = node.children.length - 1; i >= 0; i -= 1) {
13074                    stack.push(node.children[i]);
13075                }
13076            }
13077        }
13078        return result;
13079    }
13080
13081    function giveResult(ast) {
13082        var addresses, groupsAndMailboxes, i, groupOrMailbox, result;
13083        if (ast === null) {
13084            return null;
13085        }
13086        addresses = [];
13087
13088        // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'.
13089        groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast);
13090        for (i = 0; i <  groupsAndMailboxes.length; i += 1) {
13091            groupOrMailbox = groupsAndMailboxes[i];
13092            if (groupOrMailbox.name === 'group') {
13093                addresses.push(giveResultGroup(groupOrMailbox));
13094            } else if (groupOrMailbox.name === 'mailbox') {
13095                addresses.push(giveResultMailbox(groupOrMailbox));
13096            }
13097        }
13098
13099        result = {
13100            ast: ast,
13101            addresses: addresses,
13102        };
13103        if (opts.simple) {
13104            result = simplifyResult(result);
13105        }
13106        if (opts.oneResult) {
13107            return oneResult(result);
13108        }
13109        if (opts.simple) {
13110            return result && result.addresses;
13111        } else {
13112            return result;
13113        }
13114    }
13115
13116    function giveResultGroup(group) {
13117        var i;
13118        var groupName = findNode('display-name', group);
13119        var groupResultMailboxes = [];
13120        var mailboxes = findAllNodesNoChildren(['mailbox'], group);
13121        for (i = 0; i < mailboxes.length; i += 1) {
13122            groupResultMailboxes.push(giveResultMailbox(mailboxes[i]));
13123        }
13124        return {
13125            node: group,
13126            parts: {
13127                name: groupName,
13128            },
13129            type: group.name, // 'group'
13130            name: grabSemantic(groupName),
13131            addresses: groupResultMailboxes,
13132        };
13133    }
13134
13135    function giveResultMailbox(mailbox) {
13136        var name = findNode('display-name', mailbox);
13137        var aspec = findNode('addr-spec', mailbox);
13138        var comments = findAllNodes('cfws', mailbox);
13139
13140        var local = findNode('local-part', aspec);
13141        var domain = findNode('domain', aspec);
13142        return {
13143            node: mailbox,
13144            parts: {
13145                name: name,
13146                address: aspec,
13147                local: local,
13148                domain: domain,
13149                comments: comments
13150            },
13151            type: mailbox.name, // 'mailbox'
13152            name: grabSemantic(name),
13153            address: grabSemantic(aspec),
13154            local: grabSemantic(local),
13155            domain: grabSemantic(domain),
13156            groupName: grabSemantic(mailbox.groupName),
13157        };
13158    }
13159
13160    function grabSemantic(n) {
13161        return n !== null && n !== undefined ? n.semantic : null;
13162    }
13163
13164    function simplifyResult(result) {
13165        var i;
13166        if (result && result.addresses) {
13167            for (i = 0; i < result.addresses.length; i += 1) {
13168                delete result.addresses[i].node;
13169            }
13170        }
13171        return result;
13172    }
13173
13174    function oneResult(result) {
13175        if (!result) { return null; }
13176        if (!opts.partial && result.addresses.length > 1) { return null; }
13177        return result.addresses && result.addresses[0];
13178    }
13179
13180    /////////////////////////////////////////////////////
13181
13182    var parseString, pos, len, parsed, startProduction;
13183
13184    opts = handleOpts(opts, {});
13185    if (opts === null) { return null; }
13186
13187    parseString = opts.input;
13188
13189    startProduction = {
13190        'address': address,
13191        'address-list': addressList,
13192        'angle-addr': angleAddr,
13193        'from': fromSpec,
13194        'group': group,
13195        'mailbox': mailbox,
13196        'mailbox-list': mailboxList,
13197        'reply-to': replyToSpec,
13198        'sender': senderSpec,
13199    }[opts.startAt] || addressList;
13200
13201    if (!opts.strict) {
13202        initialize();
13203        opts.strict = true;
13204        parsed = startProduction(parseString);
13205        if (opts.partial || !inStr()) {
13206            return giveResult(parsed);
13207        }
13208        opts.strict = false;
13209    }
13210
13211    initialize();
13212    parsed = startProduction(parseString);
13213    if (!opts.partial && inStr()) { return null; }
13214    return giveResult(parsed);
13215}
13216
13217function parseOneAddressSimple(opts) {
13218    return parse5322(handleOpts(opts, {
13219        oneResult: true,
13220        rfc6532: true,
13221        simple: true,
13222        startAt: 'address-list',
13223    }));
13224}
13225
13226function parseAddressListSimple(opts) {
13227    return parse5322(handleOpts(opts, {
13228        rfc6532: true,
13229        simple: true,
13230        startAt: 'address-list',
13231    }));
13232}
13233
13234function parseFromSimple(opts) {
13235    return parse5322(handleOpts(opts, {
13236        rfc6532: true,
13237        simple: true,
13238        startAt: 'from',
13239    }));
13240}
13241
13242function parseSenderSimple(opts) {
13243    return parse5322(handleOpts(opts, {
13244        oneResult: true,
13245        rfc6532: true,
13246        simple: true,
13247        startAt: 'sender',
13248    }));
13249}
13250
13251function parseReplyToSimple(opts) {
13252    return parse5322(handleOpts(opts, {
13253        rfc6532: true,
13254        simple: true,
13255        startAt: 'reply-to',
13256    }));
13257}
13258
13259function handleOpts(opts, defs) {
13260    function isString(str) {
13261        return Object.prototype.toString.call(str) === '[object String]';
13262    }
13263
13264    function isObject(o) {
13265        return o === Object(o);
13266    }
13267
13268    function isNullUndef(o) {
13269        return o === null || o === undefined;
13270    }
13271
13272    var defaults, o;
13273
13274    if (isString(opts)) {
13275        opts = { input: opts };
13276    } else if (!isObject(opts)) {
13277        return null;
13278    }
13279
13280    if (!isString(opts.input)) { return null; }
13281    if (!defs) { return null; }
13282
13283    defaults = {
13284        oneResult: false,
13285        partial: false,
13286        rejectTLD: false,
13287        rfc6532: false,
13288        simple: false,
13289        startAt: 'address-list',
13290        strict: false,
13291    };
13292
13293    for (o in defaults) {
13294        if (isNullUndef(opts[o])) {
13295            opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o];
13296        }
13297    }
13298    return opts;
13299}
13300
13301parse5322.parseOneAddress = parseOneAddressSimple;
13302parse5322.parseAddressList = parseAddressListSimple;
13303parse5322.parseFrom = parseFromSimple;
13304parse5322.parseSender = parseSenderSimple;
13305parse5322.parseReplyTo = parseReplyToSimple;
13306
13307if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
13308    module.exports = parse5322;
13309} else {
13310    global.emailAddresses = parse5322;
13311}
13312
13313}(this));
13314
13315},{}],35:[function(require,module,exports){
13316var hash = exports;
13317
13318hash.utils = require('./hash/utils');
13319hash.common = require('./hash/common');
13320hash.sha = require('./hash/sha');
13321hash.ripemd = require('./hash/ripemd');
13322hash.hmac = require('./hash/hmac');
13323
13324// Proxy hash functions to the main object
13325hash.sha1 = hash.sha.sha1;
13326hash.sha256 = hash.sha.sha256;
13327hash.sha224 = hash.sha.sha224;
13328hash.sha384 = hash.sha.sha384;
13329hash.sha512 = hash.sha.sha512;
13330hash.ripemd160 = hash.ripemd.ripemd160;
13331
13332},{"./hash/common":36,"./hash/hmac":37,"./hash/ripemd":38,"./hash/sha":39,"./hash/utils":46}],36:[function(require,module,exports){
13333'use strict';
13334
13335var utils = require('./utils');
13336var assert = require('minimalistic-assert');
13337
13338function BlockHash() {
13339  this.pending = null;
13340  this.pendingTotal = 0;
13341  this.blockSize = this.constructor.blockSize;
13342  this.outSize = this.constructor.outSize;
13343  this.hmacStrength = this.constructor.hmacStrength;
13344  this.padLength = this.constructor.padLength / 8;
13345  this.endian = 'big';
13346
13347  this._delta8 = this.blockSize / 8;
13348  this._delta32 = this.blockSize / 32;
13349}
13350exports.BlockHash = BlockHash;
13351
13352BlockHash.prototype.update = function update(msg, enc) {
13353  // Convert message to array, pad it, and join into 32bit blocks
13354  msg = utils.toArray(msg, enc);
13355  if (!this.pending)
13356    this.pending = msg;
13357  else
13358    this.pending = this.pending.concat(msg);
13359  this.pendingTotal += msg.length;
13360
13361  // Enough data, try updating
13362  if (this.pending.length >= this._delta8) {
13363    msg = this.pending;
13364
13365    // Process pending data in blocks
13366    var r = msg.length % this._delta8;
13367    this.pending = msg.slice(msg.length - r, msg.length);
13368    if (this.pending.length === 0)
13369      this.pending = null;
13370
13371    msg = utils.join32(msg, 0, msg.length - r, this.endian);
13372    for (var i = 0; i < msg.length; i += this._delta32)
13373      this._update(msg, i, i + this._delta32);
13374  }
13375
13376  return this;
13377};
13378
13379BlockHash.prototype.digest = function digest(enc) {
13380  this.update(this._pad());
13381  assert(this.pending === null);
13382
13383  return this._digest(enc);
13384};
13385
13386BlockHash.prototype._pad = function pad() {
13387  var len = this.pendingTotal;
13388  var bytes = this._delta8;
13389  var k = bytes - ((len + this.padLength) % bytes);
13390  var res = new Array(k + this.padLength);
13391  res[0] = 0x80;
13392  for (var i = 1; i < k; i++)
13393    res[i] = 0;
13394
13395  // Append length
13396  len <<= 3;
13397  if (this.endian === 'big') {
13398    for (var t = 8; t < this.padLength; t++)
13399      res[i++] = 0;
13400
13401    res[i++] = 0;
13402    res[i++] = 0;
13403    res[i++] = 0;
13404    res[i++] = 0;
13405    res[i++] = (len >>> 24) & 0xff;
13406    res[i++] = (len >>> 16) & 0xff;
13407    res[i++] = (len >>> 8) & 0xff;
13408    res[i++] = len & 0xff;
13409  } else {
13410    res[i++] = len & 0xff;
13411    res[i++] = (len >>> 8) & 0xff;
13412    res[i++] = (len >>> 16) & 0xff;
13413    res[i++] = (len >>> 24) & 0xff;
13414    res[i++] = 0;
13415    res[i++] = 0;
13416    res[i++] = 0;
13417    res[i++] = 0;
13418
13419    for (t = 8; t < this.padLength; t++)
13420      res[i++] = 0;
13421  }
13422
13423  return res;
13424};
13425
13426},{"./utils":46,"minimalistic-assert":49}],37:[function(require,module,exports){
13427'use strict';
13428
13429var utils = require('./utils');
13430var assert = require('minimalistic-assert');
13431
13432function Hmac(hash, key, enc) {
13433  if (!(this instanceof Hmac))
13434    return new Hmac(hash, key, enc);
13435  this.Hash = hash;
13436  this.blockSize = hash.blockSize / 8;
13437  this.outSize = hash.outSize / 8;
13438  this.inner = null;
13439  this.outer = null;
13440
13441  this._init(utils.toArray(key, enc));
13442}
13443module.exports = Hmac;
13444
13445Hmac.prototype._init = function init(key) {
13446  // Shorten key, if needed
13447  if (key.length > this.blockSize)
13448    key = new this.Hash().update(key).digest();
13449  assert(key.length <= this.blockSize);
13450
13451  // Add padding to key
13452  for (var i = key.length; i < this.blockSize; i++)
13453    key.push(0);
13454
13455  for (i = 0; i < key.length; i++)
13456    key[i] ^= 0x36;
13457  this.inner = new this.Hash().update(key);
13458
13459  // 0x36 ^ 0x5c = 0x6a
13460  for (i = 0; i < key.length; i++)
13461    key[i] ^= 0x6a;
13462  this.outer = new this.Hash().update(key);
13463};
13464
13465Hmac.prototype.update = function update(msg, enc) {
13466  this.inner.update(msg, enc);
13467  return this;
13468};
13469
13470Hmac.prototype.digest = function digest(enc) {
13471  this.outer.update(this.inner.digest());
13472  return this.outer.digest(enc);
13473};
13474
13475},{"./utils":46,"minimalistic-assert":49}],38:[function(require,module,exports){
13476'use strict';
13477
13478var utils = require('./utils');
13479var common = require('./common');
13480
13481var rotl32 = utils.rotl32;
13482var sum32 = utils.sum32;
13483var sum32_3 = utils.sum32_3;
13484var sum32_4 = utils.sum32_4;
13485var BlockHash = common.BlockHash;
13486
13487function RIPEMD160() {
13488  if (!(this instanceof RIPEMD160))
13489    return new RIPEMD160();
13490
13491  BlockHash.call(this);
13492
13493  this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
13494  this.endian = 'little';
13495}
13496utils.inherits(RIPEMD160, BlockHash);
13497exports.ripemd160 = RIPEMD160;
13498
13499RIPEMD160.blockSize = 512;
13500RIPEMD160.outSize = 160;
13501RIPEMD160.hmacStrength = 192;
13502RIPEMD160.padLength = 64;
13503
13504RIPEMD160.prototype._update = function update(msg, start) {
13505  var A = this.h[0];
13506  var B = this.h[1];
13507  var C = this.h[2];
13508  var D = this.h[3];
13509  var E = this.h[4];
13510  var Ah = A;
13511  var Bh = B;
13512  var Ch = C;
13513  var Dh = D;
13514  var Eh = E;
13515  for (var j = 0; j < 80; j++) {
13516    var T = sum32(
13517      rotl32(
13518        sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
13519        s[j]),
13520      E);
13521    A = E;
13522    E = D;
13523    D = rotl32(C, 10);
13524    C = B;
13525    B = T;
13526    T = sum32(
13527      rotl32(
13528        sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
13529        sh[j]),
13530      Eh);
13531    Ah = Eh;
13532    Eh = Dh;
13533    Dh = rotl32(Ch, 10);
13534    Ch = Bh;
13535    Bh = T;
13536  }
13537  T = sum32_3(this.h[1], C, Dh);
13538  this.h[1] = sum32_3(this.h[2], D, Eh);
13539  this.h[2] = sum32_3(this.h[3], E, Ah);
13540  this.h[3] = sum32_3(this.h[4], A, Bh);
13541  this.h[4] = sum32_3(this.h[0], B, Ch);
13542  this.h[0] = T;
13543};
13544
13545RIPEMD160.prototype._digest = function digest(enc) {
13546  if (enc === 'hex')
13547    return utils.toHex32(this.h, 'little');
13548  else
13549    return utils.split32(this.h, 'little');
13550};
13551
13552function f(j, x, y, z) {
13553  if (j <= 15)
13554    return x ^ y ^ z;
13555  else if (j <= 31)
13556    return (x & y) | ((~x) & z);
13557  else if (j <= 47)
13558    return (x | (~y)) ^ z;
13559  else if (j <= 63)
13560    return (x & z) | (y & (~z));
13561  else
13562    return x ^ (y | (~z));
13563}
13564
13565function K(j) {
13566  if (j <= 15)
13567    return 0x00000000;
13568  else if (j <= 31)
13569    return 0x5a827999;
13570  else if (j <= 47)
13571    return 0x6ed9eba1;
13572  else if (j <= 63)
13573    return 0x8f1bbcdc;
13574  else
13575    return 0xa953fd4e;
13576}
13577
13578function Kh(j) {
13579  if (j <= 15)
13580    return 0x50a28be6;
13581  else if (j <= 31)
13582    return 0x5c4dd124;
13583  else if (j <= 47)
13584    return 0x6d703ef3;
13585  else if (j <= 63)
13586    return 0x7a6d76e9;
13587  else
13588    return 0x00000000;
13589}
13590
13591var r = [
13592  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
13593  7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
13594  3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
13595  1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
13596  4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
13597];
13598
13599var rh = [
13600  5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
13601  6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
13602  15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
13603  8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
13604  12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
13605];
13606
13607var s = [
13608  11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
13609  7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
13610  11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
13611  11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
13612  9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
13613];
13614
13615var sh = [
13616  8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
13617  9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
13618  9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
13619  15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
13620  8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
13621];
13622
13623},{"./common":36,"./utils":46}],39:[function(require,module,exports){
13624'use strict';
13625
13626exports.sha1 = require('./sha/1');
13627exports.sha224 = require('./sha/224');
13628exports.sha256 = require('./sha/256');
13629exports.sha384 = require('./sha/384');
13630exports.sha512 = require('./sha/512');
13631
13632},{"./sha/1":40,"./sha/224":41,"./sha/256":42,"./sha/384":43,"./sha/512":44}],40:[function(require,module,exports){
13633'use strict';
13634
13635var utils = require('../utils');
13636var common = require('../common');
13637var shaCommon = require('./common');
13638
13639var rotl32 = utils.rotl32;
13640var sum32 = utils.sum32;
13641var sum32_5 = utils.sum32_5;
13642var ft_1 = shaCommon.ft_1;
13643var BlockHash = common.BlockHash;
13644
13645var sha1_K = [
13646  0x5A827999, 0x6ED9EBA1,
13647  0x8F1BBCDC, 0xCA62C1D6
13648];
13649
13650function SHA1() {
13651  if (!(this instanceof SHA1))
13652    return new SHA1();
13653
13654  BlockHash.call(this);
13655  this.h = [
13656    0x67452301, 0xefcdab89, 0x98badcfe,
13657    0x10325476, 0xc3d2e1f0 ];
13658  this.W = new Array(80);
13659}
13660
13661utils.inherits(SHA1, BlockHash);
13662module.exports = SHA1;
13663
13664SHA1.blockSize = 512;
13665SHA1.outSize = 160;
13666SHA1.hmacStrength = 80;
13667SHA1.padLength = 64;
13668
13669SHA1.prototype._update = function _update(msg, start) {
13670  var W = this.W;
13671
13672  for (var i = 0; i < 16; i++)
13673    W[i] = msg[start + i];
13674
13675  for(; i < W.length; i++)
13676    W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
13677
13678  var a = this.h[0];
13679  var b = this.h[1];
13680  var c = this.h[2];
13681  var d = this.h[3];
13682  var e = this.h[4];
13683
13684  for (i = 0; i < W.length; i++) {
13685    var s = ~~(i / 20);
13686    var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
13687    e = d;
13688    d = c;
13689    c = rotl32(b, 30);
13690    b = a;
13691    a = t;
13692  }
13693
13694  this.h[0] = sum32(this.h[0], a);
13695  this.h[1] = sum32(this.h[1], b);
13696  this.h[2] = sum32(this.h[2], c);
13697  this.h[3] = sum32(this.h[3], d);
13698  this.h[4] = sum32(this.h[4], e);
13699};
13700
13701SHA1.prototype._digest = function digest(enc) {
13702  if (enc === 'hex')
13703    return utils.toHex32(this.h, 'big');
13704  else
13705    return utils.split32(this.h, 'big');
13706};
13707
13708},{"../common":36,"../utils":46,"./common":45}],41:[function(require,module,exports){
13709'use strict';
13710
13711var utils = require('../utils');
13712var SHA256 = require('./256');
13713
13714function SHA224() {
13715  if (!(this instanceof SHA224))
13716    return new SHA224();
13717
13718  SHA256.call(this);
13719  this.h = [
13720    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
13721    0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
13722}
13723utils.inherits(SHA224, SHA256);
13724module.exports = SHA224;
13725
13726SHA224.blockSize = 512;
13727SHA224.outSize = 224;
13728SHA224.hmacStrength = 192;
13729SHA224.padLength = 64;
13730
13731SHA224.prototype._digest = function digest(enc) {
13732  // Just truncate output
13733  if (enc === 'hex')
13734    return utils.toHex32(this.h.slice(0, 7), 'big');
13735  else
13736    return utils.split32(this.h.slice(0, 7), 'big');
13737};
13738
13739
13740},{"../utils":46,"./256":42}],42:[function(require,module,exports){
13741'use strict';
13742
13743var utils = require('../utils');
13744var common = require('../common');
13745var shaCommon = require('./common');
13746var assert = require('minimalistic-assert');
13747
13748var sum32 = utils.sum32;
13749var sum32_4 = utils.sum32_4;
13750var sum32_5 = utils.sum32_5;
13751var ch32 = shaCommon.ch32;
13752var maj32 = shaCommon.maj32;
13753var s0_256 = shaCommon.s0_256;
13754var s1_256 = shaCommon.s1_256;
13755var g0_256 = shaCommon.g0_256;
13756var g1_256 = shaCommon.g1_256;
13757
13758var BlockHash = common.BlockHash;
13759
13760var sha256_K = [
13761  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
13762  0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
13763  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
13764  0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
13765  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
13766  0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
13767  0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
13768  0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
13769  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
13770  0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
13771  0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
13772  0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
13773  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
13774  0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
13775  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
13776  0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
13777];
13778
13779function SHA256() {
13780  if (!(this instanceof SHA256))
13781    return new SHA256();
13782
13783  BlockHash.call(this);
13784  this.h = [
13785    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
13786    0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
13787  ];
13788  this.k = sha256_K;
13789  this.W = new Array(64);
13790}
13791utils.inherits(SHA256, BlockHash);
13792module.exports = SHA256;
13793
13794SHA256.blockSize = 512;
13795SHA256.outSize = 256;
13796SHA256.hmacStrength = 192;
13797SHA256.padLength = 64;
13798
13799SHA256.prototype._update = function _update(msg, start) {
13800  var W = this.W;
13801
13802  for (var i = 0; i < 16; i++)
13803    W[i] = msg[start + i];
13804  for (; i < W.length; i++)
13805    W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
13806
13807  var a = this.h[0];
13808  var b = this.h[1];
13809  var c = this.h[2];
13810  var d = this.h[3];
13811  var e = this.h[4];
13812  var f = this.h[5];
13813  var g = this.h[6];
13814  var h = this.h[7];
13815
13816  assert(this.k.length === W.length);
13817  for (i = 0; i < W.length; i++) {
13818    var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
13819    var T2 = sum32(s0_256(a), maj32(a, b, c));
13820    h = g;
13821    g = f;
13822    f = e;
13823    e = sum32(d, T1);
13824    d = c;
13825    c = b;
13826    b = a;
13827    a = sum32(T1, T2);
13828  }
13829
13830  this.h[0] = sum32(this.h[0], a);
13831  this.h[1] = sum32(this.h[1], b);
13832  this.h[2] = sum32(this.h[2], c);
13833  this.h[3] = sum32(this.h[3], d);
13834  this.h[4] = sum32(this.h[4], e);
13835  this.h[5] = sum32(this.h[5], f);
13836  this.h[6] = sum32(this.h[6], g);
13837  this.h[7] = sum32(this.h[7], h);
13838};
13839
13840SHA256.prototype._digest = function digest(enc) {
13841  if (enc === 'hex')
13842    return utils.toHex32(this.h, 'big');
13843  else
13844    return utils.split32(this.h, 'big');
13845};
13846
13847},{"../common":36,"../utils":46,"./common":45,"minimalistic-assert":49}],43:[function(require,module,exports){
13848'use strict';
13849
13850var utils = require('../utils');
13851
13852var SHA512 = require('./512');
13853
13854function SHA384() {
13855  if (!(this instanceof SHA384))
13856    return new SHA384();
13857
13858  SHA512.call(this);
13859  this.h = [
13860    0xcbbb9d5d, 0xc1059ed8,
13861    0x629a292a, 0x367cd507,
13862    0x9159015a, 0x3070dd17,
13863    0x152fecd8, 0xf70e5939,
13864    0x67332667, 0xffc00b31,
13865    0x8eb44a87, 0x68581511,
13866    0xdb0c2e0d, 0x64f98fa7,
13867    0x47b5481d, 0xbefa4fa4 ];
13868}
13869utils.inherits(SHA384, SHA512);
13870module.exports = SHA384;
13871
13872SHA384.blockSize = 1024;
13873SHA384.outSize = 384;
13874SHA384.hmacStrength = 192;
13875SHA384.padLength = 128;
13876
13877SHA384.prototype._digest = function digest(enc) {
13878  if (enc === 'hex')
13879    return utils.toHex32(this.h.slice(0, 12), 'big');
13880  else
13881    return utils.split32(this.h.slice(0, 12), 'big');
13882};
13883
13884},{"../utils":46,"./512":44}],44:[function(require,module,exports){
13885'use strict';
13886
13887var utils = require('../utils');
13888var common = require('../common');
13889var assert = require('minimalistic-assert');
13890
13891var rotr64_hi = utils.rotr64_hi;
13892var rotr64_lo = utils.rotr64_lo;
13893var shr64_hi = utils.shr64_hi;
13894var shr64_lo = utils.shr64_lo;
13895var sum64 = utils.sum64;
13896var sum64_hi = utils.sum64_hi;
13897var sum64_lo = utils.sum64_lo;
13898var sum64_4_hi = utils.sum64_4_hi;
13899var sum64_4_lo = utils.sum64_4_lo;
13900var sum64_5_hi = utils.sum64_5_hi;
13901var sum64_5_lo = utils.sum64_5_lo;
13902
13903var BlockHash = common.BlockHash;
13904
13905var sha512_K = [
13906  0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
13907  0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
13908  0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
13909  0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
13910  0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
13911  0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
13912  0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
13913  0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
13914  0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
13915  0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
13916  0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
13917  0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
13918  0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
13919  0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
13920  0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
13921  0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
13922  0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
13923  0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
13924  0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
13925  0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
13926  0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
13927  0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
13928  0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
13929  0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
13930  0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
13931  0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
13932  0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
13933  0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
13934  0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
13935  0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
13936  0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
13937  0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
13938  0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
13939  0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
13940  0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
13941  0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
13942  0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
13943  0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
13944  0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
13945  0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
13946];
13947
13948function SHA512() {
13949  if (!(this instanceof SHA512))
13950    return new SHA512();
13951
13952  BlockHash.call(this);
13953  this.h = [
13954    0x6a09e667, 0xf3bcc908,
13955    0xbb67ae85, 0x84caa73b,
13956    0x3c6ef372, 0xfe94f82b,
13957    0xa54ff53a, 0x5f1d36f1,
13958    0x510e527f, 0xade682d1,
13959    0x9b05688c, 0x2b3e6c1f,
13960    0x1f83d9ab, 0xfb41bd6b,
13961    0x5be0cd19, 0x137e2179 ];
13962  this.k = sha512_K;
13963  this.W = new Array(160);
13964}
13965utils.inherits(SHA512, BlockHash);
13966module.exports = SHA512;
13967
13968SHA512.blockSize = 1024;
13969SHA512.outSize = 512;
13970SHA512.hmacStrength = 192;
13971SHA512.padLength = 128;
13972
13973SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
13974  var W = this.W;
13975
13976  // 32 x 32bit words
13977  for (var i = 0; i < 32; i++)
13978    W[i] = msg[start + i];
13979  for (; i < W.length; i += 2) {
13980    var c0_hi = g1_512_hi(W[i - 4], W[i - 3]);  // i - 2
13981    var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
13982    var c1_hi = W[i - 14];  // i - 7
13983    var c1_lo = W[i - 13];
13984    var c2_hi = g0_512_hi(W[i - 30], W[i - 29]);  // i - 15
13985    var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
13986    var c3_hi = W[i - 32];  // i - 16
13987    var c3_lo = W[i - 31];
13988
13989    W[i] = sum64_4_hi(
13990      c0_hi, c0_lo,
13991      c1_hi, c1_lo,
13992      c2_hi, c2_lo,
13993      c3_hi, c3_lo);
13994    W[i + 1] = sum64_4_lo(
13995      c0_hi, c0_lo,
13996      c1_hi, c1_lo,
13997      c2_hi, c2_lo,
13998      c3_hi, c3_lo);
13999  }
14000};
14001
14002SHA512.prototype._update = function _update(msg, start) {
14003  this._prepareBlock(msg, start);
14004
14005  var W = this.W;
14006
14007  var ah = this.h[0];
14008  var al = this.h[1];
14009  var bh = this.h[2];
14010  var bl = this.h[3];
14011  var ch = this.h[4];
14012  var cl = this.h[5];
14013  var dh = this.h[6];
14014  var dl = this.h[7];
14015  var eh = this.h[8];
14016  var el = this.h[9];
14017  var fh = this.h[10];
14018  var fl = this.h[11];
14019  var gh = this.h[12];
14020  var gl = this.h[13];
14021  var hh = this.h[14];
14022  var hl = this.h[15];
14023
14024  assert(this.k.length === W.length);
14025  for (var i = 0; i < W.length; i += 2) {
14026    var c0_hi = hh;
14027    var c0_lo = hl;
14028    var c1_hi = s1_512_hi(eh, el);
14029    var c1_lo = s1_512_lo(eh, el);
14030    var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
14031    var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
14032    var c3_hi = this.k[i];
14033    var c3_lo = this.k[i + 1];
14034    var c4_hi = W[i];
14035    var c4_lo = W[i + 1];
14036
14037    var T1_hi = sum64_5_hi(
14038      c0_hi, c0_lo,
14039      c1_hi, c1_lo,
14040      c2_hi, c2_lo,
14041      c3_hi, c3_lo,
14042      c4_hi, c4_lo);
14043    var T1_lo = sum64_5_lo(
14044      c0_hi, c0_lo,
14045      c1_hi, c1_lo,
14046      c2_hi, c2_lo,
14047      c3_hi, c3_lo,
14048      c4_hi, c4_lo);
14049
14050    c0_hi = s0_512_hi(ah, al);
14051    c0_lo = s0_512_lo(ah, al);
14052    c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
14053    c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
14054
14055    var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
14056    var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
14057
14058    hh = gh;
14059    hl = gl;
14060
14061    gh = fh;
14062    gl = fl;
14063
14064    fh = eh;
14065    fl = el;
14066
14067    eh = sum64_hi(dh, dl, T1_hi, T1_lo);
14068    el = sum64_lo(dl, dl, T1_hi, T1_lo);
14069
14070    dh = ch;
14071    dl = cl;
14072
14073    ch = bh;
14074    cl = bl;
14075
14076    bh = ah;
14077    bl = al;
14078
14079    ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
14080    al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
14081  }
14082
14083  sum64(this.h, 0, ah, al);
14084  sum64(this.h, 2, bh, bl);
14085  sum64(this.h, 4, ch, cl);
14086  sum64(this.h, 6, dh, dl);
14087  sum64(this.h, 8, eh, el);
14088  sum64(this.h, 10, fh, fl);
14089  sum64(this.h, 12, gh, gl);
14090  sum64(this.h, 14, hh, hl);
14091};
14092
14093SHA512.prototype._digest = function digest(enc) {
14094  if (enc === 'hex')
14095    return utils.toHex32(this.h, 'big');
14096  else
14097    return utils.split32(this.h, 'big');
14098};
14099
14100function ch64_hi(xh, xl, yh, yl, zh) {
14101  var r = (xh & yh) ^ ((~xh) & zh);
14102  if (r < 0)
14103    r += 0x100000000;
14104  return r;
14105}
14106
14107function ch64_lo(xh, xl, yh, yl, zh, zl) {
14108  var r = (xl & yl) ^ ((~xl) & zl);
14109  if (r < 0)
14110    r += 0x100000000;
14111  return r;
14112}
14113
14114function maj64_hi(xh, xl, yh, yl, zh) {
14115  var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
14116  if (r < 0)
14117    r += 0x100000000;
14118  return r;
14119}
14120
14121function maj64_lo(xh, xl, yh, yl, zh, zl) {
14122  var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
14123  if (r < 0)
14124    r += 0x100000000;
14125  return r;
14126}
14127
14128function s0_512_hi(xh, xl) {
14129  var c0_hi = rotr64_hi(xh, xl, 28);
14130  var c1_hi = rotr64_hi(xl, xh, 2);  // 34
14131  var c2_hi = rotr64_hi(xl, xh, 7);  // 39
14132
14133  var r = c0_hi ^ c1_hi ^ c2_hi;
14134  if (r < 0)
14135    r += 0x100000000;
14136  return r;
14137}
14138
14139function s0_512_lo(xh, xl) {
14140  var c0_lo = rotr64_lo(xh, xl, 28);
14141  var c1_lo = rotr64_lo(xl, xh, 2);  // 34
14142  var c2_lo = rotr64_lo(xl, xh, 7);  // 39
14143
14144  var r = c0_lo ^ c1_lo ^ c2_lo;
14145  if (r < 0)
14146    r += 0x100000000;
14147  return r;
14148}
14149
14150function s1_512_hi(xh, xl) {
14151  var c0_hi = rotr64_hi(xh, xl, 14);
14152  var c1_hi = rotr64_hi(xh, xl, 18);
14153  var c2_hi = rotr64_hi(xl, xh, 9);  // 41
14154
14155  var r = c0_hi ^ c1_hi ^ c2_hi;
14156  if (r < 0)
14157    r += 0x100000000;
14158  return r;
14159}
14160
14161function s1_512_lo(xh, xl) {
14162  var c0_lo = rotr64_lo(xh, xl, 14);
14163  var c1_lo = rotr64_lo(xh, xl, 18);
14164  var c2_lo = rotr64_lo(xl, xh, 9);  // 41
14165
14166  var r = c0_lo ^ c1_lo ^ c2_lo;
14167  if (r < 0)
14168    r += 0x100000000;
14169  return r;
14170}
14171
14172function g0_512_hi(xh, xl) {
14173  var c0_hi = rotr64_hi(xh, xl, 1);
14174  var c1_hi = rotr64_hi(xh, xl, 8);
14175  var c2_hi = shr64_hi(xh, xl, 7);
14176
14177  var r = c0_hi ^ c1_hi ^ c2_hi;
14178  if (r < 0)
14179    r += 0x100000000;
14180  return r;
14181}
14182
14183function g0_512_lo(xh, xl) {
14184  var c0_lo = rotr64_lo(xh, xl, 1);
14185  var c1_lo = rotr64_lo(xh, xl, 8);
14186  var c2_lo = shr64_lo(xh, xl, 7);
14187
14188  var r = c0_lo ^ c1_lo ^ c2_lo;
14189  if (r < 0)
14190    r += 0x100000000;
14191  return r;
14192}
14193
14194function g1_512_hi(xh, xl) {
14195  var c0_hi = rotr64_hi(xh, xl, 19);
14196  var c1_hi = rotr64_hi(xl, xh, 29);  // 61
14197  var c2_hi = shr64_hi(xh, xl, 6);
14198
14199  var r = c0_hi ^ c1_hi ^ c2_hi;
14200  if (r < 0)
14201    r += 0x100000000;
14202  return r;
14203}
14204
14205function g1_512_lo(xh, xl) {
14206  var c0_lo = rotr64_lo(xh, xl, 19);
14207  var c1_lo = rotr64_lo(xl, xh, 29);  // 61
14208  var c2_lo = shr64_lo(xh, xl, 6);
14209
14210  var r = c0_lo ^ c1_lo ^ c2_lo;
14211  if (r < 0)
14212    r += 0x100000000;
14213  return r;
14214}
14215
14216},{"../common":36,"../utils":46,"minimalistic-assert":49}],45:[function(require,module,exports){
14217'use strict';
14218
14219var utils = require('../utils');
14220var rotr32 = utils.rotr32;
14221
14222function ft_1(s, x, y, z) {
14223  if (s === 0)
14224    return ch32(x, y, z);
14225  if (s === 1 || s === 3)
14226    return p32(x, y, z);
14227  if (s === 2)
14228    return maj32(x, y, z);
14229}
14230exports.ft_1 = ft_1;
14231
14232function ch32(x, y, z) {
14233  return (x & y) ^ ((~x) & z);
14234}
14235exports.ch32 = ch32;
14236
14237function maj32(x, y, z) {
14238  return (x & y) ^ (x & z) ^ (y & z);
14239}
14240exports.maj32 = maj32;
14241
14242function p32(x, y, z) {
14243  return x ^ y ^ z;
14244}
14245exports.p32 = p32;
14246
14247function s0_256(x) {
14248  return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
14249}
14250exports.s0_256 = s0_256;
14251
14252function s1_256(x) {
14253  return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
14254}
14255exports.s1_256 = s1_256;
14256
14257function g0_256(x) {
14258  return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
14259}
14260exports.g0_256 = g0_256;
14261
14262function g1_256(x) {
14263  return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
14264}
14265exports.g1_256 = g1_256;
14266
14267},{"../utils":46}],46:[function(require,module,exports){
14268'use strict';
14269
14270var assert = require('minimalistic-assert');
14271var inherits = require('inherits');
14272
14273exports.inherits = inherits;
14274
14275function toArray(msg, enc) {
14276  if (Array.isArray(msg))
14277    return msg.slice();
14278  if (!msg)
14279    return [];
14280  var res = [];
14281  if (typeof msg === 'string') {
14282    if (!enc) {
14283      for (var i = 0; i < msg.length; i++) {
14284        var c = msg.charCodeAt(i);
14285        var hi = c >> 8;
14286        var lo = c & 0xff;
14287        if (hi)
14288          res.push(hi, lo);
14289        else
14290          res.push(lo);
14291      }
14292    } else if (enc === 'hex') {
14293      msg = msg.replace(/[^a-z0-9]+/ig, '');
14294      if (msg.length % 2 !== 0)
14295        msg = '0' + msg;
14296      for (i = 0; i < msg.length; i += 2)
14297        res.push(parseInt(msg[i] + msg[i + 1], 16));
14298    }
14299  } else {
14300    for (i = 0; i < msg.length; i++)
14301      res[i] = msg[i] | 0;
14302  }
14303  return res;
14304}
14305exports.toArray = toArray;
14306
14307function toHex(msg) {
14308  var res = '';
14309  for (var i = 0; i < msg.length; i++)
14310    res += zero2(msg[i].toString(16));
14311  return res;
14312}
14313exports.toHex = toHex;
14314
14315function htonl(w) {
14316  var res = (w >>> 24) |
14317            ((w >>> 8) & 0xff00) |
14318            ((w << 8) & 0xff0000) |
14319            ((w & 0xff) << 24);
14320  return res >>> 0;
14321}
14322exports.htonl = htonl;
14323
14324function toHex32(msg, endian) {
14325  var res = '';
14326  for (var i = 0; i < msg.length; i++) {
14327    var w = msg[i];
14328    if (endian === 'little')
14329      w = htonl(w);
14330    res += zero8(w.toString(16));
14331  }
14332  return res;
14333}
14334exports.toHex32 = toHex32;
14335
14336function zero2(word) {
14337  if (word.length === 1)
14338    return '0' + word;
14339  else
14340    return word;
14341}
14342exports.zero2 = zero2;
14343
14344function zero8(word) {
14345  if (word.length === 7)
14346    return '0' + word;
14347  else if (word.length === 6)
14348    return '00' + word;
14349  else if (word.length === 5)
14350    return '000' + word;
14351  else if (word.length === 4)
14352    return '0000' + word;
14353  else if (word.length === 3)
14354    return '00000' + word;
14355  else if (word.length === 2)
14356    return '000000' + word;
14357  else if (word.length === 1)
14358    return '0000000' + word;
14359  else
14360    return word;
14361}
14362exports.zero8 = zero8;
14363
14364function join32(msg, start, end, endian) {
14365  var len = end - start;
14366  assert(len % 4 === 0);
14367  var res = new Array(len / 4);
14368  for (var i = 0, k = start; i < res.length; i++, k += 4) {
14369    var w;
14370    if (endian === 'big')
14371      w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
14372    else
14373      w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
14374    res[i] = w >>> 0;
14375  }
14376  return res;
14377}
14378exports.join32 = join32;
14379
14380function split32(msg, endian) {
14381  var res = new Array(msg.length * 4);
14382  for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
14383    var m = msg[i];
14384    if (endian === 'big') {
14385      res[k] = m >>> 24;
14386      res[k + 1] = (m >>> 16) & 0xff;
14387      res[k + 2] = (m >>> 8) & 0xff;
14388      res[k + 3] = m & 0xff;
14389    } else {
14390      res[k + 3] = m >>> 24;
14391      res[k + 2] = (m >>> 16) & 0xff;
14392      res[k + 1] = (m >>> 8) & 0xff;
14393      res[k] = m & 0xff;
14394    }
14395  }
14396  return res;
14397}
14398exports.split32 = split32;
14399
14400function rotr32(w, b) {
14401  return (w >>> b) | (w << (32 - b));
14402}
14403exports.rotr32 = rotr32;
14404
14405function rotl32(w, b) {
14406  return (w << b) | (w >>> (32 - b));
14407}
14408exports.rotl32 = rotl32;
14409
14410function sum32(a, b) {
14411  return (a + b) >>> 0;
14412}
14413exports.sum32 = sum32;
14414
14415function sum32_3(a, b, c) {
14416  return (a + b + c) >>> 0;
14417}
14418exports.sum32_3 = sum32_3;
14419
14420function sum32_4(a, b, c, d) {
14421  return (a + b + c + d) >>> 0;
14422}
14423exports.sum32_4 = sum32_4;
14424
14425function sum32_5(a, b, c, d, e) {
14426  return (a + b + c + d + e) >>> 0;
14427}
14428exports.sum32_5 = sum32_5;
14429
14430function sum64(buf, pos, ah, al) {
14431  var bh = buf[pos];
14432  var bl = buf[pos + 1];
14433
14434  var lo = (al + bl) >>> 0;
14435  var hi = (lo < al ? 1 : 0) + ah + bh;
14436  buf[pos] = hi >>> 0;
14437  buf[pos + 1] = lo;
14438}
14439exports.sum64 = sum64;
14440
14441function sum64_hi(ah, al, bh, bl) {
14442  var lo = (al + bl) >>> 0;
14443  var hi = (lo < al ? 1 : 0) + ah + bh;
14444  return hi >>> 0;
14445}
14446exports.sum64_hi = sum64_hi;
14447
14448function sum64_lo(ah, al, bh, bl) {
14449  var lo = al + bl;
14450  return lo >>> 0;
14451}
14452exports.sum64_lo = sum64_lo;
14453
14454function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
14455  var carry = 0;
14456  var lo = al;
14457  lo = (lo + bl) >>> 0;
14458  carry += lo < al ? 1 : 0;
14459  lo = (lo + cl) >>> 0;
14460  carry += lo < cl ? 1 : 0;
14461  lo = (lo + dl) >>> 0;
14462  carry += lo < dl ? 1 : 0;
14463
14464  var hi = ah + bh + ch + dh + carry;
14465  return hi >>> 0;
14466}
14467exports.sum64_4_hi = sum64_4_hi;
14468
14469function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
14470  var lo = al + bl + cl + dl;
14471  return lo >>> 0;
14472}
14473exports.sum64_4_lo = sum64_4_lo;
14474
14475function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
14476  var carry = 0;
14477  var lo = al;
14478  lo = (lo + bl) >>> 0;
14479  carry += lo < al ? 1 : 0;
14480  lo = (lo + cl) >>> 0;
14481  carry += lo < cl ? 1 : 0;
14482  lo = (lo + dl) >>> 0;
14483  carry += lo < dl ? 1 : 0;
14484  lo = (lo + el) >>> 0;
14485  carry += lo < el ? 1 : 0;
14486
14487  var hi = ah + bh + ch + dh + eh + carry;
14488  return hi >>> 0;
14489}
14490exports.sum64_5_hi = sum64_5_hi;
14491
14492function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
14493  var lo = al + bl + cl + dl + el;
14494
14495  return lo >>> 0;
14496}
14497exports.sum64_5_lo = sum64_5_lo;
14498
14499function rotr64_hi(ah, al, num) {
14500  var r = (al << (32 - num)) | (ah >>> num);
14501  return r >>> 0;
14502}
14503exports.rotr64_hi = rotr64_hi;
14504
14505function rotr64_lo(ah, al, num) {
14506  var r = (ah << (32 - num)) | (al >>> num);
14507  return r >>> 0;
14508}
14509exports.rotr64_lo = rotr64_lo;
14510
14511function shr64_hi(ah, al, num) {
14512  return ah >>> num;
14513}
14514exports.shr64_hi = shr64_hi;
14515
14516function shr64_lo(ah, al, num) {
14517  var r = (ah << (32 - num)) | (al >>> num);
14518  return r >>> 0;
14519}
14520exports.shr64_lo = shr64_lo;
14521
14522},{"inherits":48,"minimalistic-assert":49}],47:[function(require,module,exports){
14523'use strict';
14524
14525var hash = require('hash.js');
14526var utils = require('minimalistic-crypto-utils');
14527var assert = require('minimalistic-assert');
14528
14529function HmacDRBG(options) {
14530  if (!(this instanceof HmacDRBG))
14531    return new HmacDRBG(options);
14532  this.hash = options.hash;
14533  this.predResist = !!options.predResist;
14534
14535  this.outLen = this.hash.outSize;
14536  this.minEntropy = options.minEntropy || this.hash.hmacStrength;
14537
14538  this._reseed = null;
14539  this.reseedInterval = null;
14540  this.K = null;
14541  this.V = null;
14542
14543  var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');
14544  var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');
14545  var pers = utils.toArray(options.pers, options.persEnc || 'hex');
14546  assert(entropy.length >= (this.minEntropy / 8),
14547         'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
14548  this._init(entropy, nonce, pers);
14549}
14550module.exports = HmacDRBG;
14551
14552HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
14553  var seed = entropy.concat(nonce).concat(pers);
14554
14555  this.K = new Array(this.outLen / 8);
14556  this.V = new Array(this.outLen / 8);
14557  for (var i = 0; i < this.V.length; i++) {
14558    this.K[i] = 0x00;
14559    this.V[i] = 0x01;
14560  }
14561
14562  this._update(seed);
14563  this._reseed = 1;
14564  this.reseedInterval = 0x1000000000000;  // 2^48
14565};
14566
14567HmacDRBG.prototype._hmac = function hmac() {
14568  return new hash.hmac(this.hash, this.K);
14569};
14570
14571HmacDRBG.prototype._update = function update(seed) {
14572  var kmac = this._hmac()
14573                 .update(this.V)
14574                 .update([ 0x00 ]);
14575  if (seed)
14576    kmac = kmac.update(seed);
14577  this.K = kmac.digest();
14578  this.V = this._hmac().update(this.V).digest();
14579  if (!seed)
14580    return;
14581
14582  this.K = this._hmac()
14583               .update(this.V)
14584               .update([ 0x01 ])
14585               .update(seed)
14586               .digest();
14587  this.V = this._hmac().update(this.V).digest();
14588};
14589
14590HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
14591  // Optional entropy enc
14592  if (typeof entropyEnc !== 'string') {
14593    addEnc = add;
14594    add = entropyEnc;
14595    entropyEnc = null;
14596  }
14597
14598  entropy = utils.toArray(entropy, entropyEnc);
14599  add = utils.toArray(add, addEnc);
14600
14601  assert(entropy.length >= (this.minEntropy / 8),
14602         'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
14603
14604  this._update(entropy.concat(add || []));
14605  this._reseed = 1;
14606};
14607
14608HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
14609  if (this._reseed > this.reseedInterval)
14610    throw new Error('Reseed is required');
14611
14612  // Optional encoding
14613  if (typeof enc !== 'string') {
14614    addEnc = add;
14615    add = enc;
14616    enc = null;
14617  }
14618
14619  // Optional additional data
14620  if (add) {
14621    add = utils.toArray(add, addEnc || 'hex');
14622    this._update(add);
14623  }
14624
14625  var temp = [];
14626  while (temp.length < len) {
14627    this.V = this._hmac().update(this.V).digest();
14628    temp = temp.concat(this.V);
14629  }
14630
14631  var res = temp.slice(0, len);
14632  this._update(add);
14633  this._reseed++;
14634  return utils.encode(res, enc);
14635};
14636
14637},{"hash.js":35,"minimalistic-assert":49,"minimalistic-crypto-utils":50}],48:[function(require,module,exports){
14638if (typeof Object.create === 'function') {
14639  // implementation from standard node.js 'util' module
14640  module.exports = function inherits(ctor, superCtor) {
14641    ctor.super_ = superCtor
14642    ctor.prototype = Object.create(superCtor.prototype, {
14643      constructor: {
14644        value: ctor,
14645        enumerable: false,
14646        writable: true,
14647        configurable: true
14648      }
14649    });
14650  };
14651} else {
14652  // old school shim for old browsers
14653  module.exports = function inherits(ctor, superCtor) {
14654    ctor.super_ = superCtor
14655    var TempCtor = function () {}
14656    TempCtor.prototype = superCtor.prototype
14657    ctor.prototype = new TempCtor()
14658    ctor.prototype.constructor = ctor
14659  }
14660}
14661
14662},{}],49:[function(require,module,exports){
14663module.exports = assert;
14664
14665function assert(val, msg) {
14666  if (!val)
14667    throw new Error(msg || 'Assertion failed');
14668}
14669
14670assert.equal = function assertEqual(l, r, msg) {
14671  if (l != r)
14672    throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
14673};
14674
14675},{}],50:[function(require,module,exports){
14676'use strict';
14677
14678var utils = exports;
14679
14680function toArray(msg, enc) {
14681  if (Array.isArray(msg))
14682    return msg.slice();
14683  if (!msg)
14684    return [];
14685  var res = [];
14686  if (typeof msg !== 'string') {
14687    for (var i = 0; i < msg.length; i++)
14688      res[i] = msg[i] | 0;
14689    return res;
14690  }
14691  if (enc === 'hex') {
14692    msg = msg.replace(/[^a-z0-9]+/ig, '');
14693    if (msg.length % 2 !== 0)
14694      msg = '0' + msg;
14695    for (var i = 0; i < msg.length; i += 2)
14696      res.push(parseInt(msg[i] + msg[i + 1], 16));
14697  } else {
14698    for (var i = 0; i < msg.length; i++) {
14699      var c = msg.charCodeAt(i);
14700      var hi = c >> 8;
14701      var lo = c & 0xff;
14702      if (hi)
14703        res.push(hi, lo);
14704      else
14705        res.push(lo);
14706    }
14707  }
14708  return res;
14709}
14710utils.toArray = toArray;
14711
14712function zero2(word) {
14713  if (word.length === 1)
14714    return '0' + word;
14715  else
14716    return word;
14717}
14718utils.zero2 = zero2;
14719
14720function toHex(msg) {
14721  var res = '';
14722  for (var i = 0; i < msg.length; i++)
14723    res += zero2(msg[i].toString(16));
14724  return res;
14725}
14726utils.toHex = toHex;
14727
14728utils.encode = function encode(arr, enc) {
14729  if (enc === 'hex')
14730    return toHex(arr);
14731  else
14732    return arr;
14733};
14734
14735},{}],51:[function(require,module,exports){
14736// Top level file is just a mixin of submodules & constants
14737'use strict';
14738
14739var assign    = require('./lib/utils/common').assign;
14740
14741var deflate   = require('./lib/deflate');
14742var inflate   = require('./lib/inflate');
14743var constants = require('./lib/zlib/constants');
14744
14745var pako = {};
14746
14747assign(pako, deflate, inflate, constants);
14748
14749module.exports = pako;
14750
14751},{"./lib/deflate":52,"./lib/inflate":53,"./lib/utils/common":54,"./lib/zlib/constants":57}],52:[function(require,module,exports){
14752'use strict';
14753
14754
14755var zlib_deflate = require('./zlib/deflate');
14756var utils        = require('./utils/common');
14757var strings      = require('./utils/strings');
14758var msg          = require('./zlib/messages');
14759var ZStream      = require('./zlib/zstream');
14760
14761var toString = Object.prototype.toString;
14762
14763/* Public constants ==========================================================*/
14764/* ===========================================================================*/
14765
14766var Z_NO_FLUSH      = 0;
14767var Z_FINISH        = 4;
14768
14769var Z_OK            = 0;
14770var Z_STREAM_END    = 1;
14771var Z_SYNC_FLUSH    = 2;
14772
14773var Z_DEFAULT_COMPRESSION = -1;
14774
14775var Z_DEFAULT_STRATEGY    = 0;
14776
14777var Z_DEFLATED  = 8;
14778
14779/* ===========================================================================*/
14780
14781
14782/**
14783 * class Deflate
14784 *
14785 * Generic JS-style wrapper for zlib calls. If you don't need
14786 * streaming behaviour - use more simple functions: [[deflate]],
14787 * [[deflateRaw]] and [[gzip]].
14788 **/
14789
14790/* internal
14791 * Deflate.chunks -> Array
14792 *
14793 * Chunks of output data, if [[Deflate#onData]] not overridden.
14794 **/
14795
14796/**
14797 * Deflate.result -> Uint8Array|Array
14798 *
14799 * Compressed result, generated by default [[Deflate#onData]]
14800 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
14801 * (call [[Deflate#push]] with `Z_FINISH` / `true` param)  or if you
14802 * push a chunk with explicit flush (call [[Deflate#push]] with
14803 * `Z_SYNC_FLUSH` param).
14804 **/
14805
14806/**
14807 * Deflate.err -> Number
14808 *
14809 * Error code after deflate finished. 0 (Z_OK) on success.
14810 * You will not need it in real life, because deflate errors
14811 * are possible only on wrong options or bad `onData` / `onEnd`
14812 * custom handlers.
14813 **/
14814
14815/**
14816 * Deflate.msg -> String
14817 *
14818 * Error message, if [[Deflate.err]] != 0
14819 **/
14820
14821
14822/**
14823 * new Deflate(options)
14824 * - options (Object): zlib deflate options.
14825 *
14826 * Creates new deflator instance with specified params. Throws exception
14827 * on bad params. Supported options:
14828 *
14829 * - `level`
14830 * - `windowBits`
14831 * - `memLevel`
14832 * - `strategy`
14833 * - `dictionary`
14834 *
14835 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
14836 * for more information on these.
14837 *
14838 * Additional options, for internal needs:
14839 *
14840 * - `chunkSize` - size of generated data chunks (16K by default)
14841 * - `raw` (Boolean) - do raw deflate
14842 * - `gzip` (Boolean) - create gzip wrapper
14843 * - `to` (String) - if equal to 'string', then result will be "binary string"
14844 *    (each char code [0..255])
14845 * - `header` (Object) - custom header for gzip
14846 *   - `text` (Boolean) - true if compressed data believed to be text
14847 *   - `time` (Number) - modification time, unix timestamp
14848 *   - `os` (Number) - operation system code
14849 *   - `extra` (Array) - array of bytes with extra data (max 65536)
14850 *   - `name` (String) - file name (binary string)
14851 *   - `comment` (String) - comment (binary string)
14852 *   - `hcrc` (Boolean) - true if header crc should be added
14853 *
14854 * ##### Example:
14855 *
14856 * ```javascript
14857 * var pako = require('pako')
14858 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
14859 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
14860 *
14861 * var deflate = new pako.Deflate({ level: 3});
14862 *
14863 * deflate.push(chunk1, false);
14864 * deflate.push(chunk2, true);  // true -> last chunk
14865 *
14866 * if (deflate.err) { throw new Error(deflate.err); }
14867 *
14868 * console.log(deflate.result);
14869 * ```
14870 **/
14871function Deflate(options) {
14872  if (!(this instanceof Deflate)) return new Deflate(options);
14873
14874  this.options = utils.assign({
14875    level: Z_DEFAULT_COMPRESSION,
14876    method: Z_DEFLATED,
14877    chunkSize: 16384,
14878    windowBits: 15,
14879    memLevel: 8,
14880    strategy: Z_DEFAULT_STRATEGY,
14881    to: ''
14882  }, options || {});
14883
14884  var opt = this.options;
14885
14886  if (opt.raw && (opt.windowBits > 0)) {
14887    opt.windowBits = -opt.windowBits;
14888  }
14889
14890  else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
14891    opt.windowBits += 16;
14892  }
14893
14894  this.err    = 0;      // error code, if happens (0 = Z_OK)
14895  this.msg    = '';     // error message
14896  this.ended  = false;  // used to avoid multiple onEnd() calls
14897  this.chunks = [];     // chunks of compressed data
14898
14899  this.strm = new ZStream();
14900  this.strm.avail_out = 0;
14901
14902  var status = zlib_deflate.deflateInit2(
14903    this.strm,
14904    opt.level,
14905    opt.method,
14906    opt.windowBits,
14907    opt.memLevel,
14908    opt.strategy
14909  );
14910
14911  if (status !== Z_OK) {
14912    throw new Error(msg[status]);
14913  }
14914
14915  if (opt.header) {
14916    zlib_deflate.deflateSetHeader(this.strm, opt.header);
14917  }
14918
14919  if (opt.dictionary) {
14920    var dict;
14921    // Convert data if needed
14922    if (typeof opt.dictionary === 'string') {
14923      // If we need to compress text, change encoding to utf8.
14924      dict = strings.string2buf(opt.dictionary);
14925    } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
14926      dict = new Uint8Array(opt.dictionary);
14927    } else {
14928      dict = opt.dictionary;
14929    }
14930
14931    status = zlib_deflate.deflateSetDictionary(this.strm, dict);
14932
14933    if (status !== Z_OK) {
14934      throw new Error(msg[status]);
14935    }
14936
14937    this._dict_set = true;
14938  }
14939}
14940
14941/**
14942 * Deflate#push(data[, mode]) -> Boolean
14943 * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
14944 *   converted to utf8 byte sequence.
14945 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
14946 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
14947 *
14948 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
14949 * new compressed chunks. Returns `true` on success. The last data block must have
14950 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
14951 * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
14952 * can use mode Z_SYNC_FLUSH, keeping the compression context.
14953 *
14954 * On fail call [[Deflate#onEnd]] with error code and return false.
14955 *
14956 * We strongly recommend to use `Uint8Array` on input for best speed (output
14957 * array format is detected automatically). Also, don't skip last param and always
14958 * use the same type in your code (boolean or number). That will improve JS speed.
14959 *
14960 * For regular `Array`-s make sure all elements are [0..255].
14961 *
14962 * ##### Example
14963 *
14964 * ```javascript
14965 * push(chunk, false); // push one of data chunks
14966 * ...
14967 * push(chunk, true);  // push last chunk
14968 * ```
14969 **/
14970Deflate.prototype.push = function (data, mode) {
14971  var strm = this.strm;
14972  var chunkSize = this.options.chunkSize;
14973  var status, _mode;
14974
14975  if (this.ended) { return false; }
14976
14977  _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
14978
14979  // Convert data if needed
14980  if (typeof data === 'string') {
14981    // If we need to compress text, change encoding to utf8.
14982    strm.input = strings.string2buf(data);
14983  } else if (toString.call(data) === '[object ArrayBuffer]') {
14984    strm.input = new Uint8Array(data);
14985  } else {
14986    strm.input = data;
14987  }
14988
14989  strm.next_in = 0;
14990  strm.avail_in = strm.input.length;
14991
14992  do {
14993    if (strm.avail_out === 0) {
14994      strm.output = new utils.Buf8(chunkSize);
14995      strm.next_out = 0;
14996      strm.avail_out = chunkSize;
14997    }
14998    status = zlib_deflate.deflate(strm, _mode);    /* no bad return value */
14999
15000    if (status !== Z_STREAM_END && status !== Z_OK) {
15001      this.onEnd(status);
15002      this.ended = true;
15003      return false;
15004    }
15005    if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
15006      if (this.options.to === 'string') {
15007        this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
15008      } else {
15009        this.onData(utils.shrinkBuf(strm.output, strm.next_out));
15010      }
15011    }
15012  } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
15013
15014  // Finalize on the last chunk.
15015  if (_mode === Z_FINISH) {
15016    status = zlib_deflate.deflateEnd(this.strm);
15017    this.onEnd(status);
15018    this.ended = true;
15019    return status === Z_OK;
15020  }
15021
15022  // callback interim results if Z_SYNC_FLUSH.
15023  if (_mode === Z_SYNC_FLUSH) {
15024    this.onEnd(Z_OK);
15025    strm.avail_out = 0;
15026    return true;
15027  }
15028
15029  return true;
15030};
15031
15032
15033/**
15034 * Deflate#onData(chunk) -> Void
15035 * - chunk (Uint8Array|Array|String): output data. Type of array depends
15036 *   on js engine support. When string output requested, each chunk
15037 *   will be string.
15038 *
15039 * By default, stores data blocks in `chunks[]` property and glue
15040 * those in `onEnd`. Override this handler, if you need another behaviour.
15041 **/
15042Deflate.prototype.onData = function (chunk) {
15043  this.chunks.push(chunk);
15044};
15045
15046
15047/**
15048 * Deflate#onEnd(status) -> Void
15049 * - status (Number): deflate status. 0 (Z_OK) on success,
15050 *   other if not.
15051 *
15052 * Called once after you tell deflate that the input stream is
15053 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
15054 * or if an error happened. By default - join collected chunks,
15055 * free memory and fill `results` / `err` properties.
15056 **/
15057Deflate.prototype.onEnd = function (status) {
15058  // On success - join
15059  if (status === Z_OK) {
15060    if (this.options.to === 'string') {
15061      this.result = this.chunks.join('');
15062    } else {
15063      this.result = utils.flattenChunks(this.chunks);
15064    }
15065  }
15066  this.chunks = [];
15067  this.err = status;
15068  this.msg = this.strm.msg;
15069};
15070
15071
15072/**
15073 * deflate(data[, options]) -> Uint8Array|Array|String
15074 * - data (Uint8Array|Array|String): input data to compress.
15075 * - options (Object): zlib deflate options.
15076 *
15077 * Compress `data` with deflate algorithm and `options`.
15078 *
15079 * Supported options are:
15080 *
15081 * - level
15082 * - windowBits
15083 * - memLevel
15084 * - strategy
15085 * - dictionary
15086 *
15087 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
15088 * for more information on these.
15089 *
15090 * Sugar (options):
15091 *
15092 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
15093 *   negative windowBits implicitly.
15094 * - `to` (String) - if equal to 'string', then result will be "binary string"
15095 *    (each char code [0..255])
15096 *
15097 * ##### Example:
15098 *
15099 * ```javascript
15100 * var pako = require('pako')
15101 *   , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
15102 *
15103 * console.log(pako.deflate(data));
15104 * ```
15105 **/
15106function deflate(input, options) {
15107  var deflator = new Deflate(options);
15108
15109  deflator.push(input, true);
15110
15111  // That will never happens, if you don't cheat with options :)
15112  if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
15113
15114  return deflator.result;
15115}
15116
15117
15118/**
15119 * deflateRaw(data[, options]) -> Uint8Array|Array|String
15120 * - data (Uint8Array|Array|String): input data to compress.
15121 * - options (Object): zlib deflate options.
15122 *
15123 * The same as [[deflate]], but creates raw data, without wrapper
15124 * (header and adler32 crc).
15125 **/
15126function deflateRaw(input, options) {
15127  options = options || {};
15128  options.raw = true;
15129  return deflate(input, options);
15130}
15131
15132
15133/**
15134 * gzip(data[, options]) -> Uint8Array|Array|String
15135 * - data (Uint8Array|Array|String): input data to compress.
15136 * - options (Object): zlib deflate options.
15137 *
15138 * The same as [[deflate]], but create gzip wrapper instead of
15139 * deflate one.
15140 **/
15141function gzip(input, options) {
15142  options = options || {};
15143  options.gzip = true;
15144  return deflate(input, options);
15145}
15146
15147
15148exports.Deflate = Deflate;
15149exports.deflate = deflate;
15150exports.deflateRaw = deflateRaw;
15151exports.gzip = gzip;
15152
15153},{"./utils/common":54,"./utils/strings":55,"./zlib/deflate":59,"./zlib/messages":64,"./zlib/zstream":66}],53:[function(require,module,exports){
15154'use strict';
15155
15156
15157var zlib_inflate = require('./zlib/inflate');
15158var utils        = require('./utils/common');
15159var strings      = require('./utils/strings');
15160var c            = require('./zlib/constants');
15161var msg          = require('./zlib/messages');
15162var ZStream      = require('./zlib/zstream');
15163var GZheader     = require('./zlib/gzheader');
15164
15165var toString = Object.prototype.toString;
15166
15167/**
15168 * class Inflate
15169 *
15170 * Generic JS-style wrapper for zlib calls. If you don't need
15171 * streaming behaviour - use more simple functions: [[inflate]]
15172 * and [[inflateRaw]].
15173 **/
15174
15175/* internal
15176 * inflate.chunks -> Array
15177 *
15178 * Chunks of output data, if [[Inflate#onData]] not overridden.
15179 **/
15180
15181/**
15182 * Inflate.result -> Uint8Array|Array|String
15183 *
15184 * Uncompressed result, generated by default [[Inflate#onData]]
15185 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
15186 * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
15187 * push a chunk with explicit flush (call [[Inflate#push]] with
15188 * `Z_SYNC_FLUSH` param).
15189 **/
15190
15191/**
15192 * Inflate.err -> Number
15193 *
15194 * Error code after inflate finished. 0 (Z_OK) on success.
15195 * Should be checked if broken data possible.
15196 **/
15197
15198/**
15199 * Inflate.msg -> String
15200 *
15201 * Error message, if [[Inflate.err]] != 0
15202 **/
15203
15204
15205/**
15206 * new Inflate(options)
15207 * - options (Object): zlib inflate options.
15208 *
15209 * Creates new inflator instance with specified params. Throws exception
15210 * on bad params. Supported options:
15211 *
15212 * - `windowBits`
15213 * - `dictionary`
15214 *
15215 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
15216 * for more information on these.
15217 *
15218 * Additional options, for internal needs:
15219 *
15220 * - `chunkSize` - size of generated data chunks (16K by default)
15221 * - `raw` (Boolean) - do raw inflate
15222 * - `to` (String) - if equal to 'string', then result will be converted
15223 *   from utf8 to utf16 (javascript) string. When string output requested,
15224 *   chunk length can differ from `chunkSize`, depending on content.
15225 *
15226 * By default, when no options set, autodetect deflate/gzip data format via
15227 * wrapper header.
15228 *
15229 * ##### Example:
15230 *
15231 * ```javascript
15232 * var pako = require('pako')
15233 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
15234 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
15235 *
15236 * var inflate = new pako.Inflate({ level: 3});
15237 *
15238 * inflate.push(chunk1, false);
15239 * inflate.push(chunk2, true);  // true -> last chunk
15240 *
15241 * if (inflate.err) { throw new Error(inflate.err); }
15242 *
15243 * console.log(inflate.result);
15244 * ```
15245 **/
15246function Inflate(options) {
15247  if (!(this instanceof Inflate)) return new Inflate(options);
15248
15249  this.options = utils.assign({
15250    chunkSize: 16384,
15251    windowBits: 0,
15252    to: ''
15253  }, options || {});
15254
15255  var opt = this.options;
15256
15257  // Force window size for `raw` data, if not set directly,
15258  // because we have no header for autodetect.
15259  if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
15260    opt.windowBits = -opt.windowBits;
15261    if (opt.windowBits === 0) { opt.windowBits = -15; }
15262  }
15263
15264  // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
15265  if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
15266      !(options && options.windowBits)) {
15267    opt.windowBits += 32;
15268  }
15269
15270  // Gzip header has no info about windows size, we can do autodetect only
15271  // for deflate. So, if window size not set, force it to max when gzip possible
15272  if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
15273    // bit 3 (16) -> gzipped data
15274    // bit 4 (32) -> autodetect gzip/deflate
15275    if ((opt.windowBits & 15) === 0) {
15276      opt.windowBits |= 15;
15277    }
15278  }
15279
15280  this.err    = 0;      // error code, if happens (0 = Z_OK)
15281  this.msg    = '';     // error message
15282  this.ended  = false;  // used to avoid multiple onEnd() calls
15283  this.chunks = [];     // chunks of compressed data
15284
15285  this.strm   = new ZStream();
15286  this.strm.avail_out = 0;
15287
15288  var status  = zlib_inflate.inflateInit2(
15289    this.strm,
15290    opt.windowBits
15291  );
15292
15293  if (status !== c.Z_OK) {
15294    throw new Error(msg[status]);
15295  }
15296
15297  this.header = new GZheader();
15298
15299  zlib_inflate.inflateGetHeader(this.strm, this.header);
15300}
15301
15302/**
15303 * Inflate#push(data[, mode]) -> Boolean
15304 * - data (Uint8Array|Array|ArrayBuffer|String): input data
15305 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
15306 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
15307 *
15308 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
15309 * new output chunks. Returns `true` on success. The last data block must have
15310 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
15311 * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
15312 * can use mode Z_SYNC_FLUSH, keeping the decompression context.
15313 *
15314 * On fail call [[Inflate#onEnd]] with error code and return false.
15315 *
15316 * We strongly recommend to use `Uint8Array` on input for best speed (output
15317 * format is detected automatically). Also, don't skip last param and always
15318 * use the same type in your code (boolean or number). That will improve JS speed.
15319 *
15320 * For regular `Array`-s make sure all elements are [0..255].
15321 *
15322 * ##### Example
15323 *
15324 * ```javascript
15325 * push(chunk, false); // push one of data chunks
15326 * ...
15327 * push(chunk, true);  // push last chunk
15328 * ```
15329 **/
15330Inflate.prototype.push = function (data, mode) {
15331  var strm = this.strm;
15332  var chunkSize = this.options.chunkSize;
15333  var dictionary = this.options.dictionary;
15334  var status, _mode;
15335  var next_out_utf8, tail, utf8str;
15336  var dict;
15337
15338  // Flag to properly process Z_BUF_ERROR on testing inflate call
15339  // when we check that all output data was flushed.
15340  var allowBufError = false;
15341
15342  if (this.ended) { return false; }
15343  _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
15344
15345  // Convert data if needed
15346  if (typeof data === 'string') {
15347    // Only binary strings can be decompressed on practice
15348    strm.input = strings.binstring2buf(data);
15349  } else if (toString.call(data) === '[object ArrayBuffer]') {
15350    strm.input = new Uint8Array(data);
15351  } else {
15352    strm.input = data;
15353  }
15354
15355  strm.next_in = 0;
15356  strm.avail_in = strm.input.length;
15357
15358  do {
15359    if (strm.avail_out === 0) {
15360      strm.output = new utils.Buf8(chunkSize);
15361      strm.next_out = 0;
15362      strm.avail_out = chunkSize;
15363    }
15364
15365    status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH);    /* no bad return value */
15366
15367    if (status === c.Z_NEED_DICT && dictionary) {
15368      // Convert data if needed
15369      if (typeof dictionary === 'string') {
15370        dict = strings.string2buf(dictionary);
15371      } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
15372        dict = new Uint8Array(dictionary);
15373      } else {
15374        dict = dictionary;
15375      }
15376
15377      status = zlib_inflate.inflateSetDictionary(this.strm, dict);
15378
15379    }
15380
15381    if (status === c.Z_BUF_ERROR && allowBufError === true) {
15382      status = c.Z_OK;
15383      allowBufError = false;
15384    }
15385
15386    if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
15387      this.onEnd(status);
15388      this.ended = true;
15389      return false;
15390    }
15391
15392    if (strm.next_out) {
15393      if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
15394
15395        if (this.options.to === 'string') {
15396
15397          next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
15398
15399          tail = strm.next_out - next_out_utf8;
15400          utf8str = strings.buf2string(strm.output, next_out_utf8);
15401
15402          // move tail
15403          strm.next_out = tail;
15404          strm.avail_out = chunkSize - tail;
15405          if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
15406
15407          this.onData(utf8str);
15408
15409        } else {
15410          this.onData(utils.shrinkBuf(strm.output, strm.next_out));
15411        }
15412      }
15413    }
15414
15415    // When no more input data, we should check that internal inflate buffers
15416    // are flushed. The only way to do it when avail_out = 0 - run one more
15417    // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
15418    // Here we set flag to process this error properly.
15419    //
15420    // NOTE. Deflate does not return error in this case and does not needs such
15421    // logic.
15422    if (strm.avail_in === 0 && strm.avail_out === 0) {
15423      allowBufError = true;
15424    }
15425
15426  } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
15427
15428  if (status === c.Z_STREAM_END) {
15429    _mode = c.Z_FINISH;
15430  }
15431
15432  // Finalize on the last chunk.
15433  if (_mode === c.Z_FINISH) {
15434    status = zlib_inflate.inflateEnd(this.strm);
15435    this.onEnd(status);
15436    this.ended = true;
15437    return status === c.Z_OK;
15438  }
15439
15440  // callback interim results if Z_SYNC_FLUSH.
15441  if (_mode === c.Z_SYNC_FLUSH) {
15442    this.onEnd(c.Z_OK);
15443    strm.avail_out = 0;
15444    return true;
15445  }
15446
15447  return true;
15448};
15449
15450
15451/**
15452 * Inflate#onData(chunk) -> Void
15453 * - chunk (Uint8Array|Array|String): output data. Type of array depends
15454 *   on js engine support. When string output requested, each chunk
15455 *   will be string.
15456 *
15457 * By default, stores data blocks in `chunks[]` property and glue
15458 * those in `onEnd`. Override this handler, if you need another behaviour.
15459 **/
15460Inflate.prototype.onData = function (chunk) {
15461  this.chunks.push(chunk);
15462};
15463
15464
15465/**
15466 * Inflate#onEnd(status) -> Void
15467 * - status (Number): inflate status. 0 (Z_OK) on success,
15468 *   other if not.
15469 *
15470 * Called either after you tell inflate that the input stream is
15471 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
15472 * or if an error happened. By default - join collected chunks,
15473 * free memory and fill `results` / `err` properties.
15474 **/
15475Inflate.prototype.onEnd = function (status) {
15476  // On success - join
15477  if (status === c.Z_OK) {
15478    if (this.options.to === 'string') {
15479      // Glue & convert here, until we teach pako to send
15480      // utf8 aligned strings to onData
15481      this.result = this.chunks.join('');
15482    } else {
15483      this.result = utils.flattenChunks(this.chunks);
15484    }
15485  }
15486  this.chunks = [];
15487  this.err = status;
15488  this.msg = this.strm.msg;
15489};
15490
15491
15492/**
15493 * inflate(data[, options]) -> Uint8Array|Array|String
15494 * - data (Uint8Array|Array|String): input data to decompress.
15495 * - options (Object): zlib inflate options.
15496 *
15497 * Decompress `data` with inflate/ungzip and `options`. Autodetect
15498 * format via wrapper header by default. That's why we don't provide
15499 * separate `ungzip` method.
15500 *
15501 * Supported options are:
15502 *
15503 * - windowBits
15504 *
15505 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
15506 * for more information.
15507 *
15508 * Sugar (options):
15509 *
15510 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
15511 *   negative windowBits implicitly.
15512 * - `to` (String) - if equal to 'string', then result will be converted
15513 *   from utf8 to utf16 (javascript) string. When string output requested,
15514 *   chunk length can differ from `chunkSize`, depending on content.
15515 *
15516 *
15517 * ##### Example:
15518 *
15519 * ```javascript
15520 * var pako = require('pako')
15521 *   , input = pako.deflate([1,2,3,4,5,6,7,8,9])
15522 *   , output;
15523 *
15524 * try {
15525 *   output = pako.inflate(input);
15526 * } catch (err)
15527 *   console.log(err);
15528 * }
15529 * ```
15530 **/
15531function inflate(input, options) {
15532  var inflator = new Inflate(options);
15533
15534  inflator.push(input, true);
15535
15536  // That will never happens, if you don't cheat with options :)
15537  if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
15538
15539  return inflator.result;
15540}
15541
15542
15543/**
15544 * inflateRaw(data[, options]) -> Uint8Array|Array|String
15545 * - data (Uint8Array|Array|String): input data to decompress.
15546 * - options (Object): zlib inflate options.
15547 *
15548 * The same as [[inflate]], but creates raw data, without wrapper
15549 * (header and adler32 crc).
15550 **/
15551function inflateRaw(input, options) {
15552  options = options || {};
15553  options.raw = true;
15554  return inflate(input, options);
15555}
15556
15557
15558/**
15559 * ungzip(data[, options]) -> Uint8Array|Array|String
15560 * - data (Uint8Array|Array|String): input data to decompress.
15561 * - options (Object): zlib inflate options.
15562 *
15563 * Just shortcut to [[inflate]], because it autodetects format
15564 * by header.content. Done for convenience.
15565 **/
15566
15567
15568exports.Inflate = Inflate;
15569exports.inflate = inflate;
15570exports.inflateRaw = inflateRaw;
15571exports.ungzip  = inflate;
15572
15573},{"./utils/common":54,"./utils/strings":55,"./zlib/constants":57,"./zlib/gzheader":60,"./zlib/inflate":62,"./zlib/messages":64,"./zlib/zstream":66}],54:[function(require,module,exports){
15574'use strict';
15575
15576
15577var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
15578                (typeof Uint16Array !== 'undefined') &&
15579                (typeof Int32Array !== 'undefined');
15580
15581function _has(obj, key) {
15582  return Object.prototype.hasOwnProperty.call(obj, key);
15583}
15584
15585exports.assign = function (obj /*from1, from2, from3, ...*/) {
15586  var sources = Array.prototype.slice.call(arguments, 1);
15587  while (sources.length) {
15588    var source = sources.shift();
15589    if (!source) { continue; }
15590
15591    if (typeof source !== 'object') {
15592      throw new TypeError(source + 'must be non-object');
15593    }
15594
15595    for (var p in source) {
15596      if (_has(source, p)) {
15597        obj[p] = source[p];
15598      }
15599    }
15600  }
15601
15602  return obj;
15603};
15604
15605
15606// reduce buffer size, avoiding mem copy
15607exports.shrinkBuf = function (buf, size) {
15608  if (buf.length === size) { return buf; }
15609  if (buf.subarray) { return buf.subarray(0, size); }
15610  buf.length = size;
15611  return buf;
15612};
15613
15614
15615var fnTyped = {
15616  arraySet: function (dest, src, src_offs, len, dest_offs) {
15617    if (src.subarray && dest.subarray) {
15618      dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
15619      return;
15620    }
15621    // Fallback to ordinary array
15622    for (var i = 0; i < len; i++) {
15623      dest[dest_offs + i] = src[src_offs + i];
15624    }
15625  },
15626  // Join array of chunks to single array.
15627  flattenChunks: function (chunks) {
15628    var i, l, len, pos, chunk, result;
15629
15630    // calculate data length
15631    len = 0;
15632    for (i = 0, l = chunks.length; i < l; i++) {
15633      len += chunks[i].length;
15634    }
15635
15636    // join chunks
15637    result = new Uint8Array(len);
15638    pos = 0;
15639    for (i = 0, l = chunks.length; i < l; i++) {
15640      chunk = chunks[i];
15641      result.set(chunk, pos);
15642      pos += chunk.length;
15643    }
15644
15645    return result;
15646  }
15647};
15648
15649var fnUntyped = {
15650  arraySet: function (dest, src, src_offs, len, dest_offs) {
15651    for (var i = 0; i < len; i++) {
15652      dest[dest_offs + i] = src[src_offs + i];
15653    }
15654  },
15655  // Join array of chunks to single array.
15656  flattenChunks: function (chunks) {
15657    return [].concat.apply([], chunks);
15658  }
15659};
15660
15661
15662// Enable/Disable typed arrays use, for testing
15663//
15664exports.setTyped = function (on) {
15665  if (on) {
15666    exports.Buf8  = Uint8Array;
15667    exports.Buf16 = Uint16Array;
15668    exports.Buf32 = Int32Array;
15669    exports.assign(exports, fnTyped);
15670  } else {
15671    exports.Buf8  = Array;
15672    exports.Buf16 = Array;
15673    exports.Buf32 = Array;
15674    exports.assign(exports, fnUntyped);
15675  }
15676};
15677
15678exports.setTyped(TYPED_OK);
15679
15680},{}],55:[function(require,module,exports){
15681// String encode/decode helpers
15682'use strict';
15683
15684
15685var utils = require('./common');
15686
15687
15688// Quick check if we can use fast array to bin string conversion
15689//
15690// - apply(Array) can fail on Android 2.2
15691// - apply(Uint8Array) can fail on iOS 5.1 Safari
15692//
15693var STR_APPLY_OK = true;
15694var STR_APPLY_UIA_OK = true;
15695
15696try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
15697try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
15698
15699
15700// Table with utf8 lengths (calculated by first byte of sequence)
15701// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
15702// because max possible codepoint is 0x10ffff
15703var _utf8len = new utils.Buf8(256);
15704for (var q = 0; q < 256; q++) {
15705  _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
15706}
15707_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
15708
15709
15710// convert string to array (typed, when possible)
15711exports.string2buf = function (str) {
15712  var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
15713
15714  // count binary size
15715  for (m_pos = 0; m_pos < str_len; m_pos++) {
15716    c = str.charCodeAt(m_pos);
15717    if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
15718      c2 = str.charCodeAt(m_pos + 1);
15719      if ((c2 & 0xfc00) === 0xdc00) {
15720        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
15721        m_pos++;
15722      }
15723    }
15724    buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
15725  }
15726
15727  // allocate buffer
15728  buf = new utils.Buf8(buf_len);
15729
15730  // convert
15731  for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
15732    c = str.charCodeAt(m_pos);
15733    if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
15734      c2 = str.charCodeAt(m_pos + 1);
15735      if ((c2 & 0xfc00) === 0xdc00) {
15736        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
15737        m_pos++;
15738      }
15739    }
15740    if (c < 0x80) {
15741      /* one byte */
15742      buf[i++] = c;
15743    } else if (c < 0x800) {
15744      /* two bytes */
15745      buf[i++] = 0xC0 | (c >>> 6);
15746      buf[i++] = 0x80 | (c & 0x3f);
15747    } else if (c < 0x10000) {
15748      /* three bytes */
15749      buf[i++] = 0xE0 | (c >>> 12);
15750      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
15751      buf[i++] = 0x80 | (c & 0x3f);
15752    } else {
15753      /* four bytes */
15754      buf[i++] = 0xf0 | (c >>> 18);
15755      buf[i++] = 0x80 | (c >>> 12 & 0x3f);
15756      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
15757      buf[i++] = 0x80 | (c & 0x3f);
15758    }
15759  }
15760
15761  return buf;
15762};
15763
15764// Helper (used in 2 places)
15765function buf2binstring(buf, len) {
15766  // use fallback for big arrays to avoid stack overflow
15767  if (len < 65537) {
15768    if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
15769      return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
15770    }
15771  }
15772
15773  var result = '';
15774  for (var i = 0; i < len; i++) {
15775    result += String.fromCharCode(buf[i]);
15776  }
15777  return result;
15778}
15779
15780
15781// Convert byte array to binary string
15782exports.buf2binstring = function (buf) {
15783  return buf2binstring(buf, buf.length);
15784};
15785
15786
15787// Convert binary string (typed, when possible)
15788exports.binstring2buf = function (str) {
15789  var buf = new utils.Buf8(str.length);
15790  for (var i = 0, len = buf.length; i < len; i++) {
15791    buf[i] = str.charCodeAt(i);
15792  }
15793  return buf;
15794};
15795
15796
15797// convert array to string
15798exports.buf2string = function (buf, max) {
15799  var i, out, c, c_len;
15800  var len = max || buf.length;
15801
15802  // Reserve max possible length (2 words per char)
15803  // NB: by unknown reasons, Array is significantly faster for
15804  //     String.fromCharCode.apply than Uint16Array.
15805  var utf16buf = new Array(len * 2);
15806
15807  for (out = 0, i = 0; i < len;) {
15808    c = buf[i++];
15809    // quick process ascii
15810    if (c < 0x80) { utf16buf[out++] = c; continue; }
15811
15812    c_len = _utf8len[c];
15813    // skip 5 & 6 byte codes
15814    if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
15815
15816    // apply mask on first byte
15817    c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
15818    // join the rest
15819    while (c_len > 1 && i < len) {
15820      c = (c << 6) | (buf[i++] & 0x3f);
15821      c_len--;
15822    }
15823
15824    // terminated by end of string?
15825    if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
15826
15827    if (c < 0x10000) {
15828      utf16buf[out++] = c;
15829    } else {
15830      c -= 0x10000;
15831      utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
15832      utf16buf[out++] = 0xdc00 | (c & 0x3ff);
15833    }
15834  }
15835
15836  return buf2binstring(utf16buf, out);
15837};
15838
15839
15840// Calculate max possible position in utf8 buffer,
15841// that will not break sequence. If that's not possible
15842// - (very small limits) return max size as is.
15843//
15844// buf[] - utf8 bytes array
15845// max   - length limit (mandatory);
15846exports.utf8border = function (buf, max) {
15847  var pos;
15848
15849  max = max || buf.length;
15850  if (max > buf.length) { max = buf.length; }
15851
15852  // go back from last position, until start of sequence found
15853  pos = max - 1;
15854  while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
15855
15856  // Very small and broken sequence,
15857  // return max, because we should return something anyway.
15858  if (pos < 0) { return max; }
15859
15860  // If we came to start of buffer - that means buffer is too small,
15861  // return max too.
15862  if (pos === 0) { return max; }
15863
15864  return (pos + _utf8len[buf[pos]] > max) ? pos : max;
15865};
15866
15867},{"./common":54}],56:[function(require,module,exports){
15868'use strict';
15869
15870// Note: adler32 takes 12% for level 0 and 2% for level 6.
15871// It isn't worth it to make additional optimizations as in original.
15872// Small size is preferable.
15873
15874// (C) 1995-2013 Jean-loup Gailly and Mark Adler
15875// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
15876//
15877// This software is provided 'as-is', without any express or implied
15878// warranty. In no event will the authors be held liable for any damages
15879// arising from the use of this software.
15880//
15881// Permission is granted to anyone to use this software for any purpose,
15882// including commercial applications, and to alter it and redistribute it
15883// freely, subject to the following restrictions:
15884//
15885// 1. The origin of this software must not be misrepresented; you must not
15886//   claim that you wrote the original software. If you use this software
15887//   in a product, an acknowledgment in the product documentation would be
15888//   appreciated but is not required.
15889// 2. Altered source versions must be plainly marked as such, and must not be
15890//   misrepresented as being the original software.
15891// 3. This notice may not be removed or altered from any source distribution.
15892
15893function adler32(adler, buf, len, pos) {
15894  var s1 = (adler & 0xffff) |0,
15895      s2 = ((adler >>> 16) & 0xffff) |0,
15896      n = 0;
15897
15898  while (len !== 0) {
15899    // Set limit ~ twice less than 5552, to keep
15900    // s2 in 31-bits, because we force signed ints.
15901    // in other case %= will fail.
15902    n = len > 2000 ? 2000 : len;
15903    len -= n;
15904
15905    do {
15906      s1 = (s1 + buf[pos++]) |0;
15907      s2 = (s2 + s1) |0;
15908    } while (--n);
15909
15910    s1 %= 65521;
15911    s2 %= 65521;
15912  }
15913
15914  return (s1 | (s2 << 16)) |0;
15915}
15916
15917
15918module.exports = adler32;
15919
15920},{}],57:[function(require,module,exports){
15921'use strict';
15922
15923// (C) 1995-2013 Jean-loup Gailly and Mark Adler
15924// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
15925//
15926// This software is provided 'as-is', without any express or implied
15927// warranty. In no event will the authors be held liable for any damages
15928// arising from the use of this software.
15929//
15930// Permission is granted to anyone to use this software for any purpose,
15931// including commercial applications, and to alter it and redistribute it
15932// freely, subject to the following restrictions:
15933//
15934// 1. The origin of this software must not be misrepresented; you must not
15935//   claim that you wrote the original software. If you use this software
15936//   in a product, an acknowledgment in the product documentation would be
15937//   appreciated but is not required.
15938// 2. Altered source versions must be plainly marked as such, and must not be
15939//   misrepresented as being the original software.
15940// 3. This notice may not be removed or altered from any source distribution.
15941
15942module.exports = {
15943
15944  /* Allowed flush values; see deflate() and inflate() below for details */
15945  Z_NO_FLUSH:         0,
15946  Z_PARTIAL_FLUSH:    1,
15947  Z_SYNC_FLUSH:       2,
15948  Z_FULL_FLUSH:       3,
15949  Z_FINISH:           4,
15950  Z_BLOCK:            5,
15951  Z_TREES:            6,
15952
15953  /* Return codes for the compression/decompression functions. Negative values
15954  * are errors, positive values are used for special but normal events.
15955  */
15956  Z_OK:               0,
15957  Z_STREAM_END:       1,
15958  Z_NEED_DICT:        2,
15959  Z_ERRNO:           -1,
15960  Z_STREAM_ERROR:    -2,
15961  Z_DATA_ERROR:      -3,
15962  //Z_MEM_ERROR:     -4,
15963  Z_BUF_ERROR:       -5,
15964  //Z_VERSION_ERROR: -6,
15965
15966  /* compression levels */
15967  Z_NO_COMPRESSION:         0,
15968  Z_BEST_SPEED:             1,
15969  Z_BEST_COMPRESSION:       9,
15970  Z_DEFAULT_COMPRESSION:   -1,
15971
15972
15973  Z_FILTERED:               1,
15974  Z_HUFFMAN_ONLY:           2,
15975  Z_RLE:                    3,
15976  Z_FIXED:                  4,
15977  Z_DEFAULT_STRATEGY:       0,
15978
15979  /* Possible values of the data_type field (though see inflate()) */
15980  Z_BINARY:                 0,
15981  Z_TEXT:                   1,
15982  //Z_ASCII:                1, // = Z_TEXT (deprecated)
15983  Z_UNKNOWN:                2,
15984
15985  /* The deflate compression method */
15986  Z_DEFLATED:               8
15987  //Z_NULL:                 null // Use -1 or null inline, depending on var type
15988};
15989
15990},{}],58:[function(require,module,exports){
15991'use strict';
15992
15993// Note: we can't get significant speed boost here.
15994// So write code to minimize size - no pregenerated tables
15995// and array tools dependencies.
15996
15997// (C) 1995-2013 Jean-loup Gailly and Mark Adler
15998// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
15999//
16000// This software is provided 'as-is', without any express or implied
16001// warranty. In no event will the authors be held liable for any damages
16002// arising from the use of this software.
16003//
16004// Permission is granted to anyone to use this software for any purpose,
16005// including commercial applications, and to alter it and redistribute it
16006// freely, subject to the following restrictions:
16007//
16008// 1. The origin of this software must not be misrepresented; you must not
16009//   claim that you wrote the original software. If you use this software
16010//   in a product, an acknowledgment in the product documentation would be
16011//   appreciated but is not required.
16012// 2. Altered source versions must be plainly marked as such, and must not be
16013//   misrepresented as being the original software.
16014// 3. This notice may not be removed or altered from any source distribution.
16015
16016// Use ordinary array, since untyped makes no boost here
16017function makeTable() {
16018  var c, table = [];
16019
16020  for (var n = 0; n < 256; n++) {
16021    c = n;
16022    for (var k = 0; k < 8; k++) {
16023      c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
16024    }
16025    table[n] = c;
16026  }
16027
16028  return table;
16029}
16030
16031// Create table on load. Just 255 signed longs. Not a problem.
16032var crcTable = makeTable();
16033
16034
16035function crc32(crc, buf, len, pos) {
16036  var t = crcTable,
16037      end = pos + len;
16038
16039  crc ^= -1;
16040
16041  for (var i = pos; i < end; i++) {
16042    crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
16043  }
16044
16045  return (crc ^ (-1)); // >>> 0;
16046}
16047
16048
16049module.exports = crc32;
16050
16051},{}],59:[function(require,module,exports){
16052'use strict';
16053
16054// (C) 1995-2013 Jean-loup Gailly and Mark Adler
16055// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
16056//
16057// This software is provided 'as-is', without any express or implied
16058// warranty. In no event will the authors be held liable for any damages
16059// arising from the use of this software.
16060//
16061// Permission is granted to anyone to use this software for any purpose,
16062// including commercial applications, and to alter it and redistribute it
16063// freely, subject to the following restrictions:
16064//
16065// 1. The origin of this software must not be misrepresented; you must not
16066//   claim that you wrote the original software. If you use this software
16067//   in a product, an acknowledgment in the product documentation would be
16068//   appreciated but is not required.
16069// 2. Altered source versions must be plainly marked as such, and must not be
16070//   misrepresented as being the original software.
16071// 3. This notice may not be removed or altered from any source distribution.
16072
16073var utils   = require('../utils/common');
16074var trees   = require('./trees');
16075var adler32 = require('./adler32');
16076var crc32   = require('./crc32');
16077var msg     = require('./messages');
16078
16079/* Public constants ==========================================================*/
16080/* ===========================================================================*/
16081
16082
16083/* Allowed flush values; see deflate() and inflate() below for details */
16084var Z_NO_FLUSH      = 0;
16085var Z_PARTIAL_FLUSH = 1;
16086//var Z_SYNC_FLUSH    = 2;
16087var Z_FULL_FLUSH    = 3;
16088var Z_FINISH        = 4;
16089var Z_BLOCK         = 5;
16090//var Z_TREES         = 6;
16091
16092
16093/* Return codes for the compression/decompression functions. Negative values
16094 * are errors, positive values are used for special but normal events.
16095 */
16096var Z_OK            = 0;
16097var Z_STREAM_END    = 1;
16098//var Z_NEED_DICT     = 2;
16099//var Z_ERRNO         = -1;
16100var Z_STREAM_ERROR  = -2;
16101var Z_DATA_ERROR    = -3;
16102//var Z_MEM_ERROR     = -4;
16103var Z_BUF_ERROR     = -5;
16104//var Z_VERSION_ERROR = -6;
16105
16106
16107/* compression levels */
16108//var Z_NO_COMPRESSION      = 0;
16109//var Z_BEST_SPEED          = 1;
16110//var Z_BEST_COMPRESSION    = 9;
16111var Z_DEFAULT_COMPRESSION = -1;
16112
16113
16114var Z_FILTERED            = 1;
16115var Z_HUFFMAN_ONLY        = 2;
16116var Z_RLE                 = 3;
16117var Z_FIXED               = 4;
16118var Z_DEFAULT_STRATEGY    = 0;
16119
16120/* Possible values of the data_type field (though see inflate()) */
16121//var Z_BINARY              = 0;
16122//var Z_TEXT                = 1;
16123//var Z_ASCII               = 1; // = Z_TEXT
16124var Z_UNKNOWN             = 2;
16125
16126
16127/* The deflate compression method */
16128var Z_DEFLATED  = 8;
16129
16130/*============================================================================*/
16131
16132
16133var MAX_MEM_LEVEL = 9;
16134/* Maximum value for memLevel in deflateInit2 */
16135var MAX_WBITS = 15;
16136/* 32K LZ77 window */
16137var DEF_MEM_LEVEL = 8;
16138
16139
16140var LENGTH_CODES  = 29;
16141/* number of length codes, not counting the special END_BLOCK code */
16142var LITERALS      = 256;
16143/* number of literal bytes 0..255 */
16144var L_CODES       = LITERALS + 1 + LENGTH_CODES;
16145/* number of Literal or Length codes, including the END_BLOCK code */
16146var D_CODES       = 30;
16147/* number of distance codes */
16148var BL_CODES      = 19;
16149/* number of codes used to transfer the bit lengths */
16150var HEAP_SIZE     = 2 * L_CODES + 1;
16151/* maximum heap size */
16152var MAX_BITS  = 15;
16153/* All codes must not exceed MAX_BITS bits */
16154
16155var MIN_MATCH = 3;
16156var MAX_MATCH = 258;
16157var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
16158
16159var PRESET_DICT = 0x20;
16160
16161var INIT_STATE = 42;
16162var EXTRA_STATE = 69;
16163var NAME_STATE = 73;
16164var COMMENT_STATE = 91;
16165var HCRC_STATE = 103;
16166var BUSY_STATE = 113;
16167var FINISH_STATE = 666;
16168
16169var BS_NEED_MORE      = 1; /* block not completed, need more input or more output */
16170var BS_BLOCK_DONE     = 2; /* block flush performed */
16171var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
16172var BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */
16173
16174var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
16175
16176function err(strm, errorCode) {
16177  strm.msg = msg[errorCode];
16178  return errorCode;
16179}
16180
16181function rank(f) {
16182  return ((f) << 1) - ((f) > 4 ? 9 : 0);
16183}
16184
16185function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
16186
16187
16188/* =========================================================================
16189 * Flush as much pending output as possible. All deflate() output goes
16190 * through this function so some applications may wish to modify it
16191 * to avoid allocating a large strm->output buffer and copying into it.
16192 * (See also read_buf()).
16193 */
16194function flush_pending(strm) {
16195  var s = strm.state;
16196
16197  //_tr_flush_bits(s);
16198  var len = s.pending;
16199  if (len > strm.avail_out) {
16200    len = strm.avail_out;
16201  }
16202  if (len === 0) { return; }
16203
16204  utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
16205  strm.next_out += len;
16206  s.pending_out += len;
16207  strm.total_out += len;
16208  strm.avail_out -= len;
16209  s.pending -= len;
16210  if (s.pending === 0) {
16211    s.pending_out = 0;
16212  }
16213}
16214
16215
16216function flush_block_only(s, last) {
16217  trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
16218  s.block_start = s.strstart;
16219  flush_pending(s.strm);
16220}
16221
16222
16223function put_byte(s, b) {
16224  s.pending_buf[s.pending++] = b;
16225}
16226
16227
16228/* =========================================================================
16229 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
16230 * IN assertion: the stream state is correct and there is enough room in
16231 * pending_buf.
16232 */
16233function putShortMSB(s, b) {
16234//  put_byte(s, (Byte)(b >> 8));
16235//  put_byte(s, (Byte)(b & 0xff));
16236  s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
16237  s.pending_buf[s.pending++] = b & 0xff;
16238}
16239
16240
16241/* ===========================================================================
16242 * Read a new buffer from the current input stream, update the adler32
16243 * and total number of bytes read.  All deflate() input goes through
16244 * this function so some applications may wish to modify it to avoid
16245 * allocating a large strm->input buffer and copying from it.
16246 * (See also flush_pending()).
16247 */
16248function read_buf(strm, buf, start, size) {
16249  var len = strm.avail_in;
16250
16251  if (len > size) { len = size; }
16252  if (len === 0) { return 0; }
16253
16254  strm.avail_in -= len;
16255
16256  // zmemcpy(buf, strm->next_in, len);
16257  utils.arraySet(buf, strm.input, strm.next_in, len, start);
16258  if (strm.state.wrap === 1) {
16259    strm.adler = adler32(strm.adler, buf, len, start);
16260  }
16261
16262  else if (strm.state.wrap === 2) {
16263    strm.adler = crc32(strm.adler, buf, len, start);
16264  }
16265
16266  strm.next_in += len;
16267  strm.total_in += len;
16268
16269  return len;
16270}
16271
16272
16273/* ===========================================================================
16274 * Set match_start to the longest match starting at the given string and
16275 * return its length. Matches shorter or equal to prev_length are discarded,
16276 * in which case the result is equal to prev_length and match_start is
16277 * garbage.
16278 * IN assertions: cur_match is the head of the hash chain for the current
16279 *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
16280 * OUT assertion: the match length is not greater than s->lookahead.
16281 */
16282function longest_match(s, cur_match) {
16283  var chain_length = s.max_chain_length;      /* max hash chain length */
16284  var scan = s.strstart; /* current string */
16285  var match;                       /* matched string */
16286  var len;                           /* length of current match */
16287  var best_len = s.prev_length;              /* best match length so far */
16288  var nice_match = s.nice_match;             /* stop if match long enough */
16289  var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
16290      s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
16291
16292  var _win = s.window; // shortcut
16293
16294  var wmask = s.w_mask;
16295  var prev  = s.prev;
16296
16297  /* Stop when cur_match becomes <= limit. To simplify the code,
16298   * we prevent matches with the string of window index 0.
16299   */
16300
16301  var strend = s.strstart + MAX_MATCH;
16302  var scan_end1  = _win[scan + best_len - 1];
16303  var scan_end   = _win[scan + best_len];
16304
16305  /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
16306   * It is easy to get rid of this optimization if necessary.
16307   */
16308  // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
16309
16310  /* Do not waste too much time if we already have a good match: */
16311  if (s.prev_length >= s.good_match) {
16312    chain_length >>= 2;
16313  }
16314  /* Do not look for matches beyond the end of the input. This is necessary
16315   * to make deflate deterministic.
16316   */
16317  if (nice_match > s.lookahead) { nice_match = s.lookahead; }
16318
16319  // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
16320
16321  do {
16322    // Assert(cur_match < s->strstart, "no future");
16323    match = cur_match;
16324
16325    /* Skip to next match if the match length cannot increase
16326     * or if the match length is less than 2.  Note that the checks below
16327     * for insufficient lookahead only occur occasionally for performance
16328     * reasons.  Therefore uninitialized memory will be accessed, and
16329     * conditional jumps will be made that depend on those values.
16330     * However the length of the match is limited to the lookahead, so
16331     * the output of deflate is not affected by the uninitialized values.
16332     */
16333
16334    if (_win[match + best_len]     !== scan_end  ||
16335        _win[match + best_len - 1] !== scan_end1 ||
16336        _win[match]                !== _win[scan] ||
16337        _win[++match]              !== _win[scan + 1]) {
16338      continue;
16339    }
16340
16341    /* The check at best_len-1 can be removed because it will be made
16342     * again later. (This heuristic is not always a win.)
16343     * It is not necessary to compare scan[2] and match[2] since they
16344     * are always equal when the other bytes match, given that
16345     * the hash keys are equal and that HASH_BITS >= 8.
16346     */
16347    scan += 2;
16348    match++;
16349    // Assert(*scan == *match, "match[2]?");
16350
16351    /* We check for insufficient lookahead only every 8th comparison;
16352     * the 256th check will be made at strstart+258.
16353     */
16354    do {
16355      /*jshint noempty:false*/
16356    } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
16357             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
16358             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
16359             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
16360             scan < strend);
16361
16362    // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
16363
16364    len = MAX_MATCH - (strend - scan);
16365    scan = strend - MAX_MATCH;
16366
16367    if (len > best_len) {
16368      s.match_start = cur_match;
16369      best_len = len;
16370      if (len >= nice_match) {
16371        break;
16372      }
16373      scan_end1  = _win[scan + best_len - 1];
16374      scan_end   = _win[scan + best_len];
16375    }
16376  } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
16377
16378  if (best_len <= s.lookahead) {
16379    return best_len;
16380  }
16381  return s.lookahead;
16382}
16383
16384
16385/* ===========================================================================
16386 * Fill the window when the lookahead becomes insufficient.
16387 * Updates strstart and lookahead.
16388 *
16389 * IN assertion: lookahead < MIN_LOOKAHEAD
16390 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
16391 *    At least one byte has been read, or avail_in == 0; reads are
16392 *    performed for at least two bytes (required for the zip translate_eol
16393 *    option -- not supported here).
16394 */
16395function fill_window(s) {
16396  var _w_size = s.w_size;
16397  var p, n, m, more, str;
16398
16399  //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
16400
16401  do {
16402    more = s.window_size - s.lookahead - s.strstart;
16403
16404    // JS ints have 32 bit, block below not needed
16405    /* Deal with !@#$% 64K limit: */
16406    //if (sizeof(int) <= 2) {
16407    //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
16408    //        more = wsize;
16409    //
16410    //  } else if (more == (unsigned)(-1)) {
16411    //        /* Very unlikely, but possible on 16 bit machine if
16412    //         * strstart == 0 && lookahead == 1 (input done a byte at time)
16413    //         */
16414    //        more--;
16415    //    }
16416    //}
16417
16418
16419    /* If the window is almost full and there is insufficient lookahead,
16420     * move the upper half to the lower one to make room in the upper half.
16421     */
16422    if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
16423
16424      utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
16425      s.match_start -= _w_size;
16426      s.strstart -= _w_size;
16427      /* we now have strstart >= MAX_DIST */
16428      s.block_start -= _w_size;
16429
16430      /* Slide the hash table (could be avoided with 32 bit values
16431       at the expense of memory usage). We slide even when level == 0
16432       to keep the hash table consistent if we switch back to level > 0
16433       later. (Using level 0 permanently is not an optimal usage of
16434       zlib, so we don't care about this pathological case.)
16435       */
16436
16437      n = s.hash_size;
16438      p = n;
16439      do {
16440        m = s.head[--p];
16441        s.head[p] = (m >= _w_size ? m - _w_size : 0);
16442      } while (--n);
16443
16444      n = _w_size;
16445      p = n;
16446      do {
16447        m = s.prev[--p];
16448        s.prev[p] = (m >= _w_size ? m - _w_size : 0);
16449        /* If n is not on any hash chain, prev[n] is garbage but
16450         * its value will never be used.
16451         */
16452      } while (--n);
16453
16454      more += _w_size;
16455    }
16456    if (s.strm.avail_in === 0) {
16457      break;
16458    }
16459
16460    /* If there was no sliding:
16461     *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
16462     *    more == window_size - lookahead - strstart
16463     * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
16464     * => more >= window_size - 2*WSIZE + 2
16465     * In the BIG_MEM or MMAP case (not yet supported),
16466     *   window_size == input_size + MIN_LOOKAHEAD  &&
16467     *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
16468     * Otherwise, window_size == 2*WSIZE so more >= 2.
16469     * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
16470     */
16471    //Assert(more >= 2, "more < 2");
16472    n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
16473    s.lookahead += n;
16474
16475    /* Initialize the hash value now that we have some input: */
16476    if (s.lookahead + s.insert >= MIN_MATCH) {
16477      str = s.strstart - s.insert;
16478      s.ins_h = s.window[str];
16479
16480      /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
16481      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
16482//#if MIN_MATCH != 3
16483//        Call update_hash() MIN_MATCH-3 more times
16484//#endif
16485      while (s.insert) {
16486        /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
16487        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
16488
16489        s.prev[str & s.w_mask] = s.head[s.ins_h];
16490        s.head[s.ins_h] = str;
16491        str++;
16492        s.insert--;
16493        if (s.lookahead + s.insert < MIN_MATCH) {
16494          break;
16495        }
16496      }
16497    }
16498    /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
16499     * but this is not important since only literal bytes will be emitted.
16500     */
16501
16502  } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
16503
16504  /* If the WIN_INIT bytes after the end of the current data have never been
16505   * written, then zero those bytes in order to avoid memory check reports of
16506   * the use of uninitialized (or uninitialised as Julian writes) bytes by
16507   * the longest match routines.  Update the high water mark for the next
16508   * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
16509   * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
16510   */
16511//  if (s.high_water < s.window_size) {
16512//    var curr = s.strstart + s.lookahead;
16513//    var init = 0;
16514//
16515//    if (s.high_water < curr) {
16516//      /* Previous high water mark below current data -- zero WIN_INIT
16517//       * bytes or up to end of window, whichever is less.
16518//       */
16519//      init = s.window_size - curr;
16520//      if (init > WIN_INIT)
16521//        init = WIN_INIT;
16522//      zmemzero(s->window + curr, (unsigned)init);
16523//      s->high_water = curr + init;
16524//    }
16525//    else if (s->high_water < (ulg)curr + WIN_INIT) {
16526//      /* High water mark at or above current data, but below current data
16527//       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
16528//       * to end of window, whichever is less.
16529//       */
16530//      init = (ulg)curr + WIN_INIT - s->high_water;
16531//      if (init > s->window_size - s->high_water)
16532//        init = s->window_size - s->high_water;
16533//      zmemzero(s->window + s->high_water, (unsigned)init);
16534//      s->high_water += init;
16535//    }
16536//  }
16537//
16538//  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
16539//    "not enough room for search");
16540}
16541
16542/* ===========================================================================
16543 * Copy without compression as much as possible from the input stream, return
16544 * the current block state.
16545 * This function does not insert new strings in the dictionary since
16546 * uncompressible data is probably not useful. This function is used
16547 * only for the level=0 compression option.
16548 * NOTE: this function should be optimized to avoid extra copying from
16549 * window to pending_buf.
16550 */
16551function deflate_stored(s, flush) {
16552  /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
16553   * to pending_buf_size, and each stored block has a 5 byte header:
16554   */
16555  var max_block_size = 0xffff;
16556
16557  if (max_block_size > s.pending_buf_size - 5) {
16558    max_block_size = s.pending_buf_size - 5;
16559  }
16560
16561  /* Copy as much as possible from input to output: */
16562  for (;;) {
16563    /* Fill the window as much as possible: */
16564    if (s.lookahead <= 1) {
16565
16566      //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
16567      //  s->block_start >= (long)s->w_size, "slide too late");
16568//      if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
16569//        s.block_start >= s.w_size)) {
16570//        throw  new Error("slide too late");
16571//      }
16572
16573      fill_window(s);
16574      if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
16575        return BS_NEED_MORE;
16576      }
16577
16578      if (s.lookahead === 0) {
16579        break;
16580      }
16581      /* flush the current block */
16582    }
16583    //Assert(s->block_start >= 0L, "block gone");
16584//    if (s.block_start < 0) throw new Error("block gone");
16585
16586    s.strstart += s.lookahead;
16587    s.lookahead = 0;
16588
16589    /* Emit a stored block if pending_buf will be full: */
16590    var max_start = s.block_start + max_block_size;
16591
16592    if (s.strstart === 0 || s.strstart >= max_start) {
16593      /* strstart == 0 is possible when wraparound on 16-bit machine */
16594      s.lookahead = s.strstart - max_start;
16595      s.strstart = max_start;
16596      /*** FLUSH_BLOCK(s, 0); ***/
16597      flush_block_only(s, false);
16598      if (s.strm.avail_out === 0) {
16599        return BS_NEED_MORE;
16600      }
16601      /***/
16602
16603
16604    }
16605    /* Flush if we may have to slide, otherwise block_start may become
16606     * negative and the data will be gone:
16607     */
16608    if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
16609      /*** FLUSH_BLOCK(s, 0); ***/
16610      flush_block_only(s, false);
16611      if (s.strm.avail_out === 0) {
16612        return BS_NEED_MORE;
16613      }
16614      /***/
16615    }
16616  }
16617
16618  s.insert = 0;
16619
16620  if (flush === Z_FINISH) {
16621    /*** FLUSH_BLOCK(s, 1); ***/
16622    flush_block_only(s, true);
16623    if (s.strm.avail_out === 0) {
16624      return BS_FINISH_STARTED;
16625    }
16626    /***/
16627    return BS_FINISH_DONE;
16628  }
16629
16630  if (s.strstart > s.block_start) {
16631    /*** FLUSH_BLOCK(s, 0); ***/
16632    flush_block_only(s, false);
16633    if (s.strm.avail_out === 0) {
16634      return BS_NEED_MORE;
16635    }
16636    /***/
16637  }
16638
16639  return BS_NEED_MORE;
16640}
16641
16642/* ===========================================================================
16643 * Compress as much as possible from the input stream, return the current
16644 * block state.
16645 * This function does not perform lazy evaluation of matches and inserts
16646 * new strings in the dictionary only for unmatched strings or for short
16647 * matches. It is used only for the fast compression options.
16648 */
16649function deflate_fast(s, flush) {
16650  var hash_head;        /* head of the hash chain */
16651  var bflush;           /* set if current block must be flushed */
16652
16653  for (;;) {
16654    /* Make sure that we always have enough lookahead, except
16655     * at the end of the input file. We need MAX_MATCH bytes
16656     * for the next match, plus MIN_MATCH bytes to insert the
16657     * string following the next match.
16658     */
16659    if (s.lookahead < MIN_LOOKAHEAD) {
16660      fill_window(s);
16661      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
16662        return BS_NEED_MORE;
16663      }
16664      if (s.lookahead === 0) {
16665        break; /* flush the current block */
16666      }
16667    }
16668
16669    /* Insert the string window[strstart .. strstart+2] in the
16670     * dictionary, and set hash_head to the head of the hash chain:
16671     */
16672    hash_head = 0/*NIL*/;
16673    if (s.lookahead >= MIN_MATCH) {
16674      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
16675      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
16676      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
16677      s.head[s.ins_h] = s.strstart;
16678      /***/
16679    }
16680
16681    /* Find the longest match, discarding those <= prev_length.
16682     * At this point we have always match_length < MIN_MATCH
16683     */
16684    if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
16685      /* To simplify the code, we prevent matches with the string
16686       * of window index 0 (in particular we have to avoid a match
16687       * of the string with itself at the start of the input file).
16688       */
16689      s.match_length = longest_match(s, hash_head);
16690      /* longest_match() sets match_start */
16691    }
16692    if (s.match_length >= MIN_MATCH) {
16693      // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
16694
16695      /*** _tr_tally_dist(s, s.strstart - s.match_start,
16696                     s.match_length - MIN_MATCH, bflush); ***/
16697      bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
16698
16699      s.lookahead -= s.match_length;
16700
16701      /* Insert new strings in the hash table only if the match length
16702       * is not too large. This saves time but degrades compression.
16703       */
16704      if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
16705        s.match_length--; /* string at strstart already in table */
16706        do {
16707          s.strstart++;
16708          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
16709          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
16710          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
16711          s.head[s.ins_h] = s.strstart;
16712          /***/
16713          /* strstart never exceeds WSIZE-MAX_MATCH, so there are
16714           * always MIN_MATCH bytes ahead.
16715           */
16716        } while (--s.match_length !== 0);
16717        s.strstart++;
16718      } else
16719      {
16720        s.strstart += s.match_length;
16721        s.match_length = 0;
16722        s.ins_h = s.window[s.strstart];
16723        /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
16724        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
16725
16726//#if MIN_MATCH != 3
16727//                Call UPDATE_HASH() MIN_MATCH-3 more times
16728//#endif
16729        /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
16730         * matter since it will be recomputed at next deflate call.
16731         */
16732      }
16733    } else {
16734      /* No match, output a literal byte */
16735      //Tracevv((stderr,"%c", s.window[s.strstart]));
16736      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
16737      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
16738
16739      s.lookahead--;
16740      s.strstart++;
16741    }
16742    if (bflush) {
16743      /*** FLUSH_BLOCK(s, 0); ***/
16744      flush_block_only(s, false);
16745      if (s.strm.avail_out === 0) {
16746        return BS_NEED_MORE;
16747      }
16748      /***/
16749    }
16750  }
16751  s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
16752  if (flush === Z_FINISH) {
16753    /*** FLUSH_BLOCK(s, 1); ***/
16754    flush_block_only(s, true);
16755    if (s.strm.avail_out === 0) {
16756      return BS_FINISH_STARTED;
16757    }
16758    /***/
16759    return BS_FINISH_DONE;
16760  }
16761  if (s.last_lit) {
16762    /*** FLUSH_BLOCK(s, 0); ***/
16763    flush_block_only(s, false);
16764    if (s.strm.avail_out === 0) {
16765      return BS_NEED_MORE;
16766    }
16767    /***/
16768  }
16769  return BS_BLOCK_DONE;
16770}
16771
16772/* ===========================================================================
16773 * Same as above, but achieves better compression. We use a lazy
16774 * evaluation for matches: a match is finally adopted only if there is
16775 * no better match at the next window position.
16776 */
16777function deflate_slow(s, flush) {
16778  var hash_head;          /* head of hash chain */
16779  var bflush;              /* set if current block must be flushed */
16780
16781  var max_insert;
16782
16783  /* Process the input block. */
16784  for (;;) {
16785    /* Make sure that we always have enough lookahead, except
16786     * at the end of the input file. We need MAX_MATCH bytes
16787     * for the next match, plus MIN_MATCH bytes to insert the
16788     * string following the next match.
16789     */
16790    if (s.lookahead < MIN_LOOKAHEAD) {
16791      fill_window(s);
16792      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
16793        return BS_NEED_MORE;
16794      }
16795      if (s.lookahead === 0) { break; } /* flush the current block */
16796    }
16797
16798    /* Insert the string window[strstart .. strstart+2] in the
16799     * dictionary, and set hash_head to the head of the hash chain:
16800     */
16801    hash_head = 0/*NIL*/;
16802    if (s.lookahead >= MIN_MATCH) {
16803      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
16804      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
16805      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
16806      s.head[s.ins_h] = s.strstart;
16807      /***/
16808    }
16809
16810    /* Find the longest match, discarding those <= prev_length.
16811     */
16812    s.prev_length = s.match_length;
16813    s.prev_match = s.match_start;
16814    s.match_length = MIN_MATCH - 1;
16815
16816    if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
16817        s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
16818      /* To simplify the code, we prevent matches with the string
16819       * of window index 0 (in particular we have to avoid a match
16820       * of the string with itself at the start of the input file).
16821       */
16822      s.match_length = longest_match(s, hash_head);
16823      /* longest_match() sets match_start */
16824
16825      if (s.match_length <= 5 &&
16826         (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
16827
16828        /* If prev_match is also MIN_MATCH, match_start is garbage
16829         * but we will ignore the current match anyway.
16830         */
16831        s.match_length = MIN_MATCH - 1;
16832      }
16833    }
16834    /* If there was a match at the previous step and the current
16835     * match is not better, output the previous match:
16836     */
16837    if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
16838      max_insert = s.strstart + s.lookahead - MIN_MATCH;
16839      /* Do not insert strings in hash table beyond this. */
16840
16841      //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
16842
16843      /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
16844                     s.prev_length - MIN_MATCH, bflush);***/
16845      bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
16846      /* Insert in hash table all strings up to the end of the match.
16847       * strstart-1 and strstart are already inserted. If there is not
16848       * enough lookahead, the last two strings are not inserted in
16849       * the hash table.
16850       */
16851      s.lookahead -= s.prev_length - 1;
16852      s.prev_length -= 2;
16853      do {
16854        if (++s.strstart <= max_insert) {
16855          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
16856          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
16857          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
16858          s.head[s.ins_h] = s.strstart;
16859          /***/
16860        }
16861      } while (--s.prev_length !== 0);
16862      s.match_available = 0;
16863      s.match_length = MIN_MATCH - 1;
16864      s.strstart++;
16865
16866      if (bflush) {
16867        /*** FLUSH_BLOCK(s, 0); ***/
16868        flush_block_only(s, false);
16869        if (s.strm.avail_out === 0) {
16870          return BS_NEED_MORE;
16871        }
16872        /***/
16873      }
16874
16875    } else if (s.match_available) {
16876      /* If there was no match at the previous position, output a
16877       * single literal. If there was a match but the current match
16878       * is longer, truncate the previous match to a single literal.
16879       */
16880      //Tracevv((stderr,"%c", s->window[s->strstart-1]));
16881      /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
16882      bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
16883
16884      if (bflush) {
16885        /*** FLUSH_BLOCK_ONLY(s, 0) ***/
16886        flush_block_only(s, false);
16887        /***/
16888      }
16889      s.strstart++;
16890      s.lookahead--;
16891      if (s.strm.avail_out === 0) {
16892        return BS_NEED_MORE;
16893      }
16894    } else {
16895      /* There is no previous match to compare with, wait for
16896       * the next step to decide.
16897       */
16898      s.match_available = 1;
16899      s.strstart++;
16900      s.lookahead--;
16901    }
16902  }
16903  //Assert (flush != Z_NO_FLUSH, "no flush?");
16904  if (s.match_available) {
16905    //Tracevv((stderr,"%c", s->window[s->strstart-1]));
16906    /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
16907    bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
16908
16909    s.match_available = 0;
16910  }
16911  s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
16912  if (flush === Z_FINISH) {
16913    /*** FLUSH_BLOCK(s, 1); ***/
16914    flush_block_only(s, true);
16915    if (s.strm.avail_out === 0) {
16916      return BS_FINISH_STARTED;
16917    }
16918    /***/
16919    return BS_FINISH_DONE;
16920  }
16921  if (s.last_lit) {
16922    /*** FLUSH_BLOCK(s, 0); ***/
16923    flush_block_only(s, false);
16924    if (s.strm.avail_out === 0) {
16925      return BS_NEED_MORE;
16926    }
16927    /***/
16928  }
16929
16930  return BS_BLOCK_DONE;
16931}
16932
16933
16934/* ===========================================================================
16935 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
16936 * one.  Do not maintain a hash table.  (It will be regenerated if this run of
16937 * deflate switches away from Z_RLE.)
16938 */
16939function deflate_rle(s, flush) {
16940  var bflush;            /* set if current block must be flushed */
16941  var prev;              /* byte at distance one to match */
16942  var scan, strend;      /* scan goes up to strend for length of run */
16943
16944  var _win = s.window;
16945
16946  for (;;) {
16947    /* Make sure that we always have enough lookahead, except
16948     * at the end of the input file. We need MAX_MATCH bytes
16949     * for the longest run, plus one for the unrolled loop.
16950     */
16951    if (s.lookahead <= MAX_MATCH) {
16952      fill_window(s);
16953      if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
16954        return BS_NEED_MORE;
16955      }
16956      if (s.lookahead === 0) { break; } /* flush the current block */
16957    }
16958
16959    /* See how many times the previous byte repeats */
16960    s.match_length = 0;
16961    if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
16962      scan = s.strstart - 1;
16963      prev = _win[scan];
16964      if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
16965        strend = s.strstart + MAX_MATCH;
16966        do {
16967          /*jshint noempty:false*/
16968        } while (prev === _win[++scan] && prev === _win[++scan] &&
16969                 prev === _win[++scan] && prev === _win[++scan] &&
16970                 prev === _win[++scan] && prev === _win[++scan] &&
16971                 prev === _win[++scan] && prev === _win[++scan] &&
16972                 scan < strend);
16973        s.match_length = MAX_MATCH - (strend - scan);
16974        if (s.match_length > s.lookahead) {
16975          s.match_length = s.lookahead;
16976        }
16977      }
16978      //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
16979    }
16980
16981    /* Emit match if have run of MIN_MATCH or longer, else emit literal */
16982    if (s.match_length >= MIN_MATCH) {
16983      //check_match(s, s.strstart, s.strstart - 1, s.match_length);
16984
16985      /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
16986      bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
16987
16988      s.lookahead -= s.match_length;
16989      s.strstart += s.match_length;
16990      s.match_length = 0;
16991    } else {
16992      /* No match, output a literal byte */
16993      //Tracevv((stderr,"%c", s->window[s->strstart]));
16994      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
16995      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
16996
16997      s.lookahead--;
16998      s.strstart++;
16999    }
17000    if (bflush) {
17001      /*** FLUSH_BLOCK(s, 0); ***/
17002      flush_block_only(s, false);
17003      if (s.strm.avail_out === 0) {
17004        return BS_NEED_MORE;
17005      }
17006      /***/
17007    }
17008  }
17009  s.insert = 0;
17010  if (flush === Z_FINISH) {
17011    /*** FLUSH_BLOCK(s, 1); ***/
17012    flush_block_only(s, true);
17013    if (s.strm.avail_out === 0) {
17014      return BS_FINISH_STARTED;
17015    }
17016    /***/
17017    return BS_FINISH_DONE;
17018  }
17019  if (s.last_lit) {
17020    /*** FLUSH_BLOCK(s, 0); ***/
17021    flush_block_only(s, false);
17022    if (s.strm.avail_out === 0) {
17023      return BS_NEED_MORE;
17024    }
17025    /***/
17026  }
17027  return BS_BLOCK_DONE;
17028}
17029
17030/* ===========================================================================
17031 * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
17032 * (It will be regenerated if this run of deflate switches away from Huffman.)
17033 */
17034function deflate_huff(s, flush) {
17035  var bflush;             /* set if current block must be flushed */
17036
17037  for (;;) {
17038    /* Make sure that we have a literal to write. */
17039    if (s.lookahead === 0) {
17040      fill_window(s);
17041      if (s.lookahead === 0) {
17042        if (flush === Z_NO_FLUSH) {
17043          return BS_NEED_MORE;
17044        }
17045        break;      /* flush the current block */
17046      }
17047    }
17048
17049    /* Output a literal byte */
17050    s.match_length = 0;
17051    //Tracevv((stderr,"%c", s->window[s->strstart]));
17052    /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
17053    bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
17054    s.lookahead--;
17055    s.strstart++;
17056    if (bflush) {
17057      /*** FLUSH_BLOCK(s, 0); ***/
17058      flush_block_only(s, false);
17059      if (s.strm.avail_out === 0) {
17060        return BS_NEED_MORE;
17061      }
17062      /***/
17063    }
17064  }
17065  s.insert = 0;
17066  if (flush === Z_FINISH) {
17067    /*** FLUSH_BLOCK(s, 1); ***/
17068    flush_block_only(s, true);
17069    if (s.strm.avail_out === 0) {
17070      return BS_FINISH_STARTED;
17071    }
17072    /***/
17073    return BS_FINISH_DONE;
17074  }
17075  if (s.last_lit) {
17076    /*** FLUSH_BLOCK(s, 0); ***/
17077    flush_block_only(s, false);
17078    if (s.strm.avail_out === 0) {
17079      return BS_NEED_MORE;
17080    }
17081    /***/
17082  }
17083  return BS_BLOCK_DONE;
17084}
17085
17086/* Values for max_lazy_match, good_match and max_chain_length, depending on
17087 * the desired pack level (0..9). The values given below have been tuned to
17088 * exclude worst case performance for pathological files. Better values may be
17089 * found for specific files.
17090 */
17091function Config(good_length, max_lazy, nice_length, max_chain, func) {
17092  this.good_length = good_length;
17093  this.max_lazy = max_lazy;
17094  this.nice_length = nice_length;
17095  this.max_chain = max_chain;
17096  this.func = func;
17097}
17098
17099var configuration_table;
17100
17101configuration_table = [
17102  /*      good lazy nice chain */
17103  new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */
17104  new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */
17105  new Config(4, 5, 16, 8, deflate_fast),           /* 2 */
17106  new Config(4, 6, 32, 32, deflate_fast),          /* 3 */
17107
17108  new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */
17109  new Config(8, 16, 32, 32, deflate_slow),         /* 5 */
17110  new Config(8, 16, 128, 128, deflate_slow),       /* 6 */
17111  new Config(8, 32, 128, 256, deflate_slow),       /* 7 */
17112  new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */
17113  new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */
17114];
17115
17116
17117/* ===========================================================================
17118 * Initialize the "longest match" routines for a new zlib stream
17119 */
17120function lm_init(s) {
17121  s.window_size = 2 * s.w_size;
17122
17123  /*** CLEAR_HASH(s); ***/
17124  zero(s.head); // Fill with NIL (= 0);
17125
17126  /* Set the default configuration parameters:
17127   */
17128  s.max_lazy_match = configuration_table[s.level].max_lazy;
17129  s.good_match = configuration_table[s.level].good_length;
17130  s.nice_match = configuration_table[s.level].nice_length;
17131  s.max_chain_length = configuration_table[s.level].max_chain;
17132
17133  s.strstart = 0;
17134  s.block_start = 0;
17135  s.lookahead = 0;
17136  s.insert = 0;
17137  s.match_length = s.prev_length = MIN_MATCH - 1;
17138  s.match_available = 0;
17139  s.ins_h = 0;
17140}
17141
17142
17143function DeflateState() {
17144  this.strm = null;            /* pointer back to this zlib stream */
17145  this.status = 0;            /* as the name implies */
17146  this.pending_buf = null;      /* output still pending */
17147  this.pending_buf_size = 0;  /* size of pending_buf */
17148  this.pending_out = 0;       /* next pending byte to output to the stream */
17149  this.pending = 0;           /* nb of bytes in the pending buffer */
17150  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
17151  this.gzhead = null;         /* gzip header information to write */
17152  this.gzindex = 0;           /* where in extra, name, or comment */
17153  this.method = Z_DEFLATED; /* can only be DEFLATED */
17154  this.last_flush = -1;   /* value of flush param for previous deflate call */
17155
17156  this.w_size = 0;  /* LZ77 window size (32K by default) */
17157  this.w_bits = 0;  /* log2(w_size)  (8..16) */
17158  this.w_mask = 0;  /* w_size - 1 */
17159
17160  this.window = null;
17161  /* Sliding window. Input bytes are read into the second half of the window,
17162   * and move to the first half later to keep a dictionary of at least wSize
17163   * bytes. With this organization, matches are limited to a distance of
17164   * wSize-MAX_MATCH bytes, but this ensures that IO is always
17165   * performed with a length multiple of the block size.
17166   */
17167
17168  this.window_size = 0;
17169  /* Actual size of window: 2*wSize, except when the user input buffer
17170   * is directly used as sliding window.
17171   */
17172
17173  this.prev = null;
17174  /* Link to older string with same hash index. To limit the size of this
17175   * array to 64K, this link is maintained only for the last 32K strings.
17176   * An index in this array is thus a window index modulo 32K.
17177   */
17178
17179  this.head = null;   /* Heads of the hash chains or NIL. */
17180
17181  this.ins_h = 0;       /* hash index of string to be inserted */
17182  this.hash_size = 0;   /* number of elements in hash table */
17183  this.hash_bits = 0;   /* log2(hash_size) */
17184  this.hash_mask = 0;   /* hash_size-1 */
17185
17186  this.hash_shift = 0;
17187  /* Number of bits by which ins_h must be shifted at each input
17188   * step. It must be such that after MIN_MATCH steps, the oldest
17189   * byte no longer takes part in the hash key, that is:
17190   *   hash_shift * MIN_MATCH >= hash_bits
17191   */
17192
17193  this.block_start = 0;
17194  /* Window position at the beginning of the current output block. Gets
17195   * negative when the window is moved backwards.
17196   */
17197
17198  this.match_length = 0;      /* length of best match */
17199  this.prev_match = 0;        /* previous match */
17200  this.match_available = 0;   /* set if previous match exists */
17201  this.strstart = 0;          /* start of string to insert */
17202  this.match_start = 0;       /* start of matching string */
17203  this.lookahead = 0;         /* number of valid bytes ahead in window */
17204
17205  this.prev_length = 0;
17206  /* Length of the best match at previous step. Matches not greater than this
17207   * are discarded. This is used in the lazy match evaluation.
17208   */
17209
17210  this.max_chain_length = 0;
17211  /* To speed up deflation, hash chains are never searched beyond this
17212   * length.  A higher limit improves compression ratio but degrades the
17213   * speed.
17214   */
17215
17216  this.max_lazy_match = 0;
17217  /* Attempt to find a better match only when the current match is strictly
17218   * smaller than this value. This mechanism is used only for compression
17219   * levels >= 4.
17220   */
17221  // That's alias to max_lazy_match, don't use directly
17222  //this.max_insert_length = 0;
17223  /* Insert new strings in the hash table only if the match length is not
17224   * greater than this length. This saves time but degrades compression.
17225   * max_insert_length is used only for compression levels <= 3.
17226   */
17227
17228  this.level = 0;     /* compression level (1..9) */
17229  this.strategy = 0;  /* favor or force Huffman coding*/
17230
17231  this.good_match = 0;
17232  /* Use a faster search when the previous match is longer than this */
17233
17234  this.nice_match = 0; /* Stop searching when current match exceeds this */
17235
17236              /* used by trees.c: */
17237
17238  /* Didn't use ct_data typedef below to suppress compiler warning */
17239
17240  // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
17241  // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
17242  // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
17243
17244  // Use flat array of DOUBLE size, with interleaved fata,
17245  // because JS does not support effective
17246  this.dyn_ltree  = new utils.Buf16(HEAP_SIZE * 2);
17247  this.dyn_dtree  = new utils.Buf16((2 * D_CODES + 1) * 2);
17248  this.bl_tree    = new utils.Buf16((2 * BL_CODES + 1) * 2);
17249  zero(this.dyn_ltree);
17250  zero(this.dyn_dtree);
17251  zero(this.bl_tree);
17252
17253  this.l_desc   = null;         /* desc. for literal tree */
17254  this.d_desc   = null;         /* desc. for distance tree */
17255  this.bl_desc  = null;         /* desc. for bit length tree */
17256
17257  //ush bl_count[MAX_BITS+1];
17258  this.bl_count = new utils.Buf16(MAX_BITS + 1);
17259  /* number of codes at each bit length for an optimal tree */
17260
17261  //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
17262  this.heap = new utils.Buf16(2 * L_CODES + 1);  /* heap used to build the Huffman trees */
17263  zero(this.heap);
17264
17265  this.heap_len = 0;               /* number of elements in the heap */
17266  this.heap_max = 0;               /* element of largest frequency */
17267  /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
17268   * The same heap array is used to build all trees.
17269   */
17270
17271  this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
17272  zero(this.depth);
17273  /* Depth of each subtree used as tie breaker for trees of equal frequency
17274   */
17275
17276  this.l_buf = 0;          /* buffer index for literals or lengths */
17277
17278  this.lit_bufsize = 0;
17279  /* Size of match buffer for literals/lengths.  There are 4 reasons for
17280   * limiting lit_bufsize to 64K:
17281   *   - frequencies can be kept in 16 bit counters
17282   *   - if compression is not successful for the first block, all input
17283   *     data is still in the window so we can still emit a stored block even
17284   *     when input comes from standard input.  (This can also be done for
17285   *     all blocks if lit_bufsize is not greater than 32K.)
17286   *   - if compression is not successful for a file smaller than 64K, we can
17287   *     even emit a stored file instead of a stored block (saving 5 bytes).
17288   *     This is applicable only for zip (not gzip or zlib).
17289   *   - creating new Huffman trees less frequently may not provide fast
17290   *     adaptation to changes in the input data statistics. (Take for
17291   *     example a binary file with poorly compressible code followed by
17292   *     a highly compressible string table.) Smaller buffer sizes give
17293   *     fast adaptation but have of course the overhead of transmitting
17294   *     trees more frequently.
17295   *   - I can't count above 4
17296   */
17297
17298  this.last_lit = 0;      /* running index in l_buf */
17299
17300  this.d_buf = 0;
17301  /* Buffer index for distances. To simplify the code, d_buf and l_buf have
17302   * the same number of elements. To use different lengths, an extra flag
17303   * array would be necessary.
17304   */
17305
17306  this.opt_len = 0;       /* bit length of current block with optimal trees */
17307  this.static_len = 0;    /* bit length of current block with static trees */
17308  this.matches = 0;       /* number of string matches in current block */
17309  this.insert = 0;        /* bytes at end of window left to insert */
17310
17311
17312  this.bi_buf = 0;
17313  /* Output buffer. bits are inserted starting at the bottom (least
17314   * significant bits).
17315   */
17316  this.bi_valid = 0;
17317  /* Number of valid bits in bi_buf.  All bits above the last valid bit
17318   * are always zero.
17319   */
17320
17321  // Used for window memory init. We safely ignore it for JS. That makes
17322  // sense only for pointers and memory check tools.
17323  //this.high_water = 0;
17324  /* High water mark offset in window for initialized bytes -- bytes above
17325   * this are set to zero in order to avoid memory check warnings when
17326   * longest match routines access bytes past the input.  This is then
17327   * updated to the new high water mark.
17328   */
17329}
17330
17331
17332function deflateResetKeep(strm) {
17333  var s;
17334
17335  if (!strm || !strm.state) {
17336    return err(strm, Z_STREAM_ERROR);
17337  }
17338
17339  strm.total_in = strm.total_out = 0;
17340  strm.data_type = Z_UNKNOWN;
17341
17342  s = strm.state;
17343  s.pending = 0;
17344  s.pending_out = 0;
17345
17346  if (s.wrap < 0) {
17347    s.wrap = -s.wrap;
17348    /* was made negative by deflate(..., Z_FINISH); */
17349  }
17350  s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
17351  strm.adler = (s.wrap === 2) ?
17352    0  // crc32(0, Z_NULL, 0)
17353  :
17354    1; // adler32(0, Z_NULL, 0)
17355  s.last_flush = Z_NO_FLUSH;
17356  trees._tr_init(s);
17357  return Z_OK;
17358}
17359
17360
17361function deflateReset(strm) {
17362  var ret = deflateResetKeep(strm);
17363  if (ret === Z_OK) {
17364    lm_init(strm.state);
17365  }
17366  return ret;
17367}
17368
17369
17370function deflateSetHeader(strm, head) {
17371  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
17372  if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
17373  strm.state.gzhead = head;
17374  return Z_OK;
17375}
17376
17377
17378function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
17379  if (!strm) { // === Z_NULL
17380    return Z_STREAM_ERROR;
17381  }
17382  var wrap = 1;
17383
17384  if (level === Z_DEFAULT_COMPRESSION) {
17385    level = 6;
17386  }
17387
17388  if (windowBits < 0) { /* suppress zlib wrapper */
17389    wrap = 0;
17390    windowBits = -windowBits;
17391  }
17392
17393  else if (windowBits > 15) {
17394    wrap = 2;           /* write gzip wrapper instead */
17395    windowBits -= 16;
17396  }
17397
17398
17399  if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
17400    windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
17401    strategy < 0 || strategy > Z_FIXED) {
17402    return err(strm, Z_STREAM_ERROR);
17403  }
17404
17405
17406  if (windowBits === 8) {
17407    windowBits = 9;
17408  }
17409  /* until 256-byte window bug fixed */
17410
17411  var s = new DeflateState();
17412
17413  strm.state = s;
17414  s.strm = strm;
17415
17416  s.wrap = wrap;
17417  s.gzhead = null;
17418  s.w_bits = windowBits;
17419  s.w_size = 1 << s.w_bits;
17420  s.w_mask = s.w_size - 1;
17421
17422  s.hash_bits = memLevel + 7;
17423  s.hash_size = 1 << s.hash_bits;
17424  s.hash_mask = s.hash_size - 1;
17425  s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
17426
17427  s.window = new utils.Buf8(s.w_size * 2);
17428  s.head = new utils.Buf16(s.hash_size);
17429  s.prev = new utils.Buf16(s.w_size);
17430
17431  // Don't need mem init magic for JS.
17432  //s.high_water = 0;  /* nothing written to s->window yet */
17433
17434  s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
17435
17436  s.pending_buf_size = s.lit_bufsize * 4;
17437
17438  //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
17439  //s->pending_buf = (uchf *) overlay;
17440  s.pending_buf = new utils.Buf8(s.pending_buf_size);
17441
17442  // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
17443  //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
17444  s.d_buf = 1 * s.lit_bufsize;
17445
17446  //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
17447  s.l_buf = (1 + 2) * s.lit_bufsize;
17448
17449  s.level = level;
17450  s.strategy = strategy;
17451  s.method = method;
17452
17453  return deflateReset(strm);
17454}
17455
17456function deflateInit(strm, level) {
17457  return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
17458}
17459
17460
17461function deflate(strm, flush) {
17462  var old_flush, s;
17463  var beg, val; // for gzip header write only
17464
17465  if (!strm || !strm.state ||
17466    flush > Z_BLOCK || flush < 0) {
17467    return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
17468  }
17469
17470  s = strm.state;
17471
17472  if (!strm.output ||
17473      (!strm.input && strm.avail_in !== 0) ||
17474      (s.status === FINISH_STATE && flush !== Z_FINISH)) {
17475    return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
17476  }
17477
17478  s.strm = strm; /* just in case */
17479  old_flush = s.last_flush;
17480  s.last_flush = flush;
17481
17482  /* Write the header */
17483  if (s.status === INIT_STATE) {
17484
17485    if (s.wrap === 2) { // GZIP header
17486      strm.adler = 0;  //crc32(0L, Z_NULL, 0);
17487      put_byte(s, 31);
17488      put_byte(s, 139);
17489      put_byte(s, 8);
17490      if (!s.gzhead) { // s->gzhead == Z_NULL
17491        put_byte(s, 0);
17492        put_byte(s, 0);
17493        put_byte(s, 0);
17494        put_byte(s, 0);
17495        put_byte(s, 0);
17496        put_byte(s, s.level === 9 ? 2 :
17497                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
17498                     4 : 0));
17499        put_byte(s, OS_CODE);
17500        s.status = BUSY_STATE;
17501      }
17502      else {
17503        put_byte(s, (s.gzhead.text ? 1 : 0) +
17504                    (s.gzhead.hcrc ? 2 : 0) +
17505                    (!s.gzhead.extra ? 0 : 4) +
17506                    (!s.gzhead.name ? 0 : 8) +
17507                    (!s.gzhead.comment ? 0 : 16)
17508                );
17509        put_byte(s, s.gzhead.time & 0xff);
17510        put_byte(s, (s.gzhead.time >> 8) & 0xff);
17511        put_byte(s, (s.gzhead.time >> 16) & 0xff);
17512        put_byte(s, (s.gzhead.time >> 24) & 0xff);
17513        put_byte(s, s.level === 9 ? 2 :
17514                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
17515                     4 : 0));
17516        put_byte(s, s.gzhead.os & 0xff);
17517        if (s.gzhead.extra && s.gzhead.extra.length) {
17518          put_byte(s, s.gzhead.extra.length & 0xff);
17519          put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
17520        }
17521        if (s.gzhead.hcrc) {
17522          strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
17523        }
17524        s.gzindex = 0;
17525        s.status = EXTRA_STATE;
17526      }
17527    }
17528    else // DEFLATE header
17529    {
17530      var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
17531      var level_flags = -1;
17532
17533      if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
17534        level_flags = 0;
17535      } else if (s.level < 6) {
17536        level_flags = 1;
17537      } else if (s.level === 6) {
17538        level_flags = 2;
17539      } else {
17540        level_flags = 3;
17541      }
17542      header |= (level_flags << 6);
17543      if (s.strstart !== 0) { header |= PRESET_DICT; }
17544      header += 31 - (header % 31);
17545
17546      s.status = BUSY_STATE;
17547      putShortMSB(s, header);
17548
17549      /* Save the adler32 of the preset dictionary: */
17550      if (s.strstart !== 0) {
17551        putShortMSB(s, strm.adler >>> 16);
17552        putShortMSB(s, strm.adler & 0xffff);
17553      }
17554      strm.adler = 1; // adler32(0L, Z_NULL, 0);
17555    }
17556  }
17557
17558//#ifdef GZIP
17559  if (s.status === EXTRA_STATE) {
17560    if (s.gzhead.extra/* != Z_NULL*/) {
17561      beg = s.pending;  /* start of bytes to update crc */
17562
17563      while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
17564        if (s.pending === s.pending_buf_size) {
17565          if (s.gzhead.hcrc && s.pending > beg) {
17566            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
17567          }
17568          flush_pending(strm);
17569          beg = s.pending;
17570          if (s.pending === s.pending_buf_size) {
17571            break;
17572          }
17573        }
17574        put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
17575        s.gzindex++;
17576      }
17577      if (s.gzhead.hcrc && s.pending > beg) {
17578        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
17579      }
17580      if (s.gzindex === s.gzhead.extra.length) {
17581        s.gzindex = 0;
17582        s.status = NAME_STATE;
17583      }
17584    }
17585    else {
17586      s.status = NAME_STATE;
17587    }
17588  }
17589  if (s.status === NAME_STATE) {
17590    if (s.gzhead.name/* != Z_NULL*/) {
17591      beg = s.pending;  /* start of bytes to update crc */
17592      //int val;
17593
17594      do {
17595        if (s.pending === s.pending_buf_size) {
17596          if (s.gzhead.hcrc && s.pending > beg) {
17597            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
17598          }
17599          flush_pending(strm);
17600          beg = s.pending;
17601          if (s.pending === s.pending_buf_size) {
17602            val = 1;
17603            break;
17604          }
17605        }
17606        // JS specific: little magic to add zero terminator to end of string
17607        if (s.gzindex < s.gzhead.name.length) {
17608          val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
17609        } else {
17610          val = 0;
17611        }
17612        put_byte(s, val);
17613      } while (val !== 0);
17614
17615      if (s.gzhead.hcrc && s.pending > beg) {
17616        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
17617      }
17618      if (val === 0) {
17619        s.gzindex = 0;
17620        s.status = COMMENT_STATE;
17621      }
17622    }
17623    else {
17624      s.status = COMMENT_STATE;
17625    }
17626  }
17627  if (s.status === COMMENT_STATE) {
17628    if (s.gzhead.comment/* != Z_NULL*/) {
17629      beg = s.pending;  /* start of bytes to update crc */
17630      //int val;
17631
17632      do {
17633        if (s.pending === s.pending_buf_size) {
17634          if (s.gzhead.hcrc && s.pending > beg) {
17635            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
17636          }
17637          flush_pending(strm);
17638          beg = s.pending;
17639          if (s.pending === s.pending_buf_size) {
17640            val = 1;
17641            break;
17642          }
17643        }
17644        // JS specific: little magic to add zero terminator to end of string
17645        if (s.gzindex < s.gzhead.comment.length) {
17646          val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
17647        } else {
17648          val = 0;
17649        }
17650        put_byte(s, val);
17651      } while (val !== 0);
17652
17653      if (s.gzhead.hcrc && s.pending > beg) {
17654        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
17655      }
17656      if (val === 0) {
17657        s.status = HCRC_STATE;
17658      }
17659    }
17660    else {
17661      s.status = HCRC_STATE;
17662    }
17663  }
17664  if (s.status === HCRC_STATE) {
17665    if (s.gzhead.hcrc) {
17666      if (s.pending + 2 > s.pending_buf_size) {
17667        flush_pending(strm);
17668      }
17669      if (s.pending + 2 <= s.pending_buf_size) {
17670        put_byte(s, strm.adler & 0xff);
17671        put_byte(s, (strm.adler >> 8) & 0xff);
17672        strm.adler = 0; //crc32(0L, Z_NULL, 0);
17673        s.status = BUSY_STATE;
17674      }
17675    }
17676    else {
17677      s.status = BUSY_STATE;
17678    }
17679  }
17680//#endif
17681
17682  /* Flush as much pending output as possible */
17683  if (s.pending !== 0) {
17684    flush_pending(strm);
17685    if (strm.avail_out === 0) {
17686      /* Since avail_out is 0, deflate will be called again with
17687       * more output space, but possibly with both pending and
17688       * avail_in equal to zero. There won't be anything to do,
17689       * but this is not an error situation so make sure we
17690       * return OK instead of BUF_ERROR at next call of deflate:
17691       */
17692      s.last_flush = -1;
17693      return Z_OK;
17694    }
17695
17696    /* Make sure there is something to do and avoid duplicate consecutive
17697     * flushes. For repeated and useless calls with Z_FINISH, we keep
17698     * returning Z_STREAM_END instead of Z_BUF_ERROR.
17699     */
17700  } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
17701    flush !== Z_FINISH) {
17702    return err(strm, Z_BUF_ERROR);
17703  }
17704
17705  /* User must not provide more input after the first FINISH: */
17706  if (s.status === FINISH_STATE && strm.avail_in !== 0) {
17707    return err(strm, Z_BUF_ERROR);
17708  }
17709
17710  /* Start a new block or continue the current one.
17711   */
17712  if (strm.avail_in !== 0 || s.lookahead !== 0 ||
17713    (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
17714    var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
17715      (s.strategy === Z_RLE ? deflate_rle(s, flush) :
17716        configuration_table[s.level].func(s, flush));
17717
17718    if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
17719      s.status = FINISH_STATE;
17720    }
17721    if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
17722      if (strm.avail_out === 0) {
17723        s.last_flush = -1;
17724        /* avoid BUF_ERROR next call, see above */
17725      }
17726      return Z_OK;
17727      /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
17728       * of deflate should use the same flush parameter to make sure
17729       * that the flush is complete. So we don't have to output an
17730       * empty block here, this will be done at next call. This also
17731       * ensures that for a very small output buffer, we emit at most
17732       * one empty block.
17733       */
17734    }
17735    if (bstate === BS_BLOCK_DONE) {
17736      if (flush === Z_PARTIAL_FLUSH) {
17737        trees._tr_align(s);
17738      }
17739      else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
17740
17741        trees._tr_stored_block(s, 0, 0, false);
17742        /* For a full flush, this empty block will be recognized
17743         * as a special marker by inflate_sync().
17744         */
17745        if (flush === Z_FULL_FLUSH) {
17746          /*** CLEAR_HASH(s); ***/             /* forget history */
17747          zero(s.head); // Fill with NIL (= 0);
17748
17749          if (s.lookahead === 0) {
17750            s.strstart = 0;
17751            s.block_start = 0;
17752            s.insert = 0;
17753          }
17754        }
17755      }
17756      flush_pending(strm);
17757      if (strm.avail_out === 0) {
17758        s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
17759        return Z_OK;
17760      }
17761    }
17762  }
17763  //Assert(strm->avail_out > 0, "bug2");
17764  //if (strm.avail_out <= 0) { throw new Error("bug2");}
17765
17766  if (flush !== Z_FINISH) { return Z_OK; }
17767  if (s.wrap <= 0) { return Z_STREAM_END; }
17768
17769  /* Write the trailer */
17770  if (s.wrap === 2) {
17771    put_byte(s, strm.adler & 0xff);
17772    put_byte(s, (strm.adler >> 8) & 0xff);
17773    put_byte(s, (strm.adler >> 16) & 0xff);
17774    put_byte(s, (strm.adler >> 24) & 0xff);
17775    put_byte(s, strm.total_in & 0xff);
17776    put_byte(s, (strm.total_in >> 8) & 0xff);
17777    put_byte(s, (strm.total_in >> 16) & 0xff);
17778    put_byte(s, (strm.total_in >> 24) & 0xff);
17779  }
17780  else
17781  {
17782    putShortMSB(s, strm.adler >>> 16);
17783    putShortMSB(s, strm.adler & 0xffff);
17784  }
17785
17786  flush_pending(strm);
17787  /* If avail_out is zero, the application will call deflate again
17788   * to flush the rest.
17789   */
17790  if (s.wrap > 0) { s.wrap = -s.wrap; }
17791  /* write the trailer only once! */
17792  return s.pending !== 0 ? Z_OK : Z_STREAM_END;
17793}
17794
17795function deflateEnd(strm) {
17796  var status;
17797
17798  if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
17799    return Z_STREAM_ERROR;
17800  }
17801
17802  status = strm.state.status;
17803  if (status !== INIT_STATE &&
17804    status !== EXTRA_STATE &&
17805    status !== NAME_STATE &&
17806    status !== COMMENT_STATE &&
17807    status !== HCRC_STATE &&
17808    status !== BUSY_STATE &&
17809    status !== FINISH_STATE
17810  ) {
17811    return err(strm, Z_STREAM_ERROR);
17812  }
17813
17814  strm.state = null;
17815
17816  return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
17817}
17818
17819
17820/* =========================================================================
17821 * Initializes the compression dictionary from the given byte
17822 * sequence without producing any compressed output.
17823 */
17824function deflateSetDictionary(strm, dictionary) {
17825  var dictLength = dictionary.length;
17826
17827  var s;
17828  var str, n;
17829  var wrap;
17830  var avail;
17831  var next;
17832  var input;
17833  var tmpDict;
17834
17835  if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
17836    return Z_STREAM_ERROR;
17837  }
17838
17839  s = strm.state;
17840  wrap = s.wrap;
17841
17842  if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
17843    return Z_STREAM_ERROR;
17844  }
17845
17846  /* when using zlib wrappers, compute Adler-32 for provided dictionary */
17847  if (wrap === 1) {
17848    /* adler32(strm->adler, dictionary, dictLength); */
17849    strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
17850  }
17851
17852  s.wrap = 0;   /* avoid computing Adler-32 in read_buf */
17853
17854  /* if dictionary would fill window, just replace the history */
17855  if (dictLength >= s.w_size) {
17856    if (wrap === 0) {            /* already empty otherwise */
17857      /*** CLEAR_HASH(s); ***/
17858      zero(s.head); // Fill with NIL (= 0);
17859      s.strstart = 0;
17860      s.block_start = 0;
17861      s.insert = 0;
17862    }
17863    /* use the tail */
17864    // dictionary = dictionary.slice(dictLength - s.w_size);
17865    tmpDict = new utils.Buf8(s.w_size);
17866    utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
17867    dictionary = tmpDict;
17868    dictLength = s.w_size;
17869  }
17870  /* insert dictionary into window and hash */
17871  avail = strm.avail_in;
17872  next = strm.next_in;
17873  input = strm.input;
17874  strm.avail_in = dictLength;
17875  strm.next_in = 0;
17876  strm.input = dictionary;
17877  fill_window(s);
17878  while (s.lookahead >= MIN_MATCH) {
17879    str = s.strstart;
17880    n = s.lookahead - (MIN_MATCH - 1);
17881    do {
17882      /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
17883      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
17884
17885      s.prev[str & s.w_mask] = s.head[s.ins_h];
17886
17887      s.head[s.ins_h] = str;
17888      str++;
17889    } while (--n);
17890    s.strstart = str;
17891    s.lookahead = MIN_MATCH - 1;
17892    fill_window(s);
17893  }
17894  s.strstart += s.lookahead;
17895  s.block_start = s.strstart;
17896  s.insert = s.lookahead;
17897  s.lookahead = 0;
17898  s.match_length = s.prev_length = MIN_MATCH - 1;
17899  s.match_available = 0;
17900  strm.next_in = next;
17901  strm.input = input;
17902  strm.avail_in = avail;
17903  s.wrap = wrap;
17904  return Z_OK;
17905}
17906
17907
17908exports.deflateInit = deflateInit;
17909exports.deflateInit2 = deflateInit2;
17910exports.deflateReset = deflateReset;
17911exports.deflateResetKeep = deflateResetKeep;
17912exports.deflateSetHeader = deflateSetHeader;
17913exports.deflate = deflate;
17914exports.deflateEnd = deflateEnd;
17915exports.deflateSetDictionary = deflateSetDictionary;
17916exports.deflateInfo = 'pako deflate (from Nodeca project)';
17917
17918/* Not implemented
17919exports.deflateBound = deflateBound;
17920exports.deflateCopy = deflateCopy;
17921exports.deflateParams = deflateParams;
17922exports.deflatePending = deflatePending;
17923exports.deflatePrime = deflatePrime;
17924exports.deflateTune = deflateTune;
17925*/
17926
17927},{"../utils/common":54,"./adler32":56,"./crc32":58,"./messages":64,"./trees":65}],60:[function(require,module,exports){
17928'use strict';
17929
17930// (C) 1995-2013 Jean-loup Gailly and Mark Adler
17931// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
17932//
17933// This software is provided 'as-is', without any express or implied
17934// warranty. In no event will the authors be held liable for any damages
17935// arising from the use of this software.
17936//
17937// Permission is granted to anyone to use this software for any purpose,
17938// including commercial applications, and to alter it and redistribute it
17939// freely, subject to the following restrictions:
17940//
17941// 1. The origin of this software must not be misrepresented; you must not
17942//   claim that you wrote the original software. If you use this software
17943//   in a product, an acknowledgment in the product documentation would be
17944//   appreciated but is not required.
17945// 2. Altered source versions must be plainly marked as such, and must not be
17946//   misrepresented as being the original software.
17947// 3. This notice may not be removed or altered from any source distribution.
17948
17949function GZheader() {
17950  /* true if compressed data believed to be text */
17951  this.text       = 0;
17952  /* modification time */
17953  this.time       = 0;
17954  /* extra flags (not used when writing a gzip file) */
17955  this.xflags     = 0;
17956  /* operating system */
17957  this.os         = 0;
17958  /* pointer to extra field or Z_NULL if none */
17959  this.extra      = null;
17960  /* extra field length (valid if extra != Z_NULL) */
17961  this.extra_len  = 0; // Actually, we don't need it in JS,
17962                       // but leave for few code modifications
17963
17964  //
17965  // Setup limits is not necessary because in js we should not preallocate memory
17966  // for inflate use constant limit in 65536 bytes
17967  //
17968
17969  /* space at extra (only when reading header) */
17970  // this.extra_max  = 0;
17971  /* pointer to zero-terminated file name or Z_NULL */
17972  this.name       = '';
17973  /* space at name (only when reading header) */
17974  // this.name_max   = 0;
17975  /* pointer to zero-terminated comment or Z_NULL */
17976  this.comment    = '';
17977  /* space at comment (only when reading header) */
17978  // this.comm_max   = 0;
17979  /* true if there was or will be a header crc */
17980  this.hcrc       = 0;
17981  /* true when done reading gzip header (not used when writing a gzip file) */
17982  this.done       = false;
17983}
17984
17985module.exports = GZheader;
17986
17987},{}],61:[function(require,module,exports){
17988'use strict';
17989
17990// (C) 1995-2013 Jean-loup Gailly and Mark Adler
17991// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
17992//
17993// This software is provided 'as-is', without any express or implied
17994// warranty. In no event will the authors be held liable for any damages
17995// arising from the use of this software.
17996//
17997// Permission is granted to anyone to use this software for any purpose,
17998// including commercial applications, and to alter it and redistribute it
17999// freely, subject to the following restrictions:
18000//
18001// 1. The origin of this software must not be misrepresented; you must not
18002//   claim that you wrote the original software. If you use this software
18003//   in a product, an acknowledgment in the product documentation would be
18004//   appreciated but is not required.
18005// 2. Altered source versions must be plainly marked as such, and must not be
18006//   misrepresented as being the original software.
18007// 3. This notice may not be removed or altered from any source distribution.
18008
18009// See state defs from inflate.js
18010var BAD = 30;       /* got a data error -- remain here until reset */
18011var TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
18012
18013/*
18014   Decode literal, length, and distance codes and write out the resulting
18015   literal and match bytes until either not enough input or output is
18016   available, an end-of-block is encountered, or a data error is encountered.
18017   When large enough input and output buffers are supplied to inflate(), for
18018   example, a 16K input buffer and a 64K output buffer, more than 95% of the
18019   inflate execution time is spent in this routine.
18020
18021   Entry assumptions:
18022
18023        state.mode === LEN
18024        strm.avail_in >= 6
18025        strm.avail_out >= 258
18026        start >= strm.avail_out
18027        state.bits < 8
18028
18029   On return, state.mode is one of:
18030
18031        LEN -- ran out of enough output space or enough available input
18032        TYPE -- reached end of block code, inflate() to interpret next block
18033        BAD -- error in block data
18034
18035   Notes:
18036
18037    - The maximum input bits used by a length/distance pair is 15 bits for the
18038      length code, 5 bits for the length extra, 15 bits for the distance code,
18039      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
18040      Therefore if strm.avail_in >= 6, then there is enough input to avoid
18041      checking for available input while decoding.
18042
18043    - The maximum bytes that a single length/distance pair can output is 258
18044      bytes, which is the maximum length that can be coded.  inflate_fast()
18045      requires strm.avail_out >= 258 for each loop to avoid checking for
18046      output space.
18047 */
18048module.exports = function inflate_fast(strm, start) {
18049  var state;
18050  var _in;                    /* local strm.input */
18051  var last;                   /* have enough input while in < last */
18052  var _out;                   /* local strm.output */
18053  var beg;                    /* inflate()'s initial strm.output */
18054  var end;                    /* while out < end, enough space available */
18055//#ifdef INFLATE_STRICT
18056  var dmax;                   /* maximum distance from zlib header */
18057//#endif
18058  var wsize;                  /* window size or zero if not using window */
18059  var whave;                  /* valid bytes in the window */
18060  var wnext;                  /* window write index */
18061  // Use `s_window` instead `window`, avoid conflict with instrumentation tools
18062  var s_window;               /* allocated sliding window, if wsize != 0 */
18063  var hold;                   /* local strm.hold */
18064  var bits;                   /* local strm.bits */
18065  var lcode;                  /* local strm.lencode */
18066  var dcode;                  /* local strm.distcode */
18067  var lmask;                  /* mask for first level of length codes */
18068  var dmask;                  /* mask for first level of distance codes */
18069  var here;                   /* retrieved table entry */
18070  var op;                     /* code bits, operation, extra bits, or */
18071                              /*  window position, window bytes to copy */
18072  var len;                    /* match length, unused bytes */
18073  var dist;                   /* match distance */
18074  var from;                   /* where to copy match from */
18075  var from_source;
18076
18077
18078  var input, output; // JS specific, because we have no pointers
18079
18080  /* copy state to local variables */
18081  state = strm.state;
18082  //here = state.here;
18083  _in = strm.next_in;
18084  input = strm.input;
18085  last = _in + (strm.avail_in - 5);
18086  _out = strm.next_out;
18087  output = strm.output;
18088  beg = _out - (start - strm.avail_out);
18089  end = _out + (strm.avail_out - 257);
18090//#ifdef INFLATE_STRICT
18091  dmax = state.dmax;
18092//#endif
18093  wsize = state.wsize;
18094  whave = state.whave;
18095  wnext = state.wnext;
18096  s_window = state.window;
18097  hold = state.hold;
18098  bits = state.bits;
18099  lcode = state.lencode;
18100  dcode = state.distcode;
18101  lmask = (1 << state.lenbits) - 1;
18102  dmask = (1 << state.distbits) - 1;
18103
18104
18105  /* decode literals and length/distances until end-of-block or not enough
18106     input data or output space */
18107
18108  top:
18109  do {
18110    if (bits < 15) {
18111      hold += input[_in++] << bits;
18112      bits += 8;
18113      hold += input[_in++] << bits;
18114      bits += 8;
18115    }
18116
18117    here = lcode[hold & lmask];
18118
18119    dolen:
18120    for (;;) { // Goto emulation
18121      op = here >>> 24/*here.bits*/;
18122      hold >>>= op;
18123      bits -= op;
18124      op = (here >>> 16) & 0xff/*here.op*/;
18125      if (op === 0) {                          /* literal */
18126        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
18127        //        "inflate:         literal '%c'\n" :
18128        //        "inflate:         literal 0x%02x\n", here.val));
18129        output[_out++] = here & 0xffff/*here.val*/;
18130      }
18131      else if (op & 16) {                     /* length base */
18132        len = here & 0xffff/*here.val*/;
18133        op &= 15;                           /* number of extra bits */
18134        if (op) {
18135          if (bits < op) {
18136            hold += input[_in++] << bits;
18137            bits += 8;
18138          }
18139          len += hold & ((1 << op) - 1);
18140          hold >>>= op;
18141          bits -= op;
18142        }
18143        //Tracevv((stderr, "inflate:         length %u\n", len));
18144        if (bits < 15) {
18145          hold += input[_in++] << bits;
18146          bits += 8;
18147          hold += input[_in++] << bits;
18148          bits += 8;
18149        }
18150        here = dcode[hold & dmask];
18151
18152        dodist:
18153        for (;;) { // goto emulation
18154          op = here >>> 24/*here.bits*/;
18155          hold >>>= op;
18156          bits -= op;
18157          op = (here >>> 16) & 0xff/*here.op*/;
18158
18159          if (op & 16) {                      /* distance base */
18160            dist = here & 0xffff/*here.val*/;
18161            op &= 15;                       /* number of extra bits */
18162            if (bits < op) {
18163              hold += input[_in++] << bits;
18164              bits += 8;
18165              if (bits < op) {
18166                hold += input[_in++] << bits;
18167                bits += 8;
18168              }
18169            }
18170            dist += hold & ((1 << op) - 1);
18171//#ifdef INFLATE_STRICT
18172            if (dist > dmax) {
18173              strm.msg = 'invalid distance too far back';
18174              state.mode = BAD;
18175              break top;
18176            }
18177//#endif
18178            hold >>>= op;
18179            bits -= op;
18180            //Tracevv((stderr, "inflate:         distance %u\n", dist));
18181            op = _out - beg;                /* max distance in output */
18182            if (dist > op) {                /* see if copy from window */
18183              op = dist - op;               /* distance back in window */
18184              if (op > whave) {
18185                if (state.sane) {
18186                  strm.msg = 'invalid distance too far back';
18187                  state.mode = BAD;
18188                  break top;
18189                }
18190
18191// (!) This block is disabled in zlib defaults,
18192// don't enable it for binary compatibility
18193//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
18194//                if (len <= op - whave) {
18195//                  do {
18196//                    output[_out++] = 0;
18197//                  } while (--len);
18198//                  continue top;
18199//                }
18200//                len -= op - whave;
18201//                do {
18202//                  output[_out++] = 0;
18203//                } while (--op > whave);
18204//                if (op === 0) {
18205//                  from = _out - dist;
18206//                  do {
18207//                    output[_out++] = output[from++];
18208//                  } while (--len);
18209//                  continue top;
18210//                }
18211//#endif
18212              }
18213              from = 0; // window index
18214              from_source = s_window;
18215              if (wnext === 0) {           /* very common case */
18216                from += wsize - op;
18217                if (op < len) {         /* some from window */
18218                  len -= op;
18219                  do {
18220                    output[_out++] = s_window[from++];
18221                  } while (--op);
18222                  from = _out - dist;  /* rest from output */
18223                  from_source = output;
18224                }
18225              }
18226              else if (wnext < op) {      /* wrap around window */
18227                from += wsize + wnext - op;
18228                op -= wnext;
18229                if (op < len) {         /* some from end of window */
18230                  len -= op;
18231                  do {
18232                    output[_out++] = s_window[from++];
18233                  } while (--op);
18234                  from = 0;
18235                  if (wnext < len) {  /* some from start of window */
18236                    op = wnext;
18237                    len -= op;
18238                    do {
18239                      output[_out++] = s_window[from++];
18240                    } while (--op);
18241                    from = _out - dist;      /* rest from output */
18242                    from_source = output;
18243                  }
18244                }
18245              }
18246              else {                      /* contiguous in window */
18247                from += wnext - op;
18248                if (op < len) {         /* some from window */
18249                  len -= op;
18250                  do {
18251                    output[_out++] = s_window[from++];
18252                  } while (--op);
18253                  from = _out - dist;  /* rest from output */
18254                  from_source = output;
18255                }
18256              }
18257              while (len > 2) {
18258                output[_out++] = from_source[from++];
18259                output[_out++] = from_source[from++];
18260                output[_out++] = from_source[from++];
18261                len -= 3;
18262              }
18263              if (len) {
18264                output[_out++] = from_source[from++];
18265                if (len > 1) {
18266                  output[_out++] = from_source[from++];
18267                }
18268              }
18269            }
18270            else {
18271              from = _out - dist;          /* copy direct from output */
18272              do {                        /* minimum length is three */
18273                output[_out++] = output[from++];
18274                output[_out++] = output[from++];
18275                output[_out++] = output[from++];
18276                len -= 3;
18277              } while (len > 2);
18278              if (len) {
18279                output[_out++] = output[from++];
18280                if (len > 1) {
18281                  output[_out++] = output[from++];
18282                }
18283              }
18284            }
18285          }
18286          else if ((op & 64) === 0) {          /* 2nd level distance code */
18287            here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
18288            continue dodist;
18289          }
18290          else {
18291            strm.msg = 'invalid distance code';
18292            state.mode = BAD;
18293            break top;
18294          }
18295
18296          break; // need to emulate goto via "continue"
18297        }
18298      }
18299      else if ((op & 64) === 0) {              /* 2nd level length code */
18300        here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
18301        continue dolen;
18302      }
18303      else if (op & 32) {                     /* end-of-block */
18304        //Tracevv((stderr, "inflate:         end of block\n"));
18305        state.mode = TYPE;
18306        break top;
18307      }
18308      else {
18309        strm.msg = 'invalid literal/length code';
18310        state.mode = BAD;
18311        break top;
18312      }
18313
18314      break; // need to emulate goto via "continue"
18315    }
18316  } while (_in < last && _out < end);
18317
18318  /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
18319  len = bits >> 3;
18320  _in -= len;
18321  bits -= len << 3;
18322  hold &= (1 << bits) - 1;
18323
18324  /* update state and return */
18325  strm.next_in = _in;
18326  strm.next_out = _out;
18327  strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
18328  strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
18329  state.hold = hold;
18330  state.bits = bits;
18331  return;
18332};
18333
18334},{}],62:[function(require,module,exports){
18335'use strict';
18336
18337// (C) 1995-2013 Jean-loup Gailly and Mark Adler
18338// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
18339//
18340// This software is provided 'as-is', without any express or implied
18341// warranty. In no event will the authors be held liable for any damages
18342// arising from the use of this software.
18343//
18344// Permission is granted to anyone to use this software for any purpose,
18345// including commercial applications, and to alter it and redistribute it
18346// freely, subject to the following restrictions:
18347//
18348// 1. The origin of this software must not be misrepresented; you must not
18349//   claim that you wrote the original software. If you use this software
18350//   in a product, an acknowledgment in the product documentation would be
18351//   appreciated but is not required.
18352// 2. Altered source versions must be plainly marked as such, and must not be
18353//   misrepresented as being the original software.
18354// 3. This notice may not be removed or altered from any source distribution.
18355
18356var utils         = require('../utils/common');
18357var adler32       = require('./adler32');
18358var crc32         = require('./crc32');
18359var inflate_fast  = require('./inffast');
18360var inflate_table = require('./inftrees');
18361
18362var CODES = 0;
18363var LENS = 1;
18364var DISTS = 2;
18365
18366/* Public constants ==========================================================*/
18367/* ===========================================================================*/
18368
18369
18370/* Allowed flush values; see deflate() and inflate() below for details */
18371//var Z_NO_FLUSH      = 0;
18372//var Z_PARTIAL_FLUSH = 1;
18373//var Z_SYNC_FLUSH    = 2;
18374//var Z_FULL_FLUSH    = 3;
18375var Z_FINISH        = 4;
18376var Z_BLOCK         = 5;
18377var Z_TREES         = 6;
18378
18379
18380/* Return codes for the compression/decompression functions. Negative values
18381 * are errors, positive values are used for special but normal events.
18382 */
18383var Z_OK            = 0;
18384var Z_STREAM_END    = 1;
18385var Z_NEED_DICT     = 2;
18386//var Z_ERRNO         = -1;
18387var Z_STREAM_ERROR  = -2;
18388var Z_DATA_ERROR    = -3;
18389var Z_MEM_ERROR     = -4;
18390var Z_BUF_ERROR     = -5;
18391//var Z_VERSION_ERROR = -6;
18392
18393/* The deflate compression method */
18394var Z_DEFLATED  = 8;
18395
18396
18397/* STATES ====================================================================*/
18398/* ===========================================================================*/
18399
18400
18401var    HEAD = 1;       /* i: waiting for magic header */
18402var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
18403var    TIME = 3;       /* i: waiting for modification time (gzip) */
18404var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
18405var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
18406var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
18407var    NAME = 7;       /* i: waiting for end of file name (gzip) */
18408var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
18409var    HCRC = 9;       /* i: waiting for header crc (gzip) */
18410var    DICTID = 10;    /* i: waiting for dictionary check value */
18411var    DICT = 11;      /* waiting for inflateSetDictionary() call */
18412var        TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
18413var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
18414var        STORED = 14;    /* i: waiting for stored size (length and complement) */
18415var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
18416var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
18417var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
18418var        LENLENS = 18;   /* i: waiting for code length code lengths */
18419var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
18420var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
18421var            LEN = 21;       /* i: waiting for length/lit/eob code */
18422var            LENEXT = 22;    /* i: waiting for length extra bits */
18423var            DIST = 23;      /* i: waiting for distance code */
18424var            DISTEXT = 24;   /* i: waiting for distance extra bits */
18425var            MATCH = 25;     /* o: waiting for output space to copy string */
18426var            LIT = 26;       /* o: waiting for output space to write literal */
18427var    CHECK = 27;     /* i: waiting for 32-bit check value */
18428var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
18429var    DONE = 29;      /* finished check, done -- remain here until reset */
18430var    BAD = 30;       /* got a data error -- remain here until reset */
18431var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
18432var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */
18433
18434/* ===========================================================================*/
18435
18436
18437
18438var ENOUGH_LENS = 852;
18439var ENOUGH_DISTS = 592;
18440//var ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);
18441
18442var MAX_WBITS = 15;
18443/* 32K LZ77 window */
18444var DEF_WBITS = MAX_WBITS;
18445
18446
18447function zswap32(q) {
18448  return  (((q >>> 24) & 0xff) +
18449          ((q >>> 8) & 0xff00) +
18450          ((q & 0xff00) << 8) +
18451          ((q & 0xff) << 24));
18452}
18453
18454
18455function InflateState() {
18456  this.mode = 0;             /* current inflate mode */
18457  this.last = false;          /* true if processing last block */
18458  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
18459  this.havedict = false;      /* true if dictionary provided */
18460  this.flags = 0;             /* gzip header method and flags (0 if zlib) */
18461  this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
18462  this.check = 0;             /* protected copy of check value */
18463  this.total = 0;             /* protected copy of output count */
18464  // TODO: may be {}
18465  this.head = null;           /* where to save gzip header information */
18466
18467  /* sliding window */
18468  this.wbits = 0;             /* log base 2 of requested window size */
18469  this.wsize = 0;             /* window size or zero if not using window */
18470  this.whave = 0;             /* valid bytes in the window */
18471  this.wnext = 0;             /* window write index */
18472  this.window = null;         /* allocated sliding window, if needed */
18473
18474  /* bit accumulator */
18475  this.hold = 0;              /* input bit accumulator */
18476  this.bits = 0;              /* number of bits in "in" */
18477
18478  /* for string and stored block copying */
18479  this.length = 0;            /* literal or length of data to copy */
18480  this.offset = 0;            /* distance back to copy string from */
18481
18482  /* for table and code decoding */
18483  this.extra = 0;             /* extra bits needed */
18484
18485  /* fixed and dynamic code tables */
18486  this.lencode = null;          /* starting table for length/literal codes */
18487  this.distcode = null;         /* starting table for distance codes */
18488  this.lenbits = 0;           /* index bits for lencode */
18489  this.distbits = 0;          /* index bits for distcode */
18490
18491  /* dynamic table building */
18492  this.ncode = 0;             /* number of code length code lengths */
18493  this.nlen = 0;              /* number of length code lengths */
18494  this.ndist = 0;             /* number of distance code lengths */
18495  this.have = 0;              /* number of code lengths in lens[] */
18496  this.next = null;              /* next available space in codes[] */
18497
18498  this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
18499  this.work = new utils.Buf16(288); /* work area for code table building */
18500
18501  /*
18502   because we don't have pointers in js, we use lencode and distcode directly
18503   as buffers so we don't need codes
18504  */
18505  //this.codes = new utils.Buf32(ENOUGH);       /* space for code tables */
18506  this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
18507  this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
18508  this.sane = 0;                   /* if false, allow invalid distance too far */
18509  this.back = 0;                   /* bits back of last unprocessed length/lit */
18510  this.was = 0;                    /* initial length of match */
18511}
18512
18513function inflateResetKeep(strm) {
18514  var state;
18515
18516  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
18517  state = strm.state;
18518  strm.total_in = strm.total_out = state.total = 0;
18519  strm.msg = ''; /*Z_NULL*/
18520  if (state.wrap) {       /* to support ill-conceived Java test suite */
18521    strm.adler = state.wrap & 1;
18522  }
18523  state.mode = HEAD;
18524  state.last = 0;
18525  state.havedict = 0;
18526  state.dmax = 32768;
18527  state.head = null/*Z_NULL*/;
18528  state.hold = 0;
18529  state.bits = 0;
18530  //state.lencode = state.distcode = state.next = state.codes;
18531  state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
18532  state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
18533
18534  state.sane = 1;
18535  state.back = -1;
18536  //Tracev((stderr, "inflate: reset\n"));
18537  return Z_OK;
18538}
18539
18540function inflateReset(strm) {
18541  var state;
18542
18543  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
18544  state = strm.state;
18545  state.wsize = 0;
18546  state.whave = 0;
18547  state.wnext = 0;
18548  return inflateResetKeep(strm);
18549
18550}
18551
18552function inflateReset2(strm, windowBits) {
18553  var wrap;
18554  var state;
18555
18556  /* get the state */
18557  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
18558  state = strm.state;
18559
18560  /* extract wrap request from windowBits parameter */
18561  if (windowBits < 0) {
18562    wrap = 0;
18563    windowBits = -windowBits;
18564  }
18565  else {
18566    wrap = (windowBits >> 4) + 1;
18567    if (windowBits < 48) {
18568      windowBits &= 15;
18569    }
18570  }
18571
18572  /* set number of window bits, free window if different */
18573  if (windowBits && (windowBits < 8 || windowBits > 15)) {
18574    return Z_STREAM_ERROR;
18575  }
18576  if (state.window !== null && state.wbits !== windowBits) {
18577    state.window = null;
18578  }
18579
18580  /* update state and reset the rest of it */
18581  state.wrap = wrap;
18582  state.wbits = windowBits;
18583  return inflateReset(strm);
18584}
18585
18586function inflateInit2(strm, windowBits) {
18587  var ret;
18588  var state;
18589
18590  if (!strm) { return Z_STREAM_ERROR; }
18591  //strm.msg = Z_NULL;                 /* in case we return an error */
18592
18593  state = new InflateState();
18594
18595  //if (state === Z_NULL) return Z_MEM_ERROR;
18596  //Tracev((stderr, "inflate: allocated\n"));
18597  strm.state = state;
18598  state.window = null/*Z_NULL*/;
18599  ret = inflateReset2(strm, windowBits);
18600  if (ret !== Z_OK) {
18601    strm.state = null/*Z_NULL*/;
18602  }
18603  return ret;
18604}
18605
18606function inflateInit(strm) {
18607  return inflateInit2(strm, DEF_WBITS);
18608}
18609
18610
18611/*
18612 Return state with length and distance decoding tables and index sizes set to
18613 fixed code decoding.  Normally this returns fixed tables from inffixed.h.
18614 If BUILDFIXED is defined, then instead this routine builds the tables the
18615 first time it's called, and returns those tables the first time and
18616 thereafter.  This reduces the size of the code by about 2K bytes, in
18617 exchange for a little execution time.  However, BUILDFIXED should not be
18618 used for threaded applications, since the rewriting of the tables and virgin
18619 may not be thread-safe.
18620 */
18621var virgin = true;
18622
18623var lenfix, distfix; // We have no pointers in JS, so keep tables separate
18624
18625function fixedtables(state) {
18626  /* build fixed huffman tables if first call (may not be thread safe) */
18627  if (virgin) {
18628    var sym;
18629
18630    lenfix = new utils.Buf32(512);
18631    distfix = new utils.Buf32(32);
18632
18633    /* literal/length table */
18634    sym = 0;
18635    while (sym < 144) { state.lens[sym++] = 8; }
18636    while (sym < 256) { state.lens[sym++] = 9; }
18637    while (sym < 280) { state.lens[sym++] = 7; }
18638    while (sym < 288) { state.lens[sym++] = 8; }
18639
18640    inflate_table(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });
18641
18642    /* distance table */
18643    sym = 0;
18644    while (sym < 32) { state.lens[sym++] = 5; }
18645
18646    inflate_table(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });
18647
18648    /* do this just once */
18649    virgin = false;
18650  }
18651
18652  state.lencode = lenfix;
18653  state.lenbits = 9;
18654  state.distcode = distfix;
18655  state.distbits = 5;
18656}
18657
18658
18659/*
18660 Update the window with the last wsize (normally 32K) bytes written before
18661 returning.  If window does not exist yet, create it.  This is only called
18662 when a window is already in use, or when output has been written during this
18663 inflate call, but the end of the deflate stream has not been reached yet.
18664 It is also called to create a window for dictionary data when a dictionary
18665 is loaded.
18666
18667 Providing output buffers larger than 32K to inflate() should provide a speed
18668 advantage, since only the last 32K of output is copied to the sliding window
18669 upon return from inflate(), and since all distances after the first 32K of
18670 output will fall in the output data, making match copies simpler and faster.
18671 The advantage may be dependent on the size of the processor's data caches.
18672 */
18673function updatewindow(strm, src, end, copy) {
18674  var dist;
18675  var state = strm.state;
18676
18677  /* if it hasn't been done already, allocate space for the window */
18678  if (state.window === null) {
18679    state.wsize = 1 << state.wbits;
18680    state.wnext = 0;
18681    state.whave = 0;
18682
18683    state.window = new utils.Buf8(state.wsize);
18684  }
18685
18686  /* copy state->wsize or less output bytes into the circular window */
18687  if (copy >= state.wsize) {
18688    utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
18689    state.wnext = 0;
18690    state.whave = state.wsize;
18691  }
18692  else {
18693    dist = state.wsize - state.wnext;
18694    if (dist > copy) {
18695      dist = copy;
18696    }
18697    //zmemcpy(state->window + state->wnext, end - copy, dist);
18698    utils.arraySet(state.window, src, end - copy, dist, state.wnext);
18699    copy -= dist;
18700    if (copy) {
18701      //zmemcpy(state->window, end - copy, copy);
18702      utils.arraySet(state.window, src, end - copy, copy, 0);
18703      state.wnext = copy;
18704      state.whave = state.wsize;
18705    }
18706    else {
18707      state.wnext += dist;
18708      if (state.wnext === state.wsize) { state.wnext = 0; }
18709      if (state.whave < state.wsize) { state.whave += dist; }
18710    }
18711  }
18712  return 0;
18713}
18714
18715function inflate(strm, flush) {
18716  var state;
18717  var input, output;          // input/output buffers
18718  var next;                   /* next input INDEX */
18719  var put;                    /* next output INDEX */
18720  var have, left;             /* available input and output */
18721  var hold;                   /* bit buffer */
18722  var bits;                   /* bits in bit buffer */
18723  var _in, _out;              /* save starting available input and output */
18724  var copy;                   /* number of stored or match bytes to copy */
18725  var from;                   /* where to copy match bytes from */
18726  var from_source;
18727  var here = 0;               /* current decoding table entry */
18728  var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
18729  //var last;                   /* parent table entry */
18730  var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
18731  var len;                    /* length to copy for repeats, bits to drop */
18732  var ret;                    /* return code */
18733  var hbuf = new utils.Buf8(4);    /* buffer for gzip header crc calculation */
18734  var opts;
18735
18736  var n; // temporary var for NEED_BITS
18737
18738  var order = /* permutation of code lengths */
18739    [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
18740
18741
18742  if (!strm || !strm.state || !strm.output ||
18743      (!strm.input && strm.avail_in !== 0)) {
18744    return Z_STREAM_ERROR;
18745  }
18746
18747  state = strm.state;
18748  if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */
18749
18750
18751  //--- LOAD() ---
18752  put = strm.next_out;
18753  output = strm.output;
18754  left = strm.avail_out;
18755  next = strm.next_in;
18756  input = strm.input;
18757  have = strm.avail_in;
18758  hold = state.hold;
18759  bits = state.bits;
18760  //---
18761
18762  _in = have;
18763  _out = left;
18764  ret = Z_OK;
18765
18766  inf_leave: // goto emulation
18767  for (;;) {
18768    switch (state.mode) {
18769      case HEAD:
18770        if (state.wrap === 0) {
18771          state.mode = TYPEDO;
18772          break;
18773        }
18774        //=== NEEDBITS(16);
18775        while (bits < 16) {
18776          if (have === 0) { break inf_leave; }
18777          have--;
18778          hold += input[next++] << bits;
18779          bits += 8;
18780        }
18781        //===//
18782        if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
18783          state.check = 0/*crc32(0L, Z_NULL, 0)*/;
18784          //=== CRC2(state.check, hold);
18785          hbuf[0] = hold & 0xff;
18786          hbuf[1] = (hold >>> 8) & 0xff;
18787          state.check = crc32(state.check, hbuf, 2, 0);
18788          //===//
18789
18790          //=== INITBITS();
18791          hold = 0;
18792          bits = 0;
18793          //===//
18794          state.mode = FLAGS;
18795          break;
18796        }
18797        state.flags = 0;           /* expect zlib header */
18798        if (state.head) {
18799          state.head.done = false;
18800        }
18801        if (!(state.wrap & 1) ||   /* check if zlib header allowed */
18802          (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
18803          strm.msg = 'incorrect header check';
18804          state.mode = BAD;
18805          break;
18806        }
18807        if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
18808          strm.msg = 'unknown compression method';
18809          state.mode = BAD;
18810          break;
18811        }
18812        //--- DROPBITS(4) ---//
18813        hold >>>= 4;
18814        bits -= 4;
18815        //---//
18816        len = (hold & 0x0f)/*BITS(4)*/ + 8;
18817        if (state.wbits === 0) {
18818          state.wbits = len;
18819        }
18820        else if (len > state.wbits) {
18821          strm.msg = 'invalid window size';
18822          state.mode = BAD;
18823          break;
18824        }
18825        state.dmax = 1 << len;
18826        //Tracev((stderr, "inflate:   zlib header ok\n"));
18827        strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
18828        state.mode = hold & 0x200 ? DICTID : TYPE;
18829        //=== INITBITS();
18830        hold = 0;
18831        bits = 0;
18832        //===//
18833        break;
18834      case FLAGS:
18835        //=== NEEDBITS(16); */
18836        while (bits < 16) {
18837          if (have === 0) { break inf_leave; }
18838          have--;
18839          hold += input[next++] << bits;
18840          bits += 8;
18841        }
18842        //===//
18843        state.flags = hold;
18844        if ((state.flags & 0xff) !== Z_DEFLATED) {
18845          strm.msg = 'unknown compression method';
18846          state.mode = BAD;
18847          break;
18848        }
18849        if (state.flags & 0xe000) {
18850          strm.msg = 'unknown header flags set';
18851          state.mode = BAD;
18852          break;
18853        }
18854        if (state.head) {
18855          state.head.text = ((hold >> 8) & 1);
18856        }
18857        if (state.flags & 0x0200) {
18858          //=== CRC2(state.check, hold);
18859          hbuf[0] = hold & 0xff;
18860          hbuf[1] = (hold >>> 8) & 0xff;
18861          state.check = crc32(state.check, hbuf, 2, 0);
18862          //===//
18863        }
18864        //=== INITBITS();
18865        hold = 0;
18866        bits = 0;
18867        //===//
18868        state.mode = TIME;
18869        /* falls through */
18870      case TIME:
18871        //=== NEEDBITS(32); */
18872        while (bits < 32) {
18873          if (have === 0) { break inf_leave; }
18874          have--;
18875          hold += input[next++] << bits;
18876          bits += 8;
18877        }
18878        //===//
18879        if (state.head) {
18880          state.head.time = hold;
18881        }
18882        if (state.flags & 0x0200) {
18883          //=== CRC4(state.check, hold)
18884          hbuf[0] = hold & 0xff;
18885          hbuf[1] = (hold >>> 8) & 0xff;
18886          hbuf[2] = (hold >>> 16) & 0xff;
18887          hbuf[3] = (hold >>> 24) & 0xff;
18888          state.check = crc32(state.check, hbuf, 4, 0);
18889          //===
18890        }
18891        //=== INITBITS();
18892        hold = 0;
18893        bits = 0;
18894        //===//
18895        state.mode = OS;
18896        /* falls through */
18897      case OS:
18898        //=== NEEDBITS(16); */
18899        while (bits < 16) {
18900          if (have === 0) { break inf_leave; }
18901          have--;
18902          hold += input[next++] << bits;
18903          bits += 8;
18904        }
18905        //===//
18906        if (state.head) {
18907          state.head.xflags = (hold & 0xff);
18908          state.head.os = (hold >> 8);
18909        }
18910        if (state.flags & 0x0200) {
18911          //=== CRC2(state.check, hold);
18912          hbuf[0] = hold & 0xff;
18913          hbuf[1] = (hold >>> 8) & 0xff;
18914          state.check = crc32(state.check, hbuf, 2, 0);
18915          //===//
18916        }
18917        //=== INITBITS();
18918        hold = 0;
18919        bits = 0;
18920        //===//
18921        state.mode = EXLEN;
18922        /* falls through */
18923      case EXLEN:
18924        if (state.flags & 0x0400) {
18925          //=== NEEDBITS(16); */
18926          while (bits < 16) {
18927            if (have === 0) { break inf_leave; }
18928            have--;
18929            hold += input[next++] << bits;
18930            bits += 8;
18931          }
18932          //===//
18933          state.length = hold;
18934          if (state.head) {
18935            state.head.extra_len = hold;
18936          }
18937          if (state.flags & 0x0200) {
18938            //=== CRC2(state.check, hold);
18939            hbuf[0] = hold & 0xff;
18940            hbuf[1] = (hold >>> 8) & 0xff;
18941            state.check = crc32(state.check, hbuf, 2, 0);
18942            //===//
18943          }
18944          //=== INITBITS();
18945          hold = 0;
18946          bits = 0;
18947          //===//
18948        }
18949        else if (state.head) {
18950          state.head.extra = null/*Z_NULL*/;
18951        }
18952        state.mode = EXTRA;
18953        /* falls through */
18954      case EXTRA:
18955        if (state.flags & 0x0400) {
18956          copy = state.length;
18957          if (copy > have) { copy = have; }
18958          if (copy) {
18959            if (state.head) {
18960              len = state.head.extra_len - state.length;
18961              if (!state.head.extra) {
18962                // Use untyped array for more convenient processing later
18963                state.head.extra = new Array(state.head.extra_len);
18964              }
18965              utils.arraySet(
18966                state.head.extra,
18967                input,
18968                next,
18969                // extra field is limited to 65536 bytes
18970                // - no need for additional size check
18971                copy,
18972                /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
18973                len
18974              );
18975              //zmemcpy(state.head.extra + len, next,
18976              //        len + copy > state.head.extra_max ?
18977              //        state.head.extra_max - len : copy);
18978            }
18979            if (state.flags & 0x0200) {
18980              state.check = crc32(state.check, input, copy, next);
18981            }
18982            have -= copy;
18983            next += copy;
18984            state.length -= copy;
18985          }
18986          if (state.length) { break inf_leave; }
18987        }
18988        state.length = 0;
18989        state.mode = NAME;
18990        /* falls through */
18991      case NAME:
18992        if (state.flags & 0x0800) {
18993          if (have === 0) { break inf_leave; }
18994          copy = 0;
18995          do {
18996            // TODO: 2 or 1 bytes?
18997            len = input[next + copy++];
18998            /* use constant limit because in js we should not preallocate memory */
18999            if (state.head && len &&
19000                (state.length < 65536 /*state.head.name_max*/)) {
19001              state.head.name += String.fromCharCode(len);
19002            }
19003          } while (len && copy < have);
19004
19005          if (state.flags & 0x0200) {
19006            state.check = crc32(state.check, input, copy, next);
19007          }
19008          have -= copy;
19009          next += copy;
19010          if (len) { break inf_leave; }
19011        }
19012        else if (state.head) {
19013          state.head.name = null;
19014        }
19015        state.length = 0;
19016        state.mode = COMMENT;
19017        /* falls through */
19018      case COMMENT:
19019        if (state.flags & 0x1000) {
19020          if (have === 0) { break inf_leave; }
19021          copy = 0;
19022          do {
19023            len = input[next + copy++];
19024            /* use constant limit because in js we should not preallocate memory */
19025            if (state.head && len &&
19026                (state.length < 65536 /*state.head.comm_max*/)) {
19027              state.head.comment += String.fromCharCode(len);
19028            }
19029          } while (len && copy < have);
19030          if (state.flags & 0x0200) {
19031            state.check = crc32(state.check, input, copy, next);
19032          }
19033          have -= copy;
19034          next += copy;
19035          if (len) { break inf_leave; }
19036        }
19037        else if (state.head) {
19038          state.head.comment = null;
19039        }
19040        state.mode = HCRC;
19041        /* falls through */
19042      case HCRC:
19043        if (state.flags & 0x0200) {
19044          //=== NEEDBITS(16); */
19045          while (bits < 16) {
19046            if (have === 0) { break inf_leave; }
19047            have--;
19048            hold += input[next++] << bits;
19049            bits += 8;
19050          }
19051          //===//
19052          if (hold !== (state.check & 0xffff)) {
19053            strm.msg = 'header crc mismatch';
19054            state.mode = BAD;
19055            break;
19056          }
19057          //=== INITBITS();
19058          hold = 0;
19059          bits = 0;
19060          //===//
19061        }
19062        if (state.head) {
19063          state.head.hcrc = ((state.flags >> 9) & 1);
19064          state.head.done = true;
19065        }
19066        strm.adler = state.check = 0;
19067        state.mode = TYPE;
19068        break;
19069      case DICTID:
19070        //=== NEEDBITS(32); */
19071        while (bits < 32) {
19072          if (have === 0) { break inf_leave; }
19073          have--;
19074          hold += input[next++] << bits;
19075          bits += 8;
19076        }
19077        //===//
19078        strm.adler = state.check = zswap32(hold);
19079        //=== INITBITS();
19080        hold = 0;
19081        bits = 0;
19082        //===//
19083        state.mode = DICT;
19084        /* falls through */
19085      case DICT:
19086        if (state.havedict === 0) {
19087          //--- RESTORE() ---
19088          strm.next_out = put;
19089          strm.avail_out = left;
19090          strm.next_in = next;
19091          strm.avail_in = have;
19092          state.hold = hold;
19093          state.bits = bits;
19094          //---
19095          return Z_NEED_DICT;
19096        }
19097        strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
19098        state.mode = TYPE;
19099        /* falls through */
19100      case TYPE:
19101        if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
19102        /* falls through */
19103      case TYPEDO:
19104        if (state.last) {
19105          //--- BYTEBITS() ---//
19106          hold >>>= bits & 7;
19107          bits -= bits & 7;
19108          //---//
19109          state.mode = CHECK;
19110          break;
19111        }
19112        //=== NEEDBITS(3); */
19113        while (bits < 3) {
19114          if (have === 0) { break inf_leave; }
19115          have--;
19116          hold += input[next++] << bits;
19117          bits += 8;
19118        }
19119        //===//
19120        state.last = (hold & 0x01)/*BITS(1)*/;
19121        //--- DROPBITS(1) ---//
19122        hold >>>= 1;
19123        bits -= 1;
19124        //---//
19125
19126        switch ((hold & 0x03)/*BITS(2)*/) {
19127          case 0:                             /* stored block */
19128            //Tracev((stderr, "inflate:     stored block%s\n",
19129            //        state.last ? " (last)" : ""));
19130            state.mode = STORED;
19131            break;
19132          case 1:                             /* fixed block */
19133            fixedtables(state);
19134            //Tracev((stderr, "inflate:     fixed codes block%s\n",
19135            //        state.last ? " (last)" : ""));
19136            state.mode = LEN_;             /* decode codes */
19137            if (flush === Z_TREES) {
19138              //--- DROPBITS(2) ---//
19139              hold >>>= 2;
19140              bits -= 2;
19141              //---//
19142              break inf_leave;
19143            }
19144            break;
19145          case 2:                             /* dynamic block */
19146            //Tracev((stderr, "inflate:     dynamic codes block%s\n",
19147            //        state.last ? " (last)" : ""));
19148            state.mode = TABLE;
19149            break;
19150          case 3:
19151            strm.msg = 'invalid block type';
19152            state.mode = BAD;
19153        }
19154        //--- DROPBITS(2) ---//
19155        hold >>>= 2;
19156        bits -= 2;
19157        //---//
19158        break;
19159      case STORED:
19160        //--- BYTEBITS() ---// /* go to byte boundary */
19161        hold >>>= bits & 7;
19162        bits -= bits & 7;
19163        //---//
19164        //=== NEEDBITS(32); */
19165        while (bits < 32) {
19166          if (have === 0) { break inf_leave; }
19167          have--;
19168          hold += input[next++] << bits;
19169          bits += 8;
19170        }
19171        //===//
19172        if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
19173          strm.msg = 'invalid stored block lengths';
19174          state.mode = BAD;
19175          break;
19176        }
19177        state.length = hold & 0xffff;
19178        //Tracev((stderr, "inflate:       stored length %u\n",
19179        //        state.length));
19180        //=== INITBITS();
19181        hold = 0;
19182        bits = 0;
19183        //===//
19184        state.mode = COPY_;
19185        if (flush === Z_TREES) { break inf_leave; }
19186        /* falls through */
19187      case COPY_:
19188        state.mode = COPY;
19189        /* falls through */
19190      case COPY:
19191        copy = state.length;
19192        if (copy) {
19193          if (copy > have) { copy = have; }
19194          if (copy > left) { copy = left; }
19195          if (copy === 0) { break inf_leave; }
19196          //--- zmemcpy(put, next, copy); ---
19197          utils.arraySet(output, input, next, copy, put);
19198          //---//
19199          have -= copy;
19200          next += copy;
19201          left -= copy;
19202          put += copy;
19203          state.length -= copy;
19204          break;
19205        }
19206        //Tracev((stderr, "inflate:       stored end\n"));
19207        state.mode = TYPE;
19208        break;
19209      case TABLE:
19210        //=== NEEDBITS(14); */
19211        while (bits < 14) {
19212          if (have === 0) { break inf_leave; }
19213          have--;
19214          hold += input[next++] << bits;
19215          bits += 8;
19216        }
19217        //===//
19218        state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
19219        //--- DROPBITS(5) ---//
19220        hold >>>= 5;
19221        bits -= 5;
19222        //---//
19223        state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
19224        //--- DROPBITS(5) ---//
19225        hold >>>= 5;
19226        bits -= 5;
19227        //---//
19228        state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
19229        //--- DROPBITS(4) ---//
19230        hold >>>= 4;
19231        bits -= 4;
19232        //---//
19233//#ifndef PKZIP_BUG_WORKAROUND
19234        if (state.nlen > 286 || state.ndist > 30) {
19235          strm.msg = 'too many length or distance symbols';
19236          state.mode = BAD;
19237          break;
19238        }
19239//#endif
19240        //Tracev((stderr, "inflate:       table sizes ok\n"));
19241        state.have = 0;
19242        state.mode = LENLENS;
19243        /* falls through */
19244      case LENLENS:
19245        while (state.have < state.ncode) {
19246          //=== NEEDBITS(3);
19247          while (bits < 3) {
19248            if (have === 0) { break inf_leave; }
19249            have--;
19250            hold += input[next++] << bits;
19251            bits += 8;
19252          }
19253          //===//
19254          state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
19255          //--- DROPBITS(3) ---//
19256          hold >>>= 3;
19257          bits -= 3;
19258          //---//
19259        }
19260        while (state.have < 19) {
19261          state.lens[order[state.have++]] = 0;
19262        }
19263        // We have separate tables & no pointers. 2 commented lines below not needed.
19264        //state.next = state.codes;
19265        //state.lencode = state.next;
19266        // Switch to use dynamic table
19267        state.lencode = state.lendyn;
19268        state.lenbits = 7;
19269
19270        opts = { bits: state.lenbits };
19271        ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
19272        state.lenbits = opts.bits;
19273
19274        if (ret) {
19275          strm.msg = 'invalid code lengths set';
19276          state.mode = BAD;
19277          break;
19278        }
19279        //Tracev((stderr, "inflate:       code lengths ok\n"));
19280        state.have = 0;
19281        state.mode = CODELENS;
19282        /* falls through */
19283      case CODELENS:
19284        while (state.have < state.nlen + state.ndist) {
19285          for (;;) {
19286            here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
19287            here_bits = here >>> 24;
19288            here_op = (here >>> 16) & 0xff;
19289            here_val = here & 0xffff;
19290
19291            if ((here_bits) <= bits) { break; }
19292            //--- PULLBYTE() ---//
19293            if (have === 0) { break inf_leave; }
19294            have--;
19295            hold += input[next++] << bits;
19296            bits += 8;
19297            //---//
19298          }
19299          if (here_val < 16) {
19300            //--- DROPBITS(here.bits) ---//
19301            hold >>>= here_bits;
19302            bits -= here_bits;
19303            //---//
19304            state.lens[state.have++] = here_val;
19305          }
19306          else {
19307            if (here_val === 16) {
19308              //=== NEEDBITS(here.bits + 2);
19309              n = here_bits + 2;
19310              while (bits < n) {
19311                if (have === 0) { break inf_leave; }
19312                have--;
19313                hold += input[next++] << bits;
19314                bits += 8;
19315              }
19316              //===//
19317              //--- DROPBITS(here.bits) ---//
19318              hold >>>= here_bits;
19319              bits -= here_bits;
19320              //---//
19321              if (state.have === 0) {
19322                strm.msg = 'invalid bit length repeat';
19323                state.mode = BAD;
19324                break;
19325              }
19326              len = state.lens[state.have - 1];
19327              copy = 3 + (hold & 0x03);//BITS(2);
19328              //--- DROPBITS(2) ---//
19329              hold >>>= 2;
19330              bits -= 2;
19331              //---//
19332            }
19333            else if (here_val === 17) {
19334              //=== NEEDBITS(here.bits + 3);
19335              n = here_bits + 3;
19336              while (bits < n) {
19337                if (have === 0) { break inf_leave; }
19338                have--;
19339                hold += input[next++] << bits;
19340                bits += 8;
19341              }
19342              //===//
19343              //--- DROPBITS(here.bits) ---//
19344              hold >>>= here_bits;
19345              bits -= here_bits;
19346              //---//
19347              len = 0;
19348              copy = 3 + (hold & 0x07);//BITS(3);
19349              //--- DROPBITS(3) ---//
19350              hold >>>= 3;
19351              bits -= 3;
19352              //---//
19353            }
19354            else {
19355              //=== NEEDBITS(here.bits + 7);
19356              n = here_bits + 7;
19357              while (bits < n) {
19358                if (have === 0) { break inf_leave; }
19359                have--;
19360                hold += input[next++] << bits;
19361                bits += 8;
19362              }
19363              //===//
19364              //--- DROPBITS(here.bits) ---//
19365              hold >>>= here_bits;
19366              bits -= here_bits;
19367              //---//
19368              len = 0;
19369              copy = 11 + (hold & 0x7f);//BITS(7);
19370              //--- DROPBITS(7) ---//
19371              hold >>>= 7;
19372              bits -= 7;
19373              //---//
19374            }
19375            if (state.have + copy > state.nlen + state.ndist) {
19376              strm.msg = 'invalid bit length repeat';
19377              state.mode = BAD;
19378              break;
19379            }
19380            while (copy--) {
19381              state.lens[state.have++] = len;
19382            }
19383          }
19384        }
19385
19386        /* handle error breaks in while */
19387        if (state.mode === BAD) { break; }
19388
19389        /* check for end-of-block code (better have one) */
19390        if (state.lens[256] === 0) {
19391          strm.msg = 'invalid code -- missing end-of-block';
19392          state.mode = BAD;
19393          break;
19394        }
19395
19396        /* build code tables -- note: do not change the lenbits or distbits
19397           values here (9 and 6) without reading the comments in inftrees.h
19398           concerning the ENOUGH constants, which depend on those values */
19399        state.lenbits = 9;
19400
19401        opts = { bits: state.lenbits };
19402        ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
19403        // We have separate tables & no pointers. 2 commented lines below not needed.
19404        // state.next_index = opts.table_index;
19405        state.lenbits = opts.bits;
19406        // state.lencode = state.next;
19407
19408        if (ret) {
19409          strm.msg = 'invalid literal/lengths set';
19410          state.mode = BAD;
19411          break;
19412        }
19413
19414        state.distbits = 6;
19415        //state.distcode.copy(state.codes);
19416        // Switch to use dynamic table
19417        state.distcode = state.distdyn;
19418        opts = { bits: state.distbits };
19419        ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
19420        // We have separate tables & no pointers. 2 commented lines below not needed.
19421        // state.next_index = opts.table_index;
19422        state.distbits = opts.bits;
19423        // state.distcode = state.next;
19424
19425        if (ret) {
19426          strm.msg = 'invalid distances set';
19427          state.mode = BAD;
19428          break;
19429        }
19430        //Tracev((stderr, 'inflate:       codes ok\n'));
19431        state.mode = LEN_;
19432        if (flush === Z_TREES) { break inf_leave; }
19433        /* falls through */
19434      case LEN_:
19435        state.mode = LEN;
19436        /* falls through */
19437      case LEN:
19438        if (have >= 6 && left >= 258) {
19439          //--- RESTORE() ---
19440          strm.next_out = put;
19441          strm.avail_out = left;
19442          strm.next_in = next;
19443          strm.avail_in = have;
19444          state.hold = hold;
19445          state.bits = bits;
19446          //---
19447          inflate_fast(strm, _out);
19448          //--- LOAD() ---
19449          put = strm.next_out;
19450          output = strm.output;
19451          left = strm.avail_out;
19452          next = strm.next_in;
19453          input = strm.input;
19454          have = strm.avail_in;
19455          hold = state.hold;
19456          bits = state.bits;
19457          //---
19458
19459          if (state.mode === TYPE) {
19460            state.back = -1;
19461          }
19462          break;
19463        }
19464        state.back = 0;
19465        for (;;) {
19466          here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
19467          here_bits = here >>> 24;
19468          here_op = (here >>> 16) & 0xff;
19469          here_val = here & 0xffff;
19470
19471          if (here_bits <= bits) { break; }
19472          //--- PULLBYTE() ---//
19473          if (have === 0) { break inf_leave; }
19474          have--;
19475          hold += input[next++] << bits;
19476          bits += 8;
19477          //---//
19478        }
19479        if (here_op && (here_op & 0xf0) === 0) {
19480          last_bits = here_bits;
19481          last_op = here_op;
19482          last_val = here_val;
19483          for (;;) {
19484            here = state.lencode[last_val +
19485                    ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
19486            here_bits = here >>> 24;
19487            here_op = (here >>> 16) & 0xff;
19488            here_val = here & 0xffff;
19489
19490            if ((last_bits + here_bits) <= bits) { break; }
19491            //--- PULLBYTE() ---//
19492            if (have === 0) { break inf_leave; }
19493            have--;
19494            hold += input[next++] << bits;
19495            bits += 8;
19496            //---//
19497          }
19498          //--- DROPBITS(last.bits) ---//
19499          hold >>>= last_bits;
19500          bits -= last_bits;
19501          //---//
19502          state.back += last_bits;
19503        }
19504        //--- DROPBITS(here.bits) ---//
19505        hold >>>= here_bits;
19506        bits -= here_bits;
19507        //---//
19508        state.back += here_bits;
19509        state.length = here_val;
19510        if (here_op === 0) {
19511          //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
19512          //        "inflate:         literal '%c'\n" :
19513          //        "inflate:         literal 0x%02x\n", here.val));
19514          state.mode = LIT;
19515          break;
19516        }
19517        if (here_op & 32) {
19518          //Tracevv((stderr, "inflate:         end of block\n"));
19519          state.back = -1;
19520          state.mode = TYPE;
19521          break;
19522        }
19523        if (here_op & 64) {
19524          strm.msg = 'invalid literal/length code';
19525          state.mode = BAD;
19526          break;
19527        }
19528        state.extra = here_op & 15;
19529        state.mode = LENEXT;
19530        /* falls through */
19531      case LENEXT:
19532        if (state.extra) {
19533          //=== NEEDBITS(state.extra);
19534          n = state.extra;
19535          while (bits < n) {
19536            if (have === 0) { break inf_leave; }
19537            have--;
19538            hold += input[next++] << bits;
19539            bits += 8;
19540          }
19541          //===//
19542          state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
19543          //--- DROPBITS(state.extra) ---//
19544          hold >>>= state.extra;
19545          bits -= state.extra;
19546          //---//
19547          state.back += state.extra;
19548        }
19549        //Tracevv((stderr, "inflate:         length %u\n", state.length));
19550        state.was = state.length;
19551        state.mode = DIST;
19552        /* falls through */
19553      case DIST:
19554        for (;;) {
19555          here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
19556          here_bits = here >>> 24;
19557          here_op = (here >>> 16) & 0xff;
19558          here_val = here & 0xffff;
19559
19560          if ((here_bits) <= bits) { break; }
19561          //--- PULLBYTE() ---//
19562          if (have === 0) { break inf_leave; }
19563          have--;
19564          hold += input[next++] << bits;
19565          bits += 8;
19566          //---//
19567        }
19568        if ((here_op & 0xf0) === 0) {
19569          last_bits = here_bits;
19570          last_op = here_op;
19571          last_val = here_val;
19572          for (;;) {
19573            here = state.distcode[last_val +
19574                    ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
19575            here_bits = here >>> 24;
19576            here_op = (here >>> 16) & 0xff;
19577            here_val = here & 0xffff;
19578
19579            if ((last_bits + here_bits) <= bits) { break; }
19580            //--- PULLBYTE() ---//
19581            if (have === 0) { break inf_leave; }
19582            have--;
19583            hold += input[next++] << bits;
19584            bits += 8;
19585            //---//
19586          }
19587          //--- DROPBITS(last.bits) ---//
19588          hold >>>= last_bits;
19589          bits -= last_bits;
19590          //---//
19591          state.back += last_bits;
19592        }
19593        //--- DROPBITS(here.bits) ---//
19594        hold >>>= here_bits;
19595        bits -= here_bits;
19596        //---//
19597        state.back += here_bits;
19598        if (here_op & 64) {
19599          strm.msg = 'invalid distance code';
19600          state.mode = BAD;
19601          break;
19602        }
19603        state.offset = here_val;
19604        state.extra = (here_op) & 15;
19605        state.mode = DISTEXT;
19606        /* falls through */
19607      case DISTEXT:
19608        if (state.extra) {
19609          //=== NEEDBITS(state.extra);
19610          n = state.extra;
19611          while (bits < n) {
19612            if (have === 0) { break inf_leave; }
19613            have--;
19614            hold += input[next++] << bits;
19615            bits += 8;
19616          }
19617          //===//
19618          state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
19619          //--- DROPBITS(state.extra) ---//
19620          hold >>>= state.extra;
19621          bits -= state.extra;
19622          //---//
19623          state.back += state.extra;
19624        }
19625//#ifdef INFLATE_STRICT
19626        if (state.offset > state.dmax) {
19627          strm.msg = 'invalid distance too far back';
19628          state.mode = BAD;
19629          break;
19630        }
19631//#endif
19632        //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
19633        state.mode = MATCH;
19634        /* falls through */
19635      case MATCH:
19636        if (left === 0) { break inf_leave; }
19637        copy = _out - left;
19638        if (state.offset > copy) {         /* copy from window */
19639          copy = state.offset - copy;
19640          if (copy > state.whave) {
19641            if (state.sane) {
19642              strm.msg = 'invalid distance too far back';
19643              state.mode = BAD;
19644              break;
19645            }
19646// (!) This block is disabled in zlib defaults,
19647// don't enable it for binary compatibility
19648//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
19649//          Trace((stderr, "inflate.c too far\n"));
19650//          copy -= state.whave;
19651//          if (copy > state.length) { copy = state.length; }
19652//          if (copy > left) { copy = left; }
19653//          left -= copy;
19654//          state.length -= copy;
19655//          do {
19656//            output[put++] = 0;
19657//          } while (--copy);
19658//          if (state.length === 0) { state.mode = LEN; }
19659//          break;
19660//#endif
19661          }
19662          if (copy > state.wnext) {
19663            copy -= state.wnext;
19664            from = state.wsize - copy;
19665          }
19666          else {
19667            from = state.wnext - copy;
19668          }
19669          if (copy > state.length) { copy = state.length; }
19670          from_source = state.window;
19671        }
19672        else {                              /* copy from output */
19673          from_source = output;
19674          from = put - state.offset;
19675          copy = state.length;
19676        }
19677        if (copy > left) { copy = left; }
19678        left -= copy;
19679        state.length -= copy;
19680        do {
19681          output[put++] = from_source[from++];
19682        } while (--copy);
19683        if (state.length === 0) { state.mode = LEN; }
19684        break;
19685      case LIT:
19686        if (left === 0) { break inf_leave; }
19687        output[put++] = state.length;
19688        left--;
19689        state.mode = LEN;
19690        break;
19691      case CHECK:
19692        if (state.wrap) {
19693          //=== NEEDBITS(32);
19694          while (bits < 32) {
19695            if (have === 0) { break inf_leave; }
19696            have--;
19697            // Use '|' instead of '+' to make sure that result is signed
19698            hold |= input[next++] << bits;
19699            bits += 8;
19700          }
19701          //===//
19702          _out -= left;
19703          strm.total_out += _out;
19704          state.total += _out;
19705          if (_out) {
19706            strm.adler = state.check =
19707                /*UPDATE(state.check, put - _out, _out);*/
19708                (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
19709
19710          }
19711          _out = left;
19712          // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
19713          if ((state.flags ? hold : zswap32(hold)) !== state.check) {
19714            strm.msg = 'incorrect data check';
19715            state.mode = BAD;
19716            break;
19717          }
19718          //=== INITBITS();
19719          hold = 0;
19720          bits = 0;
19721          //===//
19722          //Tracev((stderr, "inflate:   check matches trailer\n"));
19723        }
19724        state.mode = LENGTH;
19725        /* falls through */
19726      case LENGTH:
19727        if (state.wrap && state.flags) {
19728          //=== NEEDBITS(32);
19729          while (bits < 32) {
19730            if (have === 0) { break inf_leave; }
19731            have--;
19732            hold += input[next++] << bits;
19733            bits += 8;
19734          }
19735          //===//
19736          if (hold !== (state.total & 0xffffffff)) {
19737            strm.msg = 'incorrect length check';
19738            state.mode = BAD;
19739            break;
19740          }
19741          //=== INITBITS();
19742          hold = 0;
19743          bits = 0;
19744          //===//
19745          //Tracev((stderr, "inflate:   length matches trailer\n"));
19746        }
19747        state.mode = DONE;
19748        /* falls through */
19749      case DONE:
19750        ret = Z_STREAM_END;
19751        break inf_leave;
19752      case BAD:
19753        ret = Z_DATA_ERROR;
19754        break inf_leave;
19755      case MEM:
19756        return Z_MEM_ERROR;
19757      case SYNC:
19758        /* falls through */
19759      default:
19760        return Z_STREAM_ERROR;
19761    }
19762  }
19763
19764  // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
19765
19766  /*
19767     Return from inflate(), updating the total counts and the check value.
19768     If there was no progress during the inflate() call, return a buffer
19769     error.  Call updatewindow() to create and/or update the window state.
19770     Note: a memory error from inflate() is non-recoverable.
19771   */
19772
19773  //--- RESTORE() ---
19774  strm.next_out = put;
19775  strm.avail_out = left;
19776  strm.next_in = next;
19777  strm.avail_in = have;
19778  state.hold = hold;
19779  state.bits = bits;
19780  //---
19781
19782  if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
19783                      (state.mode < CHECK || flush !== Z_FINISH))) {
19784    if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
19785      state.mode = MEM;
19786      return Z_MEM_ERROR;
19787    }
19788  }
19789  _in -= strm.avail_in;
19790  _out -= strm.avail_out;
19791  strm.total_in += _in;
19792  strm.total_out += _out;
19793  state.total += _out;
19794  if (state.wrap && _out) {
19795    strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
19796      (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
19797  }
19798  strm.data_type = state.bits + (state.last ? 64 : 0) +
19799                    (state.mode === TYPE ? 128 : 0) +
19800                    (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
19801  if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
19802    ret = Z_BUF_ERROR;
19803  }
19804  return ret;
19805}
19806
19807function inflateEnd(strm) {
19808
19809  if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
19810    return Z_STREAM_ERROR;
19811  }
19812
19813  var state = strm.state;
19814  if (state.window) {
19815    state.window = null;
19816  }
19817  strm.state = null;
19818  return Z_OK;
19819}
19820
19821function inflateGetHeader(strm, head) {
19822  var state;
19823
19824  /* check state */
19825  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
19826  state = strm.state;
19827  if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
19828
19829  /* save header structure */
19830  state.head = head;
19831  head.done = false;
19832  return Z_OK;
19833}
19834
19835function inflateSetDictionary(strm, dictionary) {
19836  var dictLength = dictionary.length;
19837
19838  var state;
19839  var dictid;
19840  var ret;
19841
19842  /* check state */
19843  if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
19844  state = strm.state;
19845
19846  if (state.wrap !== 0 && state.mode !== DICT) {
19847    return Z_STREAM_ERROR;
19848  }
19849
19850  /* check for correct dictionary identifier */
19851  if (state.mode === DICT) {
19852    dictid = 1; /* adler32(0, null, 0)*/
19853    /* dictid = adler32(dictid, dictionary, dictLength); */
19854    dictid = adler32(dictid, dictionary, dictLength, 0);
19855    if (dictid !== state.check) {
19856      return Z_DATA_ERROR;
19857    }
19858  }
19859  /* copy dictionary to window using updatewindow(), which will amend the
19860   existing dictionary if appropriate */
19861  ret = updatewindow(strm, dictionary, dictLength, dictLength);
19862  if (ret) {
19863    state.mode = MEM;
19864    return Z_MEM_ERROR;
19865  }
19866  state.havedict = 1;
19867  // Tracev((stderr, "inflate:   dictionary set\n"));
19868  return Z_OK;
19869}
19870
19871exports.inflateReset = inflateReset;
19872exports.inflateReset2 = inflateReset2;
19873exports.inflateResetKeep = inflateResetKeep;
19874exports.inflateInit = inflateInit;
19875exports.inflateInit2 = inflateInit2;
19876exports.inflate = inflate;
19877exports.inflateEnd = inflateEnd;
19878exports.inflateGetHeader = inflateGetHeader;
19879exports.inflateSetDictionary = inflateSetDictionary;
19880exports.inflateInfo = 'pako inflate (from Nodeca project)';
19881
19882/* Not implemented
19883exports.inflateCopy = inflateCopy;
19884exports.inflateGetDictionary = inflateGetDictionary;
19885exports.inflateMark = inflateMark;
19886exports.inflatePrime = inflatePrime;
19887exports.inflateSync = inflateSync;
19888exports.inflateSyncPoint = inflateSyncPoint;
19889exports.inflateUndermine = inflateUndermine;
19890*/
19891
19892},{"../utils/common":54,"./adler32":56,"./crc32":58,"./inffast":61,"./inftrees":63}],63:[function(require,module,exports){
19893'use strict';
19894
19895// (C) 1995-2013 Jean-loup Gailly and Mark Adler
19896// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
19897//
19898// This software is provided 'as-is', without any express or implied
19899// warranty. In no event will the authors be held liable for any damages
19900// arising from the use of this software.
19901//
19902// Permission is granted to anyone to use this software for any purpose,
19903// including commercial applications, and to alter it and redistribute it
19904// freely, subject to the following restrictions:
19905//
19906// 1. The origin of this software must not be misrepresented; you must not
19907//   claim that you wrote the original software. If you use this software
19908//   in a product, an acknowledgment in the product documentation would be
19909//   appreciated but is not required.
19910// 2. Altered source versions must be plainly marked as such, and must not be
19911//   misrepresented as being the original software.
19912// 3. This notice may not be removed or altered from any source distribution.
19913
19914var utils = require('../utils/common');
19915
19916var MAXBITS = 15;
19917var ENOUGH_LENS = 852;
19918var ENOUGH_DISTS = 592;
19919//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
19920
19921var CODES = 0;
19922var LENS = 1;
19923var DISTS = 2;
19924
19925var lbase = [ /* Length codes 257..285 base */
19926  3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
19927  35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
19928];
19929
19930var lext = [ /* Length codes 257..285 extra */
19931  16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19932  19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
19933];
19934
19935var dbase = [ /* Distance codes 0..29 base */
19936  1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
19937  257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
19938  8193, 12289, 16385, 24577, 0, 0
19939];
19940
19941var dext = [ /* Distance codes 0..29 extra */
19942  16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
19943  23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
19944  28, 28, 29, 29, 64, 64
19945];
19946
19947module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
19948{
19949  var bits = opts.bits;
19950      //here = opts.here; /* table entry for duplication */
19951
19952  var len = 0;               /* a code's length in bits */
19953  var sym = 0;               /* index of code symbols */
19954  var min = 0, max = 0;          /* minimum and maximum code lengths */
19955  var root = 0;              /* number of index bits for root table */
19956  var curr = 0;              /* number of index bits for current table */
19957  var drop = 0;              /* code bits to drop for sub-table */
19958  var left = 0;                   /* number of prefix codes available */
19959  var used = 0;              /* code entries in table used */
19960  var huff = 0;              /* Huffman code */
19961  var incr;              /* for incrementing code, index */
19962  var fill;              /* index for replicating entries */
19963  var low;               /* low bits for current root entry */
19964  var mask;              /* mask for low root bits */
19965  var next;             /* next available space in table */
19966  var base = null;     /* base value table to use */
19967  var base_index = 0;
19968//  var shoextra;    /* extra bits table to use */
19969  var end;                    /* use base and extra for symbol > end */
19970  var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
19971  var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
19972  var extra = null;
19973  var extra_index = 0;
19974
19975  var here_bits, here_op, here_val;
19976
19977  /*
19978   Process a set of code lengths to create a canonical Huffman code.  The
19979   code lengths are lens[0..codes-1].  Each length corresponds to the
19980   symbols 0..codes-1.  The Huffman code is generated by first sorting the
19981   symbols by length from short to long, and retaining the symbol order
19982   for codes with equal lengths.  Then the code starts with all zero bits
19983   for the first code of the shortest length, and the codes are integer
19984   increments for the same length, and zeros are appended as the length
19985   increases.  For the deflate format, these bits are stored backwards
19986   from their more natural integer increment ordering, and so when the
19987   decoding tables are built in the large loop below, the integer codes
19988   are incremented backwards.
19989
19990   This routine assumes, but does not check, that all of the entries in
19991   lens[] are in the range 0..MAXBITS.  The caller must assure this.
19992   1..MAXBITS is interpreted as that code length.  zero means that that
19993   symbol does not occur in this code.
19994
19995   The codes are sorted by computing a count of codes for each length,
19996   creating from that a table of starting indices for each length in the
19997   sorted table, and then entering the symbols in order in the sorted
19998   table.  The sorted table is work[], with that space being provided by
19999   the caller.
20000
20001   The length counts are used for other purposes as well, i.e. finding
20002   the minimum and maximum length codes, determining if there are any
20003   codes at all, checking for a valid set of lengths, and looking ahead
20004   at length counts to determine sub-table sizes when building the
20005   decoding tables.
20006   */
20007
20008  /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
20009  for (len = 0; len <= MAXBITS; len++) {
20010    count[len] = 0;
20011  }
20012  for (sym = 0; sym < codes; sym++) {
20013    count[lens[lens_index + sym]]++;
20014  }
20015
20016  /* bound code lengths, force root to be within code lengths */
20017  root = bits;
20018  for (max = MAXBITS; max >= 1; max--) {
20019    if (count[max] !== 0) { break; }
20020  }
20021  if (root > max) {
20022    root = max;
20023  }
20024  if (max === 0) {                     /* no symbols to code at all */
20025    //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
20026    //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
20027    //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
20028    table[table_index++] = (1 << 24) | (64 << 16) | 0;
20029
20030
20031    //table.op[opts.table_index] = 64;
20032    //table.bits[opts.table_index] = 1;
20033    //table.val[opts.table_index++] = 0;
20034    table[table_index++] = (1 << 24) | (64 << 16) | 0;
20035
20036    opts.bits = 1;
20037    return 0;     /* no symbols, but wait for decoding to report error */
20038  }
20039  for (min = 1; min < max; min++) {
20040    if (count[min] !== 0) { break; }
20041  }
20042  if (root < min) {
20043    root = min;
20044  }
20045
20046  /* check for an over-subscribed or incomplete set of lengths */
20047  left = 1;
20048  for (len = 1; len <= MAXBITS; len++) {
20049    left <<= 1;
20050    left -= count[len];
20051    if (left < 0) {
20052      return -1;
20053    }        /* over-subscribed */
20054  }
20055  if (left > 0 && (type === CODES || max !== 1)) {
20056    return -1;                      /* incomplete set */
20057  }
20058
20059  /* generate offsets into symbol table for each length for sorting */
20060  offs[1] = 0;
20061  for (len = 1; len < MAXBITS; len++) {
20062    offs[len + 1] = offs[len] + count[len];
20063  }
20064
20065  /* sort symbols by length, by symbol order within each length */
20066  for (sym = 0; sym < codes; sym++) {
20067    if (lens[lens_index + sym] !== 0) {
20068      work[offs[lens[lens_index + sym]]++] = sym;
20069    }
20070  }
20071
20072  /*
20073   Create and fill in decoding tables.  In this loop, the table being
20074   filled is at next and has curr index bits.  The code being used is huff
20075   with length len.  That code is converted to an index by dropping drop
20076   bits off of the bottom.  For codes where len is less than drop + curr,
20077   those top drop + curr - len bits are incremented through all values to
20078   fill the table with replicated entries.
20079
20080   root is the number of index bits for the root table.  When len exceeds
20081   root, sub-tables are created pointed to by the root entry with an index
20082   of the low root bits of huff.  This is saved in low to check for when a
20083   new sub-table should be started.  drop is zero when the root table is
20084   being filled, and drop is root when sub-tables are being filled.
20085
20086   When a new sub-table is needed, it is necessary to look ahead in the
20087   code lengths to determine what size sub-table is needed.  The length
20088   counts are used for this, and so count[] is decremented as codes are
20089   entered in the tables.
20090
20091   used keeps track of how many table entries have been allocated from the
20092   provided *table space.  It is checked for LENS and DIST tables against
20093   the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
20094   the initial root table size constants.  See the comments in inftrees.h
20095   for more information.
20096
20097   sym increments through all symbols, and the loop terminates when
20098   all codes of length max, i.e. all codes, have been processed.  This
20099   routine permits incomplete codes, so another loop after this one fills
20100   in the rest of the decoding tables with invalid code markers.
20101   */
20102
20103  /* set up for code type */
20104  // poor man optimization - use if-else instead of switch,
20105  // to avoid deopts in old v8
20106  if (type === CODES) {
20107    base = extra = work;    /* dummy value--not used */
20108    end = 19;
20109
20110  } else if (type === LENS) {
20111    base = lbase;
20112    base_index -= 257;
20113    extra = lext;
20114    extra_index -= 257;
20115    end = 256;
20116
20117  } else {                    /* DISTS */
20118    base = dbase;
20119    extra = dext;
20120    end = -1;
20121  }
20122
20123  /* initialize opts for loop */
20124  huff = 0;                   /* starting code */
20125  sym = 0;                    /* starting code symbol */
20126  len = min;                  /* starting code length */
20127  next = table_index;              /* current table to fill in */
20128  curr = root;                /* current table index bits */
20129  drop = 0;                   /* current bits to drop from code for index */
20130  low = -1;                   /* trigger new sub-table when len > root */
20131  used = 1 << root;          /* use root table entries */
20132  mask = used - 1;            /* mask for comparing low */
20133
20134  /* check available table space */
20135  if ((type === LENS && used > ENOUGH_LENS) ||
20136    (type === DISTS && used > ENOUGH_DISTS)) {
20137    return 1;
20138  }
20139
20140  /* process all codes and make table entries */
20141  for (;;) {
20142    /* create table entry */
20143    here_bits = len - drop;
20144    if (work[sym] < end) {
20145      here_op = 0;
20146      here_val = work[sym];
20147    }
20148    else if (work[sym] > end) {
20149      here_op = extra[extra_index + work[sym]];
20150      here_val = base[base_index + work[sym]];
20151    }
20152    else {
20153      here_op = 32 + 64;         /* end of block */
20154      here_val = 0;
20155    }
20156
20157    /* replicate for those indices with low len bits equal to huff */
20158    incr = 1 << (len - drop);
20159    fill = 1 << curr;
20160    min = fill;                 /* save offset to next table */
20161    do {
20162      fill -= incr;
20163      table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
20164    } while (fill !== 0);
20165
20166    /* backwards increment the len-bit code huff */
20167    incr = 1 << (len - 1);
20168    while (huff & incr) {
20169      incr >>= 1;
20170    }
20171    if (incr !== 0) {
20172      huff &= incr - 1;
20173      huff += incr;
20174    } else {
20175      huff = 0;
20176    }
20177
20178    /* go to next symbol, update count, len */
20179    sym++;
20180    if (--count[len] === 0) {
20181      if (len === max) { break; }
20182      len = lens[lens_index + work[sym]];
20183    }
20184
20185    /* create new sub-table if needed */
20186    if (len > root && (huff & mask) !== low) {
20187      /* if first time, transition to sub-tables */
20188      if (drop === 0) {
20189        drop = root;
20190      }
20191
20192      /* increment past last table */
20193      next += min;            /* here min is 1 << curr */
20194
20195      /* determine length of next table */
20196      curr = len - drop;
20197      left = 1 << curr;
20198      while (curr + drop < max) {
20199        left -= count[curr + drop];
20200        if (left <= 0) { break; }
20201        curr++;
20202        left <<= 1;
20203      }
20204
20205      /* check for enough space */
20206      used += 1 << curr;
20207      if ((type === LENS && used > ENOUGH_LENS) ||
20208        (type === DISTS && used > ENOUGH_DISTS)) {
20209        return 1;
20210      }
20211
20212      /* point entry in root table to sub-table */
20213      low = huff & mask;
20214      /*table.op[low] = curr;
20215      table.bits[low] = root;
20216      table.val[low] = next - opts.table_index;*/
20217      table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
20218    }
20219  }
20220
20221  /* fill in remaining table entry if code is incomplete (guaranteed to have
20222   at most one remaining entry, since if the code is incomplete, the
20223   maximum code length that was allowed to get this far is one bit) */
20224  if (huff !== 0) {
20225    //table.op[next + huff] = 64;            /* invalid code marker */
20226    //table.bits[next + huff] = len - drop;
20227    //table.val[next + huff] = 0;
20228    table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
20229  }
20230
20231  /* set return parameters */
20232  //opts.table_index += used;
20233  opts.bits = root;
20234  return 0;
20235};
20236
20237},{"../utils/common":54}],64:[function(require,module,exports){
20238'use strict';
20239
20240// (C) 1995-2013 Jean-loup Gailly and Mark Adler
20241// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
20242//
20243// This software is provided 'as-is', without any express or implied
20244// warranty. In no event will the authors be held liable for any damages
20245// arising from the use of this software.
20246//
20247// Permission is granted to anyone to use this software for any purpose,
20248// including commercial applications, and to alter it and redistribute it
20249// freely, subject to the following restrictions:
20250//
20251// 1. The origin of this software must not be misrepresented; you must not
20252//   claim that you wrote the original software. If you use this software
20253//   in a product, an acknowledgment in the product documentation would be
20254//   appreciated but is not required.
20255// 2. Altered source versions must be plainly marked as such, and must not be
20256//   misrepresented as being the original software.
20257// 3. This notice may not be removed or altered from any source distribution.
20258
20259module.exports = {
20260  2:      'need dictionary',     /* Z_NEED_DICT       2  */
20261  1:      'stream end',          /* Z_STREAM_END      1  */
20262  0:      '',                    /* Z_OK              0  */
20263  '-1':   'file error',          /* Z_ERRNO         (-1) */
20264  '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
20265  '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
20266  '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
20267  '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
20268  '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
20269};
20270
20271},{}],65:[function(require,module,exports){
20272'use strict';
20273
20274// (C) 1995-2013 Jean-loup Gailly and Mark Adler
20275// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
20276//
20277// This software is provided 'as-is', without any express or implied
20278// warranty. In no event will the authors be held liable for any damages
20279// arising from the use of this software.
20280//
20281// Permission is granted to anyone to use this software for any purpose,
20282// including commercial applications, and to alter it and redistribute it
20283// freely, subject to the following restrictions:
20284//
20285// 1. The origin of this software must not be misrepresented; you must not
20286//   claim that you wrote the original software. If you use this software
20287//   in a product, an acknowledgment in the product documentation would be
20288//   appreciated but is not required.
20289// 2. Altered source versions must be plainly marked as such, and must not be
20290//   misrepresented as being the original software.
20291// 3. This notice may not be removed or altered from any source distribution.
20292
20293var utils = require('../utils/common');
20294
20295/* Public constants ==========================================================*/
20296/* ===========================================================================*/
20297
20298
20299//var Z_FILTERED          = 1;
20300//var Z_HUFFMAN_ONLY      = 2;
20301//var Z_RLE               = 3;
20302var Z_FIXED               = 4;
20303//var Z_DEFAULT_STRATEGY  = 0;
20304
20305/* Possible values of the data_type field (though see inflate()) */
20306var Z_BINARY              = 0;
20307var Z_TEXT                = 1;
20308//var Z_ASCII             = 1; // = Z_TEXT
20309var Z_UNKNOWN             = 2;
20310
20311/*============================================================================*/
20312
20313
20314function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
20315
20316// From zutil.h
20317
20318var STORED_BLOCK = 0;
20319var STATIC_TREES = 1;
20320var DYN_TREES    = 2;
20321/* The three kinds of block type */
20322
20323var MIN_MATCH    = 3;
20324var MAX_MATCH    = 258;
20325/* The minimum and maximum match lengths */
20326
20327// From deflate.h
20328/* ===========================================================================
20329 * Internal compression state.
20330 */
20331
20332var LENGTH_CODES  = 29;
20333/* number of length codes, not counting the special END_BLOCK code */
20334
20335var LITERALS      = 256;
20336/* number of literal bytes 0..255 */
20337
20338var L_CODES       = LITERALS + 1 + LENGTH_CODES;
20339/* number of Literal or Length codes, including the END_BLOCK code */
20340
20341var D_CODES       = 30;
20342/* number of distance codes */
20343
20344var BL_CODES      = 19;
20345/* number of codes used to transfer the bit lengths */
20346
20347var HEAP_SIZE     = 2 * L_CODES + 1;
20348/* maximum heap size */
20349
20350var MAX_BITS      = 15;
20351/* All codes must not exceed MAX_BITS bits */
20352
20353var Buf_size      = 16;
20354/* size of bit buffer in bi_buf */
20355
20356
20357/* ===========================================================================
20358 * Constants
20359 */
20360
20361var MAX_BL_BITS = 7;
20362/* Bit length codes must not exceed MAX_BL_BITS bits */
20363
20364var END_BLOCK   = 256;
20365/* end of block literal code */
20366
20367var REP_3_6     = 16;
20368/* repeat previous bit length 3-6 times (2 bits of repeat count) */
20369
20370var REPZ_3_10   = 17;
20371/* repeat a zero length 3-10 times  (3 bits of repeat count) */
20372
20373var REPZ_11_138 = 18;
20374/* repeat a zero length 11-138 times  (7 bits of repeat count) */
20375
20376/* eslint-disable comma-spacing,array-bracket-spacing */
20377var extra_lbits =   /* extra bits for each length code */
20378  [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];
20379
20380var extra_dbits =   /* extra bits for each distance code */
20381  [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];
20382
20383var extra_blbits =  /* extra bits for each bit length code */
20384  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
20385
20386var bl_order =
20387  [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
20388/* eslint-enable comma-spacing,array-bracket-spacing */
20389
20390/* The lengths of the bit length codes are sent in order of decreasing
20391 * probability, to avoid transmitting the lengths for unused bit length codes.
20392 */
20393
20394/* ===========================================================================
20395 * Local data. These are initialized only once.
20396 */
20397
20398// We pre-fill arrays with 0 to avoid uninitialized gaps
20399
20400var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
20401
20402// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
20403var static_ltree  = new Array((L_CODES + 2) * 2);
20404zero(static_ltree);
20405/* The static literal tree. Since the bit lengths are imposed, there is no
20406 * need for the L_CODES extra codes used during heap construction. However
20407 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
20408 * below).
20409 */
20410
20411var static_dtree  = new Array(D_CODES * 2);
20412zero(static_dtree);
20413/* The static distance tree. (Actually a trivial tree since all codes use
20414 * 5 bits.)
20415 */
20416
20417var _dist_code    = new Array(DIST_CODE_LEN);
20418zero(_dist_code);
20419/* Distance codes. The first 256 values correspond to the distances
20420 * 3 .. 258, the last 256 values correspond to the top 8 bits of
20421 * the 15 bit distances.
20422 */
20423
20424var _length_code  = new Array(MAX_MATCH - MIN_MATCH + 1);
20425zero(_length_code);
20426/* length code for each normalized match length (0 == MIN_MATCH) */
20427
20428var base_length   = new Array(LENGTH_CODES);
20429zero(base_length);
20430/* First normalized length for each code (0 = MIN_MATCH) */
20431
20432var base_dist     = new Array(D_CODES);
20433zero(base_dist);
20434/* First normalized distance for each code (0 = distance of 1) */
20435
20436
20437function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
20438
20439  this.static_tree  = static_tree;  /* static tree or NULL */
20440  this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */
20441  this.extra_base   = extra_base;   /* base index for extra_bits */
20442  this.elems        = elems;        /* max number of elements in the tree */
20443  this.max_length   = max_length;   /* max bit length for the codes */
20444
20445  // show if `static_tree` has data or dummy - needed for monomorphic objects
20446  this.has_stree    = static_tree && static_tree.length;
20447}
20448
20449
20450var static_l_desc;
20451var static_d_desc;
20452var static_bl_desc;
20453
20454
20455function TreeDesc(dyn_tree, stat_desc) {
20456  this.dyn_tree = dyn_tree;     /* the dynamic tree */
20457  this.max_code = 0;            /* largest code with non zero frequency */
20458  this.stat_desc = stat_desc;   /* the corresponding static tree */
20459}
20460
20461
20462
20463function d_code(dist) {
20464  return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
20465}
20466
20467
20468/* ===========================================================================
20469 * Output a short LSB first on the stream.
20470 * IN assertion: there is enough room in pendingBuf.
20471 */
20472function put_short(s, w) {
20473//    put_byte(s, (uch)((w) & 0xff));
20474//    put_byte(s, (uch)((ush)(w) >> 8));
20475  s.pending_buf[s.pending++] = (w) & 0xff;
20476  s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
20477}
20478
20479
20480/* ===========================================================================
20481 * Send a value on a given number of bits.
20482 * IN assertion: length <= 16 and value fits in length bits.
20483 */
20484function send_bits(s, value, length) {
20485  if (s.bi_valid > (Buf_size - length)) {
20486    s.bi_buf |= (value << s.bi_valid) & 0xffff;
20487    put_short(s, s.bi_buf);
20488    s.bi_buf = value >> (Buf_size - s.bi_valid);
20489    s.bi_valid += length - Buf_size;
20490  } else {
20491    s.bi_buf |= (value << s.bi_valid) & 0xffff;
20492    s.bi_valid += length;
20493  }
20494}
20495
20496
20497function send_code(s, c, tree) {
20498  send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
20499}
20500
20501
20502/* ===========================================================================
20503 * Reverse the first len bits of a code, using straightforward code (a faster
20504 * method would use a table)
20505 * IN assertion: 1 <= len <= 15
20506 */
20507function bi_reverse(code, len) {
20508  var res = 0;
20509  do {
20510    res |= code & 1;
20511    code >>>= 1;
20512    res <<= 1;
20513  } while (--len > 0);
20514  return res >>> 1;
20515}
20516
20517
20518/* ===========================================================================
20519 * Flush the bit buffer, keeping at most 7 bits in it.
20520 */
20521function bi_flush(s) {
20522  if (s.bi_valid === 16) {
20523    put_short(s, s.bi_buf);
20524    s.bi_buf = 0;
20525    s.bi_valid = 0;
20526
20527  } else if (s.bi_valid >= 8) {
20528    s.pending_buf[s.pending++] = s.bi_buf & 0xff;
20529    s.bi_buf >>= 8;
20530    s.bi_valid -= 8;
20531  }
20532}
20533
20534
20535/* ===========================================================================
20536 * Compute the optimal bit lengths for a tree and update the total bit length
20537 * for the current block.
20538 * IN assertion: the fields freq and dad are set, heap[heap_max] and
20539 *    above are the tree nodes sorted by increasing frequency.
20540 * OUT assertions: the field len is set to the optimal bit length, the
20541 *     array bl_count contains the frequencies for each bit length.
20542 *     The length opt_len is updated; static_len is also updated if stree is
20543 *     not null.
20544 */
20545function gen_bitlen(s, desc)
20546//    deflate_state *s;
20547//    tree_desc *desc;    /* the tree descriptor */
20548{
20549  var tree            = desc.dyn_tree;
20550  var max_code        = desc.max_code;
20551  var stree           = desc.stat_desc.static_tree;
20552  var has_stree       = desc.stat_desc.has_stree;
20553  var extra           = desc.stat_desc.extra_bits;
20554  var base            = desc.stat_desc.extra_base;
20555  var max_length      = desc.stat_desc.max_length;
20556  var h;              /* heap index */
20557  var n, m;           /* iterate over the tree elements */
20558  var bits;           /* bit length */
20559  var xbits;          /* extra bits */
20560  var f;              /* frequency */
20561  var overflow = 0;   /* number of elements with bit length too large */
20562
20563  for (bits = 0; bits <= MAX_BITS; bits++) {
20564    s.bl_count[bits] = 0;
20565  }
20566
20567  /* In a first pass, compute the optimal bit lengths (which may
20568   * overflow in the case of the bit length tree).
20569   */
20570  tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
20571
20572  for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
20573    n = s.heap[h];
20574    bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
20575    if (bits > max_length) {
20576      bits = max_length;
20577      overflow++;
20578    }
20579    tree[n * 2 + 1]/*.Len*/ = bits;
20580    /* We overwrite tree[n].Dad which is no longer needed */
20581
20582    if (n > max_code) { continue; } /* not a leaf node */
20583
20584    s.bl_count[bits]++;
20585    xbits = 0;
20586    if (n >= base) {
20587      xbits = extra[n - base];
20588    }
20589    f = tree[n * 2]/*.Freq*/;
20590    s.opt_len += f * (bits + xbits);
20591    if (has_stree) {
20592      s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
20593    }
20594  }
20595  if (overflow === 0) { return; }
20596
20597  // Trace((stderr,"\nbit length overflow\n"));
20598  /* This happens for example on obj2 and pic of the Calgary corpus */
20599
20600  /* Find the first bit length which could increase: */
20601  do {
20602    bits = max_length - 1;
20603    while (s.bl_count[bits] === 0) { bits--; }
20604    s.bl_count[bits]--;      /* move one leaf down the tree */
20605    s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
20606    s.bl_count[max_length]--;
20607    /* The brother of the overflow item also moves one step up,
20608     * but this does not affect bl_count[max_length]
20609     */
20610    overflow -= 2;
20611  } while (overflow > 0);
20612
20613  /* Now recompute all bit lengths, scanning in increasing frequency.
20614   * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
20615   * lengths instead of fixing only the wrong ones. This idea is taken
20616   * from 'ar' written by Haruhiko Okumura.)
20617   */
20618  for (bits = max_length; bits !== 0; bits--) {
20619    n = s.bl_count[bits];
20620    while (n !== 0) {
20621      m = s.heap[--h];
20622      if (m > max_code) { continue; }
20623      if (tree[m * 2 + 1]/*.Len*/ !== bits) {
20624        // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
20625        s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
20626        tree[m * 2 + 1]/*.Len*/ = bits;
20627      }
20628      n--;
20629    }
20630  }
20631}
20632
20633
20634/* ===========================================================================
20635 * Generate the codes for a given tree and bit counts (which need not be
20636 * optimal).
20637 * IN assertion: the array bl_count contains the bit length statistics for
20638 * the given tree and the field len is set for all tree elements.
20639 * OUT assertion: the field code is set for all tree elements of non
20640 *     zero code length.
20641 */
20642function gen_codes(tree, max_code, bl_count)
20643//    ct_data *tree;             /* the tree to decorate */
20644//    int max_code;              /* largest code with non zero frequency */
20645//    ushf *bl_count;            /* number of codes at each bit length */
20646{
20647  var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
20648  var code = 0;              /* running code value */
20649  var bits;                  /* bit index */
20650  var n;                     /* code index */
20651
20652  /* The distribution counts are first used to generate the code values
20653   * without bit reversal.
20654   */
20655  for (bits = 1; bits <= MAX_BITS; bits++) {
20656    next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
20657  }
20658  /* Check that the bit counts in bl_count are consistent. The last code
20659   * must be all ones.
20660   */
20661  //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
20662  //        "inconsistent bit counts");
20663  //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
20664
20665  for (n = 0;  n <= max_code; n++) {
20666    var len = tree[n * 2 + 1]/*.Len*/;
20667    if (len === 0) { continue; }
20668    /* Now reverse the bits */
20669    tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
20670
20671    //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
20672    //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
20673  }
20674}
20675
20676
20677/* ===========================================================================
20678 * Initialize the various 'constant' tables.
20679 */
20680function tr_static_init() {
20681  var n;        /* iterates over tree elements */
20682  var bits;     /* bit counter */
20683  var length;   /* length value */
20684  var code;     /* code value */
20685  var dist;     /* distance index */
20686  var bl_count = new Array(MAX_BITS + 1);
20687  /* number of codes at each bit length for an optimal tree */
20688
20689  // do check in _tr_init()
20690  //if (static_init_done) return;
20691
20692  /* For some embedded targets, global variables are not initialized: */
20693/*#ifdef NO_INIT_GLOBAL_POINTERS
20694  static_l_desc.static_tree = static_ltree;
20695  static_l_desc.extra_bits = extra_lbits;
20696  static_d_desc.static_tree = static_dtree;
20697  static_d_desc.extra_bits = extra_dbits;
20698  static_bl_desc.extra_bits = extra_blbits;
20699#endif*/
20700
20701  /* Initialize the mapping length (0..255) -> length code (0..28) */
20702  length = 0;
20703  for (code = 0; code < LENGTH_CODES - 1; code++) {
20704    base_length[code] = length;
20705    for (n = 0; n < (1 << extra_lbits[code]); n++) {
20706      _length_code[length++] = code;
20707    }
20708  }
20709  //Assert (length == 256, "tr_static_init: length != 256");
20710  /* Note that the length 255 (match length 258) can be represented
20711   * in two different ways: code 284 + 5 bits or code 285, so we
20712   * overwrite length_code[255] to use the best encoding:
20713   */
20714  _length_code[length - 1] = code;
20715
20716  /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
20717  dist = 0;
20718  for (code = 0; code < 16; code++) {
20719    base_dist[code] = dist;
20720    for (n = 0; n < (1 << extra_dbits[code]); n++) {
20721      _dist_code[dist++] = code;
20722    }
20723  }
20724  //Assert (dist == 256, "tr_static_init: dist != 256");
20725  dist >>= 7; /* from now on, all distances are divided by 128 */
20726  for (; code < D_CODES; code++) {
20727    base_dist[code] = dist << 7;
20728    for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
20729      _dist_code[256 + dist++] = code;
20730    }
20731  }
20732  //Assert (dist == 256, "tr_static_init: 256+dist != 512");
20733
20734  /* Construct the codes of the static literal tree */
20735  for (bits = 0; bits <= MAX_BITS; bits++) {
20736    bl_count[bits] = 0;
20737  }
20738
20739  n = 0;
20740  while (n <= 143) {
20741    static_ltree[n * 2 + 1]/*.Len*/ = 8;
20742    n++;
20743    bl_count[8]++;
20744  }
20745  while (n <= 255) {
20746    static_ltree[n * 2 + 1]/*.Len*/ = 9;
20747    n++;
20748    bl_count[9]++;
20749  }
20750  while (n <= 279) {
20751    static_ltree[n * 2 + 1]/*.Len*/ = 7;
20752    n++;
20753    bl_count[7]++;
20754  }
20755  while (n <= 287) {
20756    static_ltree[n * 2 + 1]/*.Len*/ = 8;
20757    n++;
20758    bl_count[8]++;
20759  }
20760  /* Codes 286 and 287 do not exist, but we must include them in the
20761   * tree construction to get a canonical Huffman tree (longest code
20762   * all ones)
20763   */
20764  gen_codes(static_ltree, L_CODES + 1, bl_count);
20765
20766  /* The static distance tree is trivial: */
20767  for (n = 0; n < D_CODES; n++) {
20768    static_dtree[n * 2 + 1]/*.Len*/ = 5;
20769    static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
20770  }
20771
20772  // Now data ready and we can init static trees
20773  static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
20774  static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS);
20775  static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES, MAX_BL_BITS);
20776
20777  //static_init_done = true;
20778}
20779
20780
20781/* ===========================================================================
20782 * Initialize a new block.
20783 */
20784function init_block(s) {
20785  var n; /* iterates over tree elements */
20786
20787  /* Initialize the trees. */
20788  for (n = 0; n < L_CODES;  n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
20789  for (n = 0; n < D_CODES;  n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
20790  for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
20791
20792  s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
20793  s.opt_len = s.static_len = 0;
20794  s.last_lit = s.matches = 0;
20795}
20796
20797
20798/* ===========================================================================
20799 * Flush the bit buffer and align the output on a byte boundary
20800 */
20801function bi_windup(s)
20802{
20803  if (s.bi_valid > 8) {
20804    put_short(s, s.bi_buf);
20805  } else if (s.bi_valid > 0) {
20806    //put_byte(s, (Byte)s->bi_buf);
20807    s.pending_buf[s.pending++] = s.bi_buf;
20808  }
20809  s.bi_buf = 0;
20810  s.bi_valid = 0;
20811}
20812
20813/* ===========================================================================
20814 * Copy a stored block, storing first the length and its
20815 * one's complement if requested.
20816 */
20817function copy_block(s, buf, len, header)
20818//DeflateState *s;
20819//charf    *buf;    /* the input data */
20820//unsigned len;     /* its length */
20821//int      header;  /* true if block header must be written */
20822{
20823  bi_windup(s);        /* align on byte boundary */
20824
20825  if (header) {
20826    put_short(s, len);
20827    put_short(s, ~len);
20828  }
20829//  while (len--) {
20830//    put_byte(s, *buf++);
20831//  }
20832  utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
20833  s.pending += len;
20834}
20835
20836/* ===========================================================================
20837 * Compares to subtrees, using the tree depth as tie breaker when
20838 * the subtrees have equal frequency. This minimizes the worst case length.
20839 */
20840function smaller(tree, n, m, depth) {
20841  var _n2 = n * 2;
20842  var _m2 = m * 2;
20843  return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
20844         (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
20845}
20846
20847/* ===========================================================================
20848 * Restore the heap property by moving down the tree starting at node k,
20849 * exchanging a node with the smallest of its two sons if necessary, stopping
20850 * when the heap property is re-established (each father smaller than its
20851 * two sons).
20852 */
20853function pqdownheap(s, tree, k)
20854//    deflate_state *s;
20855//    ct_data *tree;  /* the tree to restore */
20856//    int k;               /* node to move down */
20857{
20858  var v = s.heap[k];
20859  var j = k << 1;  /* left son of k */
20860  while (j <= s.heap_len) {
20861    /* Set j to the smallest of the two sons: */
20862    if (j < s.heap_len &&
20863      smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
20864      j++;
20865    }
20866    /* Exit if v is smaller than both sons */
20867    if (smaller(tree, v, s.heap[j], s.depth)) { break; }
20868
20869    /* Exchange v with the smallest son */
20870    s.heap[k] = s.heap[j];
20871    k = j;
20872
20873    /* And continue down the tree, setting j to the left son of k */
20874    j <<= 1;
20875  }
20876  s.heap[k] = v;
20877}
20878
20879
20880// inlined manually
20881// var SMALLEST = 1;
20882
20883/* ===========================================================================
20884 * Send the block data compressed using the given Huffman trees
20885 */
20886function compress_block(s, ltree, dtree)
20887//    deflate_state *s;
20888//    const ct_data *ltree; /* literal tree */
20889//    const ct_data *dtree; /* distance tree */
20890{
20891  var dist;           /* distance of matched string */
20892  var lc;             /* match length or unmatched char (if dist == 0) */
20893  var lx = 0;         /* running index in l_buf */
20894  var code;           /* the code to send */
20895  var extra;          /* number of extra bits to send */
20896
20897  if (s.last_lit !== 0) {
20898    do {
20899      dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
20900      lc = s.pending_buf[s.l_buf + lx];
20901      lx++;
20902
20903      if (dist === 0) {
20904        send_code(s, lc, ltree); /* send a literal byte */
20905        //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
20906      } else {
20907        /* Here, lc is the match length - MIN_MATCH */
20908        code = _length_code[lc];
20909        send_code(s, code + LITERALS + 1, ltree); /* send the length code */
20910        extra = extra_lbits[code];
20911        if (extra !== 0) {
20912          lc -= base_length[code];
20913          send_bits(s, lc, extra);       /* send the extra length bits */
20914        }
20915        dist--; /* dist is now the match distance - 1 */
20916        code = d_code(dist);
20917        //Assert (code < D_CODES, "bad d_code");
20918
20919        send_code(s, code, dtree);       /* send the distance code */
20920        extra = extra_dbits[code];
20921        if (extra !== 0) {
20922          dist -= base_dist[code];
20923          send_bits(s, dist, extra);   /* send the extra distance bits */
20924        }
20925      } /* literal or match pair ? */
20926
20927      /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
20928      //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
20929      //       "pendingBuf overflow");
20930
20931    } while (lx < s.last_lit);
20932  }
20933
20934  send_code(s, END_BLOCK, ltree);
20935}
20936
20937
20938/* ===========================================================================
20939 * Construct one Huffman tree and assigns the code bit strings and lengths.
20940 * Update the total bit length for the current block.
20941 * IN assertion: the field freq is set for all tree elements.
20942 * OUT assertions: the fields len and code are set to the optimal bit length
20943 *     and corresponding code. The length opt_len is updated; static_len is
20944 *     also updated if stree is not null. The field max_code is set.
20945 */
20946function build_tree(s, desc)
20947//    deflate_state *s;
20948//    tree_desc *desc; /* the tree descriptor */
20949{
20950  var tree     = desc.dyn_tree;
20951  var stree    = desc.stat_desc.static_tree;
20952  var has_stree = desc.stat_desc.has_stree;
20953  var elems    = desc.stat_desc.elems;
20954  var n, m;          /* iterate over heap elements */
20955  var max_code = -1; /* largest code with non zero frequency */
20956  var node;          /* new node being created */
20957
20958  /* Construct the initial heap, with least frequent element in
20959   * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
20960   * heap[0] is not used.
20961   */
20962  s.heap_len = 0;
20963  s.heap_max = HEAP_SIZE;
20964
20965  for (n = 0; n < elems; n++) {
20966    if (tree[n * 2]/*.Freq*/ !== 0) {
20967      s.heap[++s.heap_len] = max_code = n;
20968      s.depth[n] = 0;
20969
20970    } else {
20971      tree[n * 2 + 1]/*.Len*/ = 0;
20972    }
20973  }
20974
20975  /* The pkzip format requires that at least one distance code exists,
20976   * and that at least one bit should be sent even if there is only one
20977   * possible code. So to avoid special checks later on we force at least
20978   * two codes of non zero frequency.
20979   */
20980  while (s.heap_len < 2) {
20981    node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
20982    tree[node * 2]/*.Freq*/ = 1;
20983    s.depth[node] = 0;
20984    s.opt_len--;
20985
20986    if (has_stree) {
20987      s.static_len -= stree[node * 2 + 1]/*.Len*/;
20988    }
20989    /* node is 0 or 1 so it does not have extra bits */
20990  }
20991  desc.max_code = max_code;
20992
20993  /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
20994   * establish sub-heaps of increasing lengths:
20995   */
20996  for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
20997
20998  /* Construct the Huffman tree by repeatedly combining the least two
20999   * frequent nodes.
21000   */
21001  node = elems;              /* next internal node of the tree */
21002  do {
21003    //pqremove(s, tree, n);  /* n = node of least frequency */
21004    /*** pqremove ***/
21005    n = s.heap[1/*SMALLEST*/];
21006    s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
21007    pqdownheap(s, tree, 1/*SMALLEST*/);
21008    /***/
21009
21010    m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
21011
21012    s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
21013    s.heap[--s.heap_max] = m;
21014
21015    /* Create a new node father of n and m */
21016    tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
21017    s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
21018    tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
21019
21020    /* and insert the new node in the heap */
21021    s.heap[1/*SMALLEST*/] = node++;
21022    pqdownheap(s, tree, 1/*SMALLEST*/);
21023
21024  } while (s.heap_len >= 2);
21025
21026  s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
21027
21028  /* At this point, the fields freq and dad are set. We can now
21029   * generate the bit lengths.
21030   */
21031  gen_bitlen(s, desc);
21032
21033  /* The field len is now set, we can generate the bit codes */
21034  gen_codes(tree, max_code, s.bl_count);
21035}
21036
21037
21038/* ===========================================================================
21039 * Scan a literal or distance tree to determine the frequencies of the codes
21040 * in the bit length tree.
21041 */
21042function scan_tree(s, tree, max_code)
21043//    deflate_state *s;
21044//    ct_data *tree;   /* the tree to be scanned */
21045//    int max_code;    /* and its largest code of non zero frequency */
21046{
21047  var n;                     /* iterates over all tree elements */
21048  var prevlen = -1;          /* last emitted length */
21049  var curlen;                /* length of current code */
21050
21051  var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
21052
21053  var count = 0;             /* repeat count of the current code */
21054  var max_count = 7;         /* max repeat count */
21055  var min_count = 4;         /* min repeat count */
21056
21057  if (nextlen === 0) {
21058    max_count = 138;
21059    min_count = 3;
21060  }
21061  tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
21062
21063  for (n = 0; n <= max_code; n++) {
21064    curlen = nextlen;
21065    nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
21066
21067    if (++count < max_count && curlen === nextlen) {
21068      continue;
21069
21070    } else if (count < min_count) {
21071      s.bl_tree[curlen * 2]/*.Freq*/ += count;
21072
21073    } else if (curlen !== 0) {
21074
21075      if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
21076      s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
21077
21078    } else if (count <= 10) {
21079      s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
21080
21081    } else {
21082      s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
21083    }
21084
21085    count = 0;
21086    prevlen = curlen;
21087
21088    if (nextlen === 0) {
21089      max_count = 138;
21090      min_count = 3;
21091
21092    } else if (curlen === nextlen) {
21093      max_count = 6;
21094      min_count = 3;
21095
21096    } else {
21097      max_count = 7;
21098      min_count = 4;
21099    }
21100  }
21101}
21102
21103
21104/* ===========================================================================
21105 * Send a literal or distance tree in compressed form, using the codes in
21106 * bl_tree.
21107 */
21108function send_tree(s, tree, max_code)
21109//    deflate_state *s;
21110//    ct_data *tree; /* the tree to be scanned */
21111//    int max_code;       /* and its largest code of non zero frequency */
21112{
21113  var n;                     /* iterates over all tree elements */
21114  var prevlen = -1;          /* last emitted length */
21115  var curlen;                /* length of current code */
21116
21117  var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
21118
21119  var count = 0;             /* repeat count of the current code */
21120  var max_count = 7;         /* max repeat count */
21121  var min_count = 4;         /* min repeat count */
21122
21123  /* tree[max_code+1].Len = -1; */  /* guard already set */
21124  if (nextlen === 0) {
21125    max_count = 138;
21126    min_count = 3;
21127  }
21128
21129  for (n = 0; n <= max_code; n++) {
21130    curlen = nextlen;
21131    nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
21132
21133    if (++count < max_count && curlen === nextlen) {
21134      continue;
21135
21136    } else if (count < min_count) {
21137      do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
21138
21139    } else if (curlen !== 0) {
21140      if (curlen !== prevlen) {
21141        send_code(s, curlen, s.bl_tree);
21142        count--;
21143      }
21144      //Assert(count >= 3 && count <= 6, " 3_6?");
21145      send_code(s, REP_3_6, s.bl_tree);
21146      send_bits(s, count - 3, 2);
21147
21148    } else if (count <= 10) {
21149      send_code(s, REPZ_3_10, s.bl_tree);
21150      send_bits(s, count - 3, 3);
21151
21152    } else {
21153      send_code(s, REPZ_11_138, s.bl_tree);
21154      send_bits(s, count - 11, 7);
21155    }
21156
21157    count = 0;
21158    prevlen = curlen;
21159    if (nextlen === 0) {
21160      max_count = 138;
21161      min_count = 3;
21162
21163    } else if (curlen === nextlen) {
21164      max_count = 6;
21165      min_count = 3;
21166
21167    } else {
21168      max_count = 7;
21169      min_count = 4;
21170    }
21171  }
21172}
21173
21174
21175/* ===========================================================================
21176 * Construct the Huffman tree for the bit lengths and return the index in
21177 * bl_order of the last bit length code to send.
21178 */
21179function build_bl_tree(s) {
21180  var max_blindex;  /* index of last bit length code of non zero freq */
21181
21182  /* Determine the bit length frequencies for literal and distance trees */
21183  scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
21184  scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
21185
21186  /* Build the bit length tree: */
21187  build_tree(s, s.bl_desc);
21188  /* opt_len now includes the length of the tree representations, except
21189   * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
21190   */
21191
21192  /* Determine the number of bit length codes to send. The pkzip format
21193   * requires that at least 4 bit length codes be sent. (appnote.txt says
21194   * 3 but the actual value used is 4.)
21195   */
21196  for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
21197    if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
21198      break;
21199    }
21200  }
21201  /* Update opt_len to include the bit length tree and counts */
21202  s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
21203  //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
21204  //        s->opt_len, s->static_len));
21205
21206  return max_blindex;
21207}
21208
21209
21210/* ===========================================================================
21211 * Send the header for a block using dynamic Huffman trees: the counts, the
21212 * lengths of the bit length codes, the literal tree and the distance tree.
21213 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
21214 */
21215function send_all_trees(s, lcodes, dcodes, blcodes)
21216//    deflate_state *s;
21217//    int lcodes, dcodes, blcodes; /* number of codes for each tree */
21218{
21219  var rank;                    /* index in bl_order */
21220
21221  //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
21222  //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
21223  //        "too many codes");
21224  //Tracev((stderr, "\nbl counts: "));
21225  send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
21226  send_bits(s, dcodes - 1,   5);
21227  send_bits(s, blcodes - 4,  4); /* not -3 as stated in appnote.txt */
21228  for (rank = 0; rank < blcodes; rank++) {
21229    //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
21230    send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
21231  }
21232  //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
21233
21234  send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
21235  //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
21236
21237  send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
21238  //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
21239}
21240
21241
21242/* ===========================================================================
21243 * Check if the data type is TEXT or BINARY, using the following algorithm:
21244 * - TEXT if the two conditions below are satisfied:
21245 *    a) There are no non-portable control characters belonging to the
21246 *       "black list" (0..6, 14..25, 28..31).
21247 *    b) There is at least one printable character belonging to the
21248 *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
21249 * - BINARY otherwise.
21250 * - The following partially-portable control characters form a
21251 *   "gray list" that is ignored in this detection algorithm:
21252 *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
21253 * IN assertion: the fields Freq of dyn_ltree are set.
21254 */
21255function detect_data_type(s) {
21256  /* black_mask is the bit mask of black-listed bytes
21257   * set bits 0..6, 14..25, and 28..31
21258   * 0xf3ffc07f = binary 11110011111111111100000001111111
21259   */
21260  var black_mask = 0xf3ffc07f;
21261  var n;
21262
21263  /* Check for non-textual ("black-listed") bytes. */
21264  for (n = 0; n <= 31; n++, black_mask >>>= 1) {
21265    if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
21266      return Z_BINARY;
21267    }
21268  }
21269
21270  /* Check for textual ("white-listed") bytes. */
21271  if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
21272      s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
21273    return Z_TEXT;
21274  }
21275  for (n = 32; n < LITERALS; n++) {
21276    if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
21277      return Z_TEXT;
21278    }
21279  }
21280
21281  /* There are no "black-listed" or "white-listed" bytes:
21282   * this stream either is empty or has tolerated ("gray-listed") bytes only.
21283   */
21284  return Z_BINARY;
21285}
21286
21287
21288var static_init_done = false;
21289
21290/* ===========================================================================
21291 * Initialize the tree data structures for a new zlib stream.
21292 */
21293function _tr_init(s)
21294{
21295
21296  if (!static_init_done) {
21297    tr_static_init();
21298    static_init_done = true;
21299  }
21300
21301  s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);
21302  s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);
21303  s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
21304
21305  s.bi_buf = 0;
21306  s.bi_valid = 0;
21307
21308  /* Initialize the first block of the first file: */
21309  init_block(s);
21310}
21311
21312
21313/* ===========================================================================
21314 * Send a stored block
21315 */
21316function _tr_stored_block(s, buf, stored_len, last)
21317//DeflateState *s;
21318//charf *buf;       /* input block */
21319//ulg stored_len;   /* length of input block */
21320//int last;         /* one if this is the last block for a file */
21321{
21322  send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);    /* send block type */
21323  copy_block(s, buf, stored_len, true); /* with header */
21324}
21325
21326
21327/* ===========================================================================
21328 * Send one empty static block to give enough lookahead for inflate.
21329 * This takes 10 bits, of which 7 may remain in the bit buffer.
21330 */
21331function _tr_align(s) {
21332  send_bits(s, STATIC_TREES << 1, 3);
21333  send_code(s, END_BLOCK, static_ltree);
21334  bi_flush(s);
21335}
21336
21337
21338/* ===========================================================================
21339 * Determine the best encoding for the current block: dynamic trees, static
21340 * trees or store, and output the encoded block to the zip file.
21341 */
21342function _tr_flush_block(s, buf, stored_len, last)
21343//DeflateState *s;
21344//charf *buf;       /* input block, or NULL if too old */
21345//ulg stored_len;   /* length of input block */
21346//int last;         /* one if this is the last block for a file */
21347{
21348  var opt_lenb, static_lenb;  /* opt_len and static_len in bytes */
21349  var max_blindex = 0;        /* index of last bit length code of non zero freq */
21350
21351  /* Build the Huffman trees unless a stored block is forced */
21352  if (s.level > 0) {
21353
21354    /* Check if the file is binary or text */
21355    if (s.strm.data_type === Z_UNKNOWN) {
21356      s.strm.data_type = detect_data_type(s);
21357    }
21358
21359    /* Construct the literal and distance trees */
21360    build_tree(s, s.l_desc);
21361    // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
21362    //        s->static_len));
21363
21364    build_tree(s, s.d_desc);
21365    // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
21366    //        s->static_len));
21367    /* At this point, opt_len and static_len are the total bit lengths of
21368     * the compressed block data, excluding the tree representations.
21369     */
21370
21371    /* Build the bit length tree for the above two trees, and get the index
21372     * in bl_order of the last bit length code to send.
21373     */
21374    max_blindex = build_bl_tree(s);
21375
21376    /* Determine the best encoding. Compute the block lengths in bytes. */
21377    opt_lenb = (s.opt_len + 3 + 7) >>> 3;
21378    static_lenb = (s.static_len + 3 + 7) >>> 3;
21379
21380    // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
21381    //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
21382    //        s->last_lit));
21383
21384    if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
21385
21386  } else {
21387    // Assert(buf != (char*)0, "lost buf");
21388    opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
21389  }
21390
21391  if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
21392    /* 4: two words for the lengths */
21393
21394    /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
21395     * Otherwise we can't have processed more than WSIZE input bytes since
21396     * the last block flush, because compression would have been
21397     * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
21398     * transform a block into a stored block.
21399     */
21400    _tr_stored_block(s, buf, stored_len, last);
21401
21402  } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
21403
21404    send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
21405    compress_block(s, static_ltree, static_dtree);
21406
21407  } else {
21408    send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
21409    send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
21410    compress_block(s, s.dyn_ltree, s.dyn_dtree);
21411  }
21412  // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
21413  /* The above check is made mod 2^32, for files larger than 512 MB
21414   * and uLong implemented on 32 bits.
21415   */
21416  init_block(s);
21417
21418  if (last) {
21419    bi_windup(s);
21420  }
21421  // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
21422  //       s->compressed_len-7*last));
21423}
21424
21425/* ===========================================================================
21426 * Save the match info and tally the frequency counts. Return true if
21427 * the current block must be flushed.
21428 */
21429function _tr_tally(s, dist, lc)
21430//    deflate_state *s;
21431//    unsigned dist;  /* distance of matched string */
21432//    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
21433{
21434  //var out_length, in_length, dcode;
21435
21436  s.pending_buf[s.d_buf + s.last_lit * 2]     = (dist >>> 8) & 0xff;
21437  s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
21438
21439  s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
21440  s.last_lit++;
21441
21442  if (dist === 0) {
21443    /* lc is the unmatched char */
21444    s.dyn_ltree[lc * 2]/*.Freq*/++;
21445  } else {
21446    s.matches++;
21447    /* Here, lc is the match length - MIN_MATCH */
21448    dist--;             /* dist = match distance - 1 */
21449    //Assert((ush)dist < (ush)MAX_DIST(s) &&
21450    //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
21451    //       (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
21452
21453    s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
21454    s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
21455  }
21456
21457// (!) This block is disabled in zlib defaults,
21458// don't enable it for binary compatibility
21459
21460//#ifdef TRUNCATE_BLOCK
21461//  /* Try to guess if it is profitable to stop the current block here */
21462//  if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
21463//    /* Compute an upper bound for the compressed length */
21464//    out_length = s.last_lit*8;
21465//    in_length = s.strstart - s.block_start;
21466//
21467//    for (dcode = 0; dcode < D_CODES; dcode++) {
21468//      out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
21469//    }
21470//    out_length >>>= 3;
21471//    //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
21472//    //       s->last_lit, in_length, out_length,
21473//    //       100L - out_length*100L/in_length));
21474//    if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
21475//      return true;
21476//    }
21477//  }
21478//#endif
21479
21480  return (s.last_lit === s.lit_bufsize - 1);
21481  /* We avoid equality with lit_bufsize because of wraparound at 64K
21482   * on 16 bit machines and because stored blocks are restricted to
21483   * 64K-1 bytes.
21484   */
21485}
21486
21487exports._tr_init  = _tr_init;
21488exports._tr_stored_block = _tr_stored_block;
21489exports._tr_flush_block  = _tr_flush_block;
21490exports._tr_tally = _tr_tally;
21491exports._tr_align = _tr_align;
21492
21493},{"../utils/common":54}],66:[function(require,module,exports){
21494'use strict';
21495
21496// (C) 1995-2013 Jean-loup Gailly and Mark Adler
21497// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
21498//
21499// This software is provided 'as-is', without any express or implied
21500// warranty. In no event will the authors be held liable for any damages
21501// arising from the use of this software.
21502//
21503// Permission is granted to anyone to use this software for any purpose,
21504// including commercial applications, and to alter it and redistribute it
21505// freely, subject to the following restrictions:
21506//
21507// 1. The origin of this software must not be misrepresented; you must not
21508//   claim that you wrote the original software. If you use this software
21509//   in a product, an acknowledgment in the product documentation would be
21510//   appreciated but is not required.
21511// 2. Altered source versions must be plainly marked as such, and must not be
21512//   misrepresented as being the original software.
21513// 3. This notice may not be removed or altered from any source distribution.
21514
21515function ZStream() {
21516  /* next input byte */
21517  this.input = null; // JS specific, because we have no pointers
21518  this.next_in = 0;
21519  /* number of bytes available at input */
21520  this.avail_in = 0;
21521  /* total number of input bytes read so far */
21522  this.total_in = 0;
21523  /* next output byte should be put there */
21524  this.output = null; // JS specific, because we have no pointers
21525  this.next_out = 0;
21526  /* remaining free space at output */
21527  this.avail_out = 0;
21528  /* total number of bytes output so far */
21529  this.total_out = 0;
21530  /* last error message, NULL if no error */
21531  this.msg = ''/*Z_NULL*/;
21532  /* not visible by applications */
21533  this.state = null;
21534  /* best guess about the data type: binary or text */
21535  this.data_type = 2/*Z_UNKNOWN*/;
21536  /* adler32 value of the uncompressed data */
21537  this.adler = 0;
21538}
21539
21540module.exports = ZStream;
21541
21542},{}],67:[function(require,module,exports){
21543// shim for using process in browser
21544var process = module.exports = {};
21545
21546// cached from whatever global is present so that test runners that stub it
21547// don't break things.  But we need to wrap it in a try catch in case it is
21548// wrapped in strict mode code which doesn't define any globals.  It's inside a
21549// function because try/catches deoptimize in certain engines.
21550
21551var cachedSetTimeout;
21552var cachedClearTimeout;
21553
21554function defaultSetTimout() {
21555    throw new Error('setTimeout has not been defined');
21556}
21557function defaultClearTimeout () {
21558    throw new Error('clearTimeout has not been defined');
21559}
21560(function () {
21561    try {
21562        if (typeof setTimeout === 'function') {
21563            cachedSetTimeout = setTimeout;
21564        } else {
21565            cachedSetTimeout = defaultSetTimout;
21566        }
21567    } catch (e) {
21568        cachedSetTimeout = defaultSetTimout;
21569    }
21570    try {
21571        if (typeof clearTimeout === 'function') {
21572            cachedClearTimeout = clearTimeout;
21573        } else {
21574            cachedClearTimeout = defaultClearTimeout;
21575        }
21576    } catch (e) {
21577        cachedClearTimeout = defaultClearTimeout;
21578    }
21579} ())
21580function runTimeout(fun) {
21581    if (cachedSetTimeout === setTimeout) {
21582        //normal enviroments in sane situations
21583        return setTimeout(fun, 0);
21584    }
21585    // if setTimeout wasn't available but was latter defined
21586    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
21587        cachedSetTimeout = setTimeout;
21588        return setTimeout(fun, 0);
21589    }
21590    try {
21591        // when when somebody has screwed with setTimeout but no I.E. maddness
21592        return cachedSetTimeout(fun, 0);
21593    } catch(e){
21594        try {
21595            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
21596            return cachedSetTimeout.call(null, fun, 0);
21597        } catch(e){
21598            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
21599            return cachedSetTimeout.call(this, fun, 0);
21600        }
21601    }
21602
21603
21604}
21605function runClearTimeout(marker) {
21606    if (cachedClearTimeout === clearTimeout) {
21607        //normal enviroments in sane situations
21608        return clearTimeout(marker);
21609    }
21610    // if clearTimeout wasn't available but was latter defined
21611    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
21612        cachedClearTimeout = clearTimeout;
21613        return clearTimeout(marker);
21614    }
21615    try {
21616        // when when somebody has screwed with setTimeout but no I.E. maddness
21617        return cachedClearTimeout(marker);
21618    } catch (e){
21619        try {
21620            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
21621            return cachedClearTimeout.call(null, marker);
21622        } catch (e){
21623            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
21624            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
21625            return cachedClearTimeout.call(this, marker);
21626        }
21627    }
21628
21629
21630
21631}
21632var queue = [];
21633var draining = false;
21634var currentQueue;
21635var queueIndex = -1;
21636
21637function cleanUpNextTick() {
21638    if (!draining || !currentQueue) {
21639        return;
21640    }
21641    draining = false;
21642    if (currentQueue.length) {
21643        queue = currentQueue.concat(queue);
21644    } else {
21645        queueIndex = -1;
21646    }
21647    if (queue.length) {
21648        drainQueue();
21649    }
21650}
21651
21652function drainQueue() {
21653    if (draining) {
21654        return;
21655    }
21656    var timeout = runTimeout(cleanUpNextTick);
21657    draining = true;
21658
21659    var len = queue.length;
21660    while(len) {
21661        currentQueue = queue;
21662        queue = [];
21663        while (++queueIndex < len) {
21664            if (currentQueue) {
21665                currentQueue[queueIndex].run();
21666            }
21667        }
21668        queueIndex = -1;
21669        len = queue.length;
21670    }
21671    currentQueue = null;
21672    draining = false;
21673    runClearTimeout(timeout);
21674}
21675
21676process.nextTick = function (fun) {
21677    var args = new Array(arguments.length - 1);
21678    if (arguments.length > 1) {
21679        for (var i = 1; i < arguments.length; i++) {
21680            args[i - 1] = arguments[i];
21681        }
21682    }
21683    queue.push(new Item(fun, args));
21684    if (queue.length === 1 && !draining) {
21685        runTimeout(drainQueue);
21686    }
21687};
21688
21689// v8 likes predictible objects
21690function Item(fun, array) {
21691    this.fun = fun;
21692    this.array = array;
21693}
21694Item.prototype.run = function () {
21695    this.fun.apply(null, this.array);
21696};
21697process.title = 'browser';
21698process.browser = true;
21699process.env = {};
21700process.argv = [];
21701process.version = ''; // empty string to avoid regexp issues
21702process.versions = {};
21703
21704function noop() {}
21705
21706process.on = noop;
21707process.addListener = noop;
21708process.once = noop;
21709process.off = noop;
21710process.removeListener = noop;
21711process.removeAllListeners = noop;
21712process.emit = noop;
21713process.prependListener = noop;
21714process.prependOnceListener = noop;
21715
21716process.listeners = function (name) { return [] }
21717
21718process.binding = function (name) {
21719    throw new Error('process.binding is not supported');
21720};
21721
21722process.cwd = function () { return '/' };
21723process.chdir = function (dir) {
21724    throw new Error('process.chdir is not supported');
21725};
21726process.umask = function() { return 0; };
21727
21728},{}],68:[function(require,module,exports){
21729'use strict';
21730
21731/*
21732node-bzip - a pure-javascript Node.JS module for decoding bzip2 data
21733
21734Copyright (C) 2012 Eli Skeggs
21735
21736This library is free software; you can redistribute it and/or
21737modify it under the terms of the GNU Lesser General Public
21738License as published by the Free Software Foundation; either
21739version 2.1 of the License, or (at your option) any later version.
21740
21741This library is distributed in the hope that it will be useful,
21742but WITHOUT ANY WARRANTY; without even the implied warranty of
21743MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21744Lesser General Public License for more details.
21745
21746You should have received a copy of the GNU Lesser General Public
21747License along with this library; if not, see
21748http://www.gnu.org/licenses/lgpl-2.1.html
21749
21750Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).
21751
21752Based on micro-bunzip by Rob Landley (rob@landley.net).
21753
21754Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
21755which also acknowledges contributions by Mike Burrows, David Wheeler,
21756Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
21757Robert Sedgewick, and Jon L. Bentley.
21758*/
21759
21760var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];
21761
21762// offset in bytes
21763var BitReader = function BitReader(stream) {
21764  this.stream = stream;
21765  this.bitOffset = 0;
21766  this.curByte = 0;
21767  this.hasByte = false;
21768};
21769
21770BitReader.prototype._ensureByte = function () {
21771  if (!this.hasByte) {
21772    this.curByte = this.stream.readByte();
21773    this.hasByte = true;
21774  }
21775};
21776
21777// reads bits from the buffer
21778BitReader.prototype.read = function (bits) {
21779  var result = 0;
21780  while (bits > 0) {
21781    this._ensureByte();
21782    var remaining = 8 - this.bitOffset;
21783    // if we're in a byte
21784    if (bits >= remaining) {
21785      result <<= remaining;
21786      result |= BITMASK[remaining] & this.curByte;
21787      this.hasByte = false;
21788      this.bitOffset = 0;
21789      bits -= remaining;
21790    } else {
21791      result <<= bits;
21792      var shift = remaining - bits;
21793      result |= (this.curByte & BITMASK[bits] << shift) >> shift;
21794      this.bitOffset += bits;
21795      bits = 0;
21796    }
21797  }
21798  return result;
21799};
21800
21801// seek to an arbitrary point in the buffer (expressed in bits)
21802BitReader.prototype.seek = function (pos) {
21803  var n_bit = pos % 8;
21804  var n_byte = (pos - n_bit) / 8;
21805  this.bitOffset = n_bit;
21806  this.stream.seek(n_byte);
21807  this.hasByte = false;
21808};
21809
21810// reads 6 bytes worth of data using the read method
21811BitReader.prototype.pi = function () {
21812  var buf = new Uint8Array(6),
21813      i;
21814  for (i = 0; i < buf.length; i++) {
21815    buf[i] = this.read(8);
21816  }
21817  return bufToHex(buf);
21818};
21819
21820function bufToHex(buf) {
21821  return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');
21822}
21823
21824module.exports = BitReader;
21825
21826},{}],69:[function(require,module,exports){
21827"use strict";
21828
21829/* CRC32, used in Bzip2 implementation.
21830 * This is a port of CRC32.java from the jbzip2 implementation at
21831 *   https://code.google.com/p/jbzip2
21832 * which is:
21833 *   Copyright (c) 2011 Matthew Francis
21834 *
21835 *   Permission is hereby granted, free of charge, to any person
21836 *   obtaining a copy of this software and associated documentation
21837 *   files (the "Software"), to deal in the Software without
21838 *   restriction, including without limitation the rights to use,
21839 *   copy, modify, merge, publish, distribute, sublicense, and/or sell
21840 *   copies of the Software, and to permit persons to whom the
21841 *   Software is furnished to do so, subject to the following
21842 *   conditions:
21843 *
21844 *   The above copyright notice and this permission notice shall be
21845 *   included in all copies or substantial portions of the Software.
21846 *
21847 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21848 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
21849 *   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21850 *   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21851 *   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21852 *   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21853 *   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21854 *   OTHER DEALINGS IN THE SOFTWARE.
21855 * This JavaScript implementation is:
21856 *   Copyright (c) 2013 C. Scott Ananian
21857 * with the same licensing terms as Matthew Francis' original implementation.
21858 */
21859module.exports = function () {
21860
21861  /**
21862   * A static CRC lookup table
21863   */
21864  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]);
21865
21866  var CRC32 = function CRC32() {
21867    /**
21868     * The current CRC
21869     */
21870    var crc = 0xffffffff;
21871
21872    /**
21873     * @return The current CRC
21874     */
21875    this.getCRC = function () {
21876      return ~crc >>> 0; // return an unsigned value
21877    };
21878
21879    /**
21880     * Update the CRC with a single byte
21881     * @param value The value to update the CRC with
21882     */
21883    this.updateCRC = function (value) {
21884      crc = crc << 8 ^ crc32Lookup[(crc >>> 24 ^ value) & 0xff];
21885    };
21886
21887    /**
21888     * Update the CRC with a sequence of identical bytes
21889     * @param value The value to update the CRC with
21890     * @param count The number of bytes
21891     */
21892    this.updateCRCRun = function (value, count) {
21893      while (count-- > 0) {
21894        crc = crc << 8 ^ crc32Lookup[(crc >>> 24 ^ value) & 0xff];
21895      }
21896    };
21897  };
21898  return CRC32;
21899}();
21900
21901},{}],70:[function(require,module,exports){
21902'use strict';
21903
21904/*
21905seek-bzip - a pure-javascript module for seeking within bzip2 data
21906
21907Copyright (C) 2013 C. Scott Ananian
21908Copyright (C) 2012 Eli Skeggs
21909Copyright (C) 2011 Kevin Kwok
21910
21911This library is free software; you can redistribute it and/or
21912modify it under the terms of the GNU Lesser General Public
21913License as published by the Free Software Foundation; either
21914version 2.1 of the License, or (at your option) any later version.
21915
21916This library is distributed in the hope that it will be useful,
21917but WITHOUT ANY WARRANTY; without even the implied warranty of
21918MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21919Lesser General Public License for more details.
21920
21921You should have received a copy of the GNU Lesser General Public
21922License along with this library; if not, see
21923http://www.gnu.org/licenses/lgpl-2.1.html
21924
21925Adapted from node-bzip, copyright 2012 Eli Skeggs.
21926Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).
21927
21928Based on micro-bunzip by Rob Landley (rob@landley.net).
21929
21930Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
21931which also acknowledges contributions by Mike Burrows, David Wheeler,
21932Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
21933Robert Sedgewick, and Jon L. Bentley.
21934*/
21935
21936var BitReader = require('./bitreader');
21937var Stream = require('./stream');
21938var CRC32 = require('./crc32');
21939
21940var MAX_HUFCODE_BITS = 20;
21941var MAX_SYMBOLS = 258;
21942var SYMBOL_RUNA = 0;
21943var SYMBOL_RUNB = 1;
21944var MIN_GROUPS = 2;
21945var MAX_GROUPS = 6;
21946var GROUP_SIZE = 50;
21947
21948var WHOLEPI = "314159265359";
21949var SQRTPI = "177245385090";
21950
21951var mtf = function mtf(array, index) {
21952  var src = array[index],
21953      i;
21954  for (i = index; i > 0; i--) {
21955    array[i] = array[i - 1];
21956  }
21957  array[0] = src;
21958  return src;
21959};
21960
21961var Err = {
21962  OK: 0,
21963  LAST_BLOCK: -1,
21964  NOT_BZIP_DATA: -2,
21965  UNEXPECTED_INPUT_EOF: -3,
21966  UNEXPECTED_OUTPUT_EOF: -4,
21967  DATA_ERROR: -5,
21968  OUT_OF_MEMORY: -6,
21969  OBSOLETE_INPUT: -7,
21970  END_OF_BLOCK: -8
21971};
21972var ErrorMessages = {};
21973ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum";
21974ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data";
21975ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF";
21976ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF";
21977ErrorMessages[Err.DATA_ERROR] = "Data error";
21978ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory";
21979ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported.";
21980
21981var _throw = function _throw(status, optDetail) {
21982  var msg = ErrorMessages[status] || 'unknown error';
21983  if (optDetail) {
21984    msg += ': ' + optDetail;
21985  }
21986  var e = new TypeError(msg);
21987  e.errorCode = status;
21988  throw e;
21989};
21990
21991var Bunzip = function Bunzip(inputStream, outputStream) {
21992  this.writePos = this.writeCurrent = this.writeCount = 0;
21993
21994  this._start_bunzip(inputStream, outputStream);
21995};
21996Bunzip.prototype._init_block = function () {
21997  var moreBlocks = this._get_next_block();
21998  if (!moreBlocks) {
21999    this.writeCount = -1;
22000    return false; /* no more blocks */
22001  }
22002  this.blockCRC = new CRC32();
22003  return true;
22004};
22005/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */
22006Bunzip.prototype._start_bunzip = function (inputStream, outputStream) {
22007  /* Ensure that file starts with "BZh['1'-'9']." */
22008  var buf = new Uint8Array(4);
22009  if (inputStream.read(buf, 0, 4) !== 4 || String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh') _throw(Err.NOT_BZIP_DATA, 'bad magic');
22010
22011  var level = buf[3] - 0x30;
22012  if (level < 1 || level > 9) _throw(Err.NOT_BZIP_DATA, 'level out of range');
22013
22014  this.reader = new BitReader(inputStream);
22015
22016  /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of
22017     uncompressed data.  Allocate intermediate buffer for block. */
22018  this.dbufSize = 100000 * level;
22019  this.nextoutput = 0;
22020  this.outputStream = outputStream;
22021  this.streamCRC = 0;
22022};
22023Bunzip.prototype._get_next_block = function () {
22024  var i, j, k;
22025  var reader = this.reader;
22026  // this is get_next_block() function from micro-bunzip:
22027  /* Read in header signature and CRC, then validate signature.
22028     (last block signature means CRC is for whole file, return now) */
22029  var h = reader.pi();
22030  if (h === SQRTPI) {
22031    // last block
22032    return false; /* no more blocks */
22033  }
22034  if (h !== WHOLEPI) _throw(Err.NOT_BZIP_DATA);
22035  this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)
22036  this.streamCRC = (this.targetBlockCRC ^ (this.streamCRC << 1 | this.streamCRC >>> 31)) >>> 0;
22037  /* We can add support for blockRandomised if anybody complains.  There was
22038     some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
22039     it didn't actually work. */
22040  if (reader.read(1)) _throw(Err.OBSOLETE_INPUT);
22041  var origPointer = reader.read(24);
22042  if (origPointer > this.dbufSize) _throw(Err.DATA_ERROR, 'initial position out of bounds');
22043  /* mapping table: if some byte values are never used (encoding things
22044     like ascii text), the compression code removes the gaps to have fewer
22045     symbols to deal with, and writes a sparse bitfield indicating which
22046     values were present.  We make a translation table to convert the symbols
22047     back to the corresponding bytes. */
22048  var t = reader.read(16);
22049  var symToByte = new Uint8Array(256),
22050      symTotal = 0;
22051  for (i = 0; i < 16; i++) {
22052    if (t & 1 << 0xF - i) {
22053      var o = i * 16;
22054      k = reader.read(16);
22055      for (j = 0; j < 16; j++) if (k & 1 << 0xF - j) symToByte[symTotal++] = o + j;
22056    }
22057  }
22058
22059  /* How many different huffman coding groups does this block use? */
22060  var groupCount = reader.read(3);
22061  if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS) _throw(Err.DATA_ERROR);
22062  /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding
22063     group.  Read in the group selector list, which is stored as MTF encoded
22064     bit runs.  (MTF=Move To Front, as each value is used it's moved to the
22065     start of the list.) */
22066  var nSelectors = reader.read(15);
22067  if (nSelectors === 0) _throw(Err.DATA_ERROR);
22068
22069  var mtfSymbol = new Uint8Array(256);
22070  for (i = 0; i < groupCount; i++) mtfSymbol[i] = i;
22071
22072  var selectors = new Uint8Array(nSelectors); // was 32768...
22073
22074  for (i = 0; i < nSelectors; i++) {
22075    /* Get next value */
22076    for (j = 0; reader.read(1); j++) if (j >= groupCount) _throw(Err.DATA_ERROR);
22077    /* Decode MTF to get the next selector */
22078    selectors[i] = mtf(mtfSymbol, j);
22079  }
22080
22081  /* Read the huffman coding tables for each group, which code for symTotal
22082     literal symbols, plus two run symbols (RUNA, RUNB) */
22083  var symCount = symTotal + 2;
22084  var groups = [],
22085      hufGroup;
22086  for (j = 0; j < groupCount; j++) {
22087    var length = new Uint8Array(symCount),
22088        temp = new Uint16Array(MAX_HUFCODE_BITS + 1);
22089    /* Read huffman code lengths for each symbol.  They're stored in
22090       a way similar to mtf; record a starting value for the first symbol,
22091       and an offset from the previous value for everys symbol after that. */
22092    t = reader.read(5); // lengths
22093    for (i = 0; i < symCount; i++) {
22094      for (;;) {
22095        if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);
22096        /* If first bit is 0, stop.  Else second bit indicates whether
22097           to increment or decrement the value. */
22098        if (!reader.read(1)) break;
22099        if (!reader.read(1)) t++;else t--;
22100      }
22101      length[i] = t;
22102    }
22103
22104    /* Find largest and smallest lengths in this group */
22105    var minLen, maxLen;
22106    minLen = maxLen = length[0];
22107    for (i = 1; i < symCount; i++) {
22108      if (length[i] > maxLen) maxLen = length[i];else if (length[i] < minLen) minLen = length[i];
22109    }
22110
22111    /* Calculate permute[], base[], and limit[] tables from length[].
22112     *
22113     * permute[] is the lookup table for converting huffman coded symbols
22114     * into decoded symbols.  base[] is the amount to subtract from the
22115     * value of a huffman symbol of a given length when using permute[].
22116     *
22117     * limit[] indicates the largest numerical value a symbol with a given
22118     * number of bits can have.  This is how the huffman codes can vary in
22119     * length: each code with a value>limit[length] needs another bit.
22120     */
22121    hufGroup = {};
22122    groups.push(hufGroup);
22123    hufGroup.permute = new Uint16Array(MAX_SYMBOLS);
22124    hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);
22125    hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);
22126    hufGroup.minLen = minLen;
22127    hufGroup.maxLen = maxLen;
22128    /* Calculate permute[].  Concurently, initialize temp[] and limit[]. */
22129    var pp = 0;
22130    for (i = minLen; i <= maxLen; i++) {
22131      temp[i] = hufGroup.limit[i] = 0;
22132      for (t = 0; t < symCount; t++) if (length[t] === i) hufGroup.permute[pp++] = t;
22133    }
22134    /* Count symbols coded for at each bit length */
22135    for (i = 0; i < symCount; i++) temp[length[i]]++;
22136    /* Calculate limit[] (the largest symbol-coding value at each bit
22137     * length, which is (previous limit<<1)+symbols at this level), and
22138     * base[] (number of symbols to ignore at each bit length, which is
22139     * limit minus the cumulative count of symbols coded for already). */
22140    pp = t = 0;
22141    for (i = minLen; i < maxLen; i++) {
22142      pp += temp[i];
22143      /* We read the largest possible symbol size and then unget bits
22144         after determining how many we need, and those extra bits could
22145         be set to anything.  (They're noise from future symbols.)  At
22146         each level we're really only interested in the first few bits,
22147         so here we set all the trailing to-be-ignored bits to 1 so they
22148         don't affect the value>limit[length] comparison. */
22149      hufGroup.limit[i] = pp - 1;
22150      pp <<= 1;
22151      t += temp[i];
22152      hufGroup.base[i + 1] = pp - t;
22153    }
22154    hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */
22155    hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;
22156    hufGroup.base[minLen] = 0;
22157  }
22158  /* We've finished reading and digesting the block header.  Now read this
22159     block's huffman coded symbols from the file and undo the huffman coding
22160     and run length encoding, saving the result into dbuf[dbufCount++]=uc */
22161
22162  /* Initialize symbol occurrence counters and symbol Move To Front table */
22163  var byteCount = new Uint32Array(256);
22164  for (i = 0; i < 256; i++) mtfSymbol[i] = i;
22165  /* Loop through compressed symbols. */
22166  var runPos = 0,
22167      dbufCount = 0,
22168      selector = 0,
22169      uc;
22170  var dbuf = this.dbuf = new Uint32Array(this.dbufSize);
22171  symCount = 0;
22172  for (;;) {
22173    /* Determine which huffman coding group to use. */
22174    if (!symCount--) {
22175      symCount = GROUP_SIZE - 1;
22176      if (selector >= nSelectors) {
22177        _throw(Err.DATA_ERROR);
22178      }
22179      hufGroup = groups[selectors[selector++]];
22180    }
22181    /* Read next huffman-coded symbol. */
22182    i = hufGroup.minLen;
22183    j = reader.read(i);
22184    for (;; i++) {
22185      if (i > hufGroup.maxLen) {
22186        _throw(Err.DATA_ERROR);
22187      }
22188      if (j <= hufGroup.limit[i]) break;
22189      j = j << 1 | reader.read(1);
22190    }
22191    /* Huffman decode value to get nextSym (with bounds checking) */
22192    j -= hufGroup.base[i];
22193    if (j < 0 || j >= MAX_SYMBOLS) {
22194      _throw(Err.DATA_ERROR);
22195    }
22196    var nextSym = hufGroup.permute[j];
22197    /* We have now decoded the symbol, which indicates either a new literal
22198       byte, or a repeated run of the most recent literal byte.  First,
22199       check if nextSym indicates a repeated run, and if so loop collecting
22200       how many times to repeat the last literal. */
22201    if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {
22202      /* If this is the start of a new run, zero out counter */
22203      if (!runPos) {
22204        runPos = 1;
22205        t = 0;
22206      }
22207      /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
22208         each bit position, add 1 or 2 instead.  For example,
22209         1011 is 1<<0 + 1<<1 + 2<<2.  1010 is 2<<0 + 2<<1 + 1<<2.
22210         You can make any bit pattern that way using 1 less symbol than
22211         the basic or 0/1 method (except all bits 0, which would use no
22212         symbols, but a run of length 0 doesn't mean anything in this
22213         context).  Thus space is saved. */
22214      if (nextSym === SYMBOL_RUNA) t += runPos;else t += 2 * runPos;
22215      runPos <<= 1;
22216      continue;
22217    }
22218    /* When we hit the first non-run symbol after a run, we now know
22219       how many times to repeat the last literal, so append that many
22220       copies to our buffer of decoded symbols (dbuf) now.  (The last
22221       literal used is the one at the head of the mtfSymbol array.) */
22222    if (runPos) {
22223      runPos = 0;
22224      if (dbufCount + t > this.dbufSize) {
22225        _throw(Err.DATA_ERROR);
22226      }
22227      uc = symToByte[mtfSymbol[0]];
22228      byteCount[uc] += t;
22229      while (t--) dbuf[dbufCount++] = uc;
22230    }
22231    /* Is this the terminating symbol? */
22232    if (nextSym > symTotal) break;
22233    /* At this point, nextSym indicates a new literal character.  Subtract
22234       one to get the position in the MTF array at which this literal is
22235       currently to be found.  (Note that the result can't be -1 or 0,
22236       because 0 and 1 are RUNA and RUNB.  But another instance of the
22237       first symbol in the mtf array, position 0, would have been handled
22238       as part of a run above.  Therefore 1 unused mtf position minus
22239       2 non-literal nextSym values equals -1.) */
22240    if (dbufCount >= this.dbufSize) {
22241      _throw(Err.DATA_ERROR);
22242    }
22243    i = nextSym - 1;
22244    uc = mtf(mtfSymbol, i);
22245    uc = symToByte[uc];
22246    /* We have our literal byte.  Save it into dbuf. */
22247    byteCount[uc]++;
22248    dbuf[dbufCount++] = uc;
22249  }
22250  /* At this point, we've read all the huffman-coded symbols (and repeated
22251     runs) for this block from the input stream, and decoded them into the
22252     intermediate buffer.  There are dbufCount many decoded bytes in dbuf[].
22253     Now undo the Burrows-Wheeler transform on dbuf.
22254     See http://dogma.net/markn/articles/bwt/bwt.htm
22255  */
22256  if (origPointer < 0 || origPointer >= dbufCount) {
22257    _throw(Err.DATA_ERROR);
22258  }
22259  /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
22260  j = 0;
22261  for (i = 0; i < 256; i++) {
22262    k = j + byteCount[i];
22263    byteCount[i] = j;
22264    j = k;
22265  }
22266  /* Figure out what order dbuf would be in if we sorted it. */
22267  for (i = 0; i < dbufCount; i++) {
22268    uc = dbuf[i] & 0xff;
22269    dbuf[byteCount[uc]] |= i << 8;
22270    byteCount[uc]++;
22271  }
22272  /* Decode first byte by hand to initialize "previous" byte.  Note that it
22273     doesn't get output, and if the first three characters are identical
22274     it doesn't qualify as a run (hence writeRunCountdown=5). */
22275  var pos = 0,
22276      current = 0,
22277      run = 0;
22278  if (dbufCount) {
22279    pos = dbuf[origPointer];
22280    current = pos & 0xff;
22281    pos >>= 8;
22282    run = -1;
22283  }
22284  this.writePos = pos;
22285  this.writeCurrent = current;
22286  this.writeCount = dbufCount;
22287  this.writeRun = run;
22288
22289  return true; /* more blocks to come */
22290};
22291/* Undo burrows-wheeler transform on intermediate buffer to produce output.
22292   If start_bunzip was initialized with out_fd=-1, then up to len bytes of
22293   data are written to outbuf.  Return value is number of bytes written or
22294   error (all errors are negative numbers).  If out_fd!=-1, outbuf and len
22295   are ignored, data is written to out_fd and return is RETVAL_OK or error.
22296*/
22297Bunzip.prototype._read_bunzip = function (outputBuffer, len) {
22298  var copies, previous, outbyte;
22299  /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully
22300     decoded, which results in this returning RETVAL_LAST_BLOCK, also
22301     equal to -1... Confusing, I'm returning 0 here to indicate no
22302     bytes written into the buffer */
22303  if (this.writeCount < 0) {
22304    return 0;
22305  }
22306
22307  var gotcount = 0;
22308  var dbuf = this.dbuf,
22309      pos = this.writePos,
22310      current = this.writeCurrent;
22311  var dbufCount = this.writeCount,
22312      outputsize = this.outputsize;
22313  var run = this.writeRun;
22314
22315  while (dbufCount) {
22316    dbufCount--;
22317    previous = current;
22318    pos = dbuf[pos];
22319    current = pos & 0xff;
22320    pos >>= 8;
22321    if (run++ === 3) {
22322      copies = current;
22323      outbyte = previous;
22324      current = -1;
22325    } else {
22326      copies = 1;
22327      outbyte = current;
22328    }
22329    this.blockCRC.updateCRCRun(outbyte, copies);
22330    while (copies--) {
22331      this.outputStream.writeByte(outbyte);
22332      this.nextoutput++;
22333    }
22334    if (current != previous) run = 0;
22335  }
22336  this.writeCount = dbufCount;
22337  // check CRC
22338  if (this.blockCRC.getCRC() !== this.targetBlockCRC) {
22339    _throw(Err.DATA_ERROR, "Bad block CRC " + "(got " + this.blockCRC.getCRC().toString(16) + " expected " + this.targetBlockCRC.toString(16) + ")");
22340  }
22341  return this.nextoutput;
22342};
22343
22344var coerceInputStream = function coerceInputStream(input) {
22345  if ('readByte' in input) {
22346    return input;
22347  }
22348  var inputStream = new Stream();
22349  inputStream.pos = 0;
22350  inputStream.readByte = function () {
22351    return input[this.pos++];
22352  };
22353  inputStream.seek = function (pos) {
22354    this.pos = pos;
22355  };
22356  inputStream.eof = function () {
22357    return this.pos >= input.length;
22358  };
22359  return inputStream;
22360};
22361var coerceOutputStream = function coerceOutputStream(output) {
22362  var outputStream = new Stream();
22363  var resizeOk = true;
22364  if (output) {
22365    if (typeof output === 'number') {
22366      outputStream.buffer = new Uint8Array(output);
22367      resizeOk = false;
22368    } else if ('writeByte' in output) {
22369      return output;
22370    } else {
22371      outputStream.buffer = output;
22372      resizeOk = false;
22373    }
22374  } else {
22375    outputStream.buffer = new Uint8Array(16384);
22376  }
22377  outputStream.pos = 0;
22378  outputStream.writeByte = function (_byte) {
22379    if (resizeOk && this.pos >= this.buffer.length) {
22380      var newBuffer = new Uint8Array(this.buffer.length * 2);
22381      newBuffer.set(this.buffer);
22382      this.buffer = newBuffer;
22383    }
22384    this.buffer[this.pos++] = _byte;
22385  };
22386  outputStream.getBuffer = function () {
22387    // trim buffer
22388    if (this.pos !== this.buffer.length) {
22389      if (!resizeOk) throw new TypeError('outputsize does not match decoded input');
22390      var newBuffer = new Uint8Array(this.pos);
22391      newBuffer.set(this.buffer.subarray(0, this.pos));
22392      this.buffer = newBuffer;
22393    }
22394    return this.buffer;
22395  };
22396  outputStream._coerced = true;
22397  return outputStream;
22398};
22399
22400/* Static helper functions */
22401Bunzip.Err = Err;
22402// 'input' can be a stream or a buffer
22403// 'output' can be a stream or a buffer or a number (buffer size)
22404Bunzip.decode = function (input, output, multistream) {
22405  // make a stream from a buffer, if necessary
22406  var inputStream = coerceInputStream(input);
22407  var outputStream = coerceOutputStream(output);
22408
22409  var bz = new Bunzip(inputStream, outputStream);
22410  while (true) {
22411    if ('eof' in inputStream && inputStream.eof()) break;
22412    if (bz._init_block()) {
22413      bz._read_bunzip();
22414    } else {
22415      var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)
22416      if (targetStreamCRC !== bz.streamCRC) {
22417        _throw(Err.DATA_ERROR, "Bad stream CRC " + "(got " + bz.streamCRC.toString(16) + " expected " + targetStreamCRC.toString(16) + ")");
22418      }
22419      if (multistream && 'eof' in inputStream && !inputStream.eof()) {
22420        // note that start_bunzip will also resync the bit reader to next byte
22421        bz._start_bunzip(inputStream, outputStream);
22422      } else break;
22423    }
22424  }
22425  if ('getBuffer' in outputStream) return outputStream.getBuffer();
22426};
22427Bunzip.decodeBlock = function (input, pos, output) {
22428  // make a stream from a buffer, if necessary
22429  var inputStream = coerceInputStream(input);
22430  var outputStream = coerceOutputStream(output);
22431  var bz = new Bunzip(inputStream, outputStream);
22432  bz.reader.seek(pos);
22433  /* Fill the decode buffer for the block */
22434  var moreBlocks = bz._get_next_block();
22435  if (moreBlocks) {
22436    /* Init the CRC for writing */
22437    bz.blockCRC = new CRC32();
22438
22439    /* Zero this so the current byte from before the seek is not written */
22440    bz.writeCopies = 0;
22441
22442    /* Decompress the block and write to stdout */
22443    bz._read_bunzip();
22444    // XXX keep writing?
22445  }
22446  if ('getBuffer' in outputStream) return outputStream.getBuffer();
22447};
22448/* Reads bzip2 file from stream or buffer `input`, and invoke
22449 * `callback(position, size)` once for each bzip2 block,
22450 * where position gives the starting position (in *bits*)
22451 * and size gives uncompressed size of the block (in *bytes*). */
22452Bunzip.table = function (input, callback, multistream) {
22453  // make a stream from a buffer, if necessary
22454  var inputStream = new Stream();
22455  inputStream.delegate = coerceInputStream(input);
22456  inputStream.pos = 0;
22457  inputStream.readByte = function () {
22458    this.pos++;
22459    return this.delegate.readByte();
22460  };
22461  if (inputStream.delegate.eof) {
22462    inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);
22463  }
22464  var outputStream = new Stream();
22465  outputStream.pos = 0;
22466  outputStream.writeByte = function () {
22467    this.pos++;
22468  };
22469
22470  var bz = new Bunzip(inputStream, outputStream);
22471  var blockSize = bz.dbufSize;
22472  while (true) {
22473    if ('eof' in inputStream && inputStream.eof()) break;
22474
22475    var position = inputStream.pos * 8 + bz.reader.bitOffset;
22476    if (bz.reader.hasByte) {
22477      position -= 8;
22478    }
22479
22480    if (bz._init_block()) {
22481      var start = outputStream.pos;
22482      bz._read_bunzip();
22483      callback(position, outputStream.pos - start);
22484    } else {
22485      var crc = bz.reader.read(32); // (but we ignore the crc)
22486      if (multistream && 'eof' in inputStream && !inputStream.eof()) {
22487        // note that start_bunzip will also resync the bit reader to next byte
22488        bz._start_bunzip(inputStream, outputStream);
22489        console.assert(bz.dbufSize === blockSize, "shouldn't change block size within multistream file");
22490      } else break;
22491    }
22492  }
22493};
22494
22495Bunzip.Stream = Stream;
22496
22497module.exports = Bunzip;
22498
22499},{"./bitreader":68,"./crc32":69,"./stream":71}],71:[function(require,module,exports){
22500"use strict";
22501
22502/* very simple input/output stream interface */
22503var Stream = function Stream() {};
22504
22505// input streams //////////////
22506/** Returns the next byte, or -1 for EOF. */
22507Stream.prototype.readByte = function () {
22508  throw new Error("abstract method readByte() not implemented");
22509};
22510/** Attempts to fill the buffer; returns number of bytes read, or
22511 *  -1 for EOF. */
22512Stream.prototype.read = function (buffer, bufOffset, length) {
22513  var bytesRead = 0;
22514  while (bytesRead < length) {
22515    var c = this.readByte();
22516    if (c < 0) {
22517      // EOF
22518      return bytesRead === 0 ? -1 : bytesRead;
22519    }
22520    buffer[bufOffset++] = c;
22521    bytesRead++;
22522  }
22523  return bytesRead;
22524};
22525Stream.prototype.seek = function (new_pos) {
22526  throw new Error("abstract method seek() not implemented");
22527};
22528
22529// output streams ///////////
22530Stream.prototype.writeByte = function (_byte) {
22531  throw new Error("abstract method readByte() not implemented");
22532};
22533Stream.prototype.write = function (buffer, bufOffset, length) {
22534  var i;
22535  for (i = 0; i < length; i++) {
22536    this.writeByte(buffer[bufOffset++]);
22537  }
22538  return length;
22539};
22540Stream.prototype.flush = function () {};
22541
22542module.exports = Stream;
22543
22544},{}],72:[function(require,module,exports){
22545'use strict';
22546
22547// This is free and unencumbered software released into the public domain.
22548// See LICENSE.md for more information.
22549
22550//
22551// Utilities
22552//
22553
22554/**
22555 * @param {number} a The number to test.
22556 * @param {number} min The minimum value in the range, inclusive.
22557 * @param {number} max The maximum value in the range, inclusive.
22558 * @return {boolean} True if a >= min and a <= max.
22559 */
22560function inRange(a, min, max) {
22561  return min <= a && a <= max;
22562}
22563
22564/**
22565 * @param {*} o
22566 * @return {Object}
22567 */
22568function ToDictionary(o) {
22569  if (o === undefined) return {};
22570  if (o === Object(o)) return o;
22571  throw TypeError('Could not convert argument to dictionary');
22572}
22573
22574/**
22575 * @param {string} string Input string of UTF-16 code units.
22576 * @return {!Array.<number>} Code points.
22577 */
22578function stringToCodePoints(string) {
22579  // https://heycam.github.io/webidl/#dfn-obtain-unicode
22580
22581  // 1. Let S be the DOMString value.
22582  var s = String(string);
22583
22584  // 2. Let n be the length of S.
22585  var n = s.length;
22586
22587  // 3. Initialize i to 0.
22588  var i = 0;
22589
22590  // 4. Initialize U to be an empty sequence of Unicode characters.
22591  var u = [];
22592
22593  // 5. While i < n:
22594  while (i < n) {
22595
22596    // 1. Let c be the code unit in S at index i.
22597    var c = s.charCodeAt(i);
22598
22599    // 2. Depending on the value of c:
22600
22601    // c < 0xD800 or c > 0xDFFF
22602    if (c < 0xD800 || c > 0xDFFF) {
22603      // Append to U the Unicode character with code point c.
22604      u.push(c);
22605    }
22606
22607    // 0xDC00 ≤ c ≤ 0xDFFF
22608    else if (0xDC00 <= c && c <= 0xDFFF) {
22609      // Append to U a U+FFFD REPLACEMENT CHARACTER.
22610      u.push(0xFFFD);
22611    }
22612
22613    // 0xD800 ≤ c ≤ 0xDBFF
22614    else if (0xD800 <= c && c <= 0xDBFF) {
22615      // 1. If i = n−1, then append to U a U+FFFD REPLACEMENT
22616      // CHARACTER.
22617      if (i === n - 1) {
22618        u.push(0xFFFD);
22619      }
22620      // 2. Otherwise, i < n−1:
22621      else {
22622        // 1. Let d be the code unit in S at index i+1.
22623        var d = string.charCodeAt(i + 1);
22624
22625        // 2. If 0xDC00 ≤ d ≤ 0xDFFF, then:
22626        if (0xDC00 <= d && d <= 0xDFFF) {
22627          // 1. Let a be c & 0x3FF.
22628          var a = c & 0x3FF;
22629
22630          // 2. Let b be d & 0x3FF.
22631          var b = d & 0x3FF;
22632
22633          // 3. Append to U the Unicode character with code point
22634          // 2^16+2^10*a+b.
22635          u.push(0x10000 + (a << 10) + b);
22636
22637          // 4. Set i to i+1.
22638          i += 1;
22639        }
22640
22641        // 3. Otherwise, d < 0xDC00 or d > 0xDFFF. Append to U a
22642        // U+FFFD REPLACEMENT CHARACTER.
22643        else  {
22644          u.push(0xFFFD);
22645        }
22646      }
22647    }
22648
22649    // 3. Set i to i+1.
22650    i += 1;
22651  }
22652
22653  // 6. Return U.
22654  return u;
22655}
22656
22657/**
22658 * @param {!Array.<number>} code_points Array of code points.
22659 * @return {string} string String of UTF-16 code units.
22660 */
22661function codePointsToString(code_points) {
22662  var s = '';
22663  for (var i = 0; i < code_points.length; ++i) {
22664    var cp = code_points[i];
22665    if (cp <= 0xFFFF) {
22666      s += String.fromCharCode(cp);
22667    } else {
22668      cp -= 0x10000;
22669      s += String.fromCharCode((cp >> 10) + 0xD800,
22670                               (cp & 0x3FF) + 0xDC00);
22671    }
22672  }
22673  return s;
22674}
22675
22676
22677//
22678// Implementation of Encoding specification
22679// https://encoding.spec.whatwg.org/
22680//
22681
22682//
22683// 3. Terminology
22684//
22685
22686/**
22687 * End-of-stream is a special token that signifies no more tokens
22688 * are in the stream.
22689 * @const
22690 */ var end_of_stream = -1;
22691
22692/**
22693 * A stream represents an ordered sequence of tokens.
22694 *
22695 * @constructor
22696 * @param {!(Array.<number>|Uint8Array)} tokens Array of tokens that provide the
22697 * stream.
22698 */
22699function Stream(tokens) {
22700  /** @type {!Array.<number>} */
22701  this.tokens = [].slice.call(tokens);
22702}
22703
22704Stream.prototype = {
22705  /**
22706   * @return {boolean} True if end-of-stream has been hit.
22707   */
22708  endOfStream: function() {
22709    return !this.tokens.length;
22710  },
22711
22712  /**
22713   * When a token is read from a stream, the first token in the
22714   * stream must be returned and subsequently removed, and
22715   * end-of-stream must be returned otherwise.
22716   *
22717   * @return {number} Get the next token from the stream, or
22718   * end_of_stream.
22719   */
22720   read: function() {
22721    if (!this.tokens.length)
22722      return end_of_stream;
22723     return this.tokens.shift();
22724   },
22725
22726  /**
22727   * When one or more tokens are prepended to a stream, those tokens
22728   * must be inserted, in given order, before the first token in the
22729   * stream.
22730   *
22731   * @param {(number|!Array.<number>)} token The token(s) to prepend to the stream.
22732   */
22733  prepend: function(token) {
22734    if (Array.isArray(token)) {
22735      var tokens = /**@type {!Array.<number>}*/(token);
22736      while (tokens.length)
22737        this.tokens.unshift(tokens.pop());
22738    } else {
22739      this.tokens.unshift(token);
22740    }
22741  },
22742
22743  /**
22744   * When one or more tokens are pushed to a stream, those tokens
22745   * must be inserted, in given order, after the last token in the
22746   * stream.
22747   *
22748   * @param {(number|!Array.<number>)} token The tokens(s) to prepend to the stream.
22749   */
22750  push: function(token) {
22751    if (Array.isArray(token)) {
22752      var tokens = /**@type {!Array.<number>}*/(token);
22753      while (tokens.length)
22754        this.tokens.push(tokens.shift());
22755    } else {
22756      this.tokens.push(token);
22757    }
22758  }
22759};
22760
22761//
22762// 4. Encodings
22763//
22764
22765// 4.1 Encoders and decoders
22766
22767/** @const */
22768var finished = -1;
22769
22770/**
22771 * @param {boolean} fatal If true, decoding errors raise an exception.
22772 * @param {number=} opt_code_point Override the standard fallback code point.
22773 * @return {number} The code point to insert on a decoding error.
22774 */
22775function decoderError(fatal, opt_code_point) {
22776  if (fatal)
22777    throw TypeError('Decoder error');
22778  return opt_code_point || 0xFFFD;
22779}
22780
22781//
22782// 7. API
22783//
22784
22785/** @const */ var DEFAULT_ENCODING = 'utf-8';
22786
22787// 7.1 Interface TextDecoder
22788
22789/**
22790 * @constructor
22791 * @param {string=} encoding The label of the encoding;
22792 *     defaults to 'utf-8'.
22793 * @param {Object=} options
22794 */
22795function TextDecoder(encoding, options) {
22796  if (!(this instanceof TextDecoder)) {
22797    return new TextDecoder(encoding, options);
22798  }
22799  encoding = encoding !== undefined ? String(encoding).toLowerCase() : DEFAULT_ENCODING;
22800  if (encoding !== DEFAULT_ENCODING) {
22801    throw new Error('Encoding not supported. Only utf-8 is supported');
22802  }
22803  options = ToDictionary(options);
22804
22805  /** @private @type {boolean} */
22806  this._streaming = false;
22807  /** @private @type {boolean} */
22808  this._BOMseen = false;
22809  /** @private @type {?Decoder} */
22810  this._decoder = null;
22811  /** @private @type {boolean} */
22812  this._fatal = Boolean(options['fatal']);
22813  /** @private @type {boolean} */
22814  this._ignoreBOM = Boolean(options['ignoreBOM']);
22815
22816  Object.defineProperty(this, 'encoding', {value: 'utf-8'});
22817  Object.defineProperty(this, 'fatal', {value: this._fatal});
22818  Object.defineProperty(this, 'ignoreBOM', {value: this._ignoreBOM});
22819}
22820
22821TextDecoder.prototype = {
22822  /**
22823   * @param {ArrayBufferView=} input The buffer of bytes to decode.
22824   * @param {Object=} options
22825   * @return {string} The decoded string.
22826   */
22827  decode: function decode(input, options) {
22828    var bytes;
22829    if (typeof input === 'object' && input instanceof ArrayBuffer) {
22830      bytes = new Uint8Array(input);
22831    } else if (typeof input === 'object' && 'buffer' in input &&
22832               input.buffer instanceof ArrayBuffer) {
22833      bytes = new Uint8Array(input.buffer,
22834                             input.byteOffset,
22835                             input.byteLength);
22836    } else {
22837      bytes = new Uint8Array(0);
22838    }
22839
22840    options = ToDictionary(options);
22841
22842    if (!this._streaming) {
22843      this._decoder = new UTF8Decoder({fatal: this._fatal});
22844      this._BOMseen = false;
22845    }
22846    this._streaming = Boolean(options['stream']);
22847
22848    var input_stream = new Stream(bytes);
22849
22850    var code_points = [];
22851
22852    /** @type {?(number|!Array.<number>)} */
22853    var result;
22854
22855    while (!input_stream.endOfStream()) {
22856      result = this._decoder.handler(input_stream, input_stream.read());
22857      if (result === finished)
22858        break;
22859      if (result === null)
22860        continue;
22861      if (Array.isArray(result))
22862        code_points.push.apply(code_points, /**@type {!Array.<number>}*/(result));
22863      else
22864        code_points.push(result);
22865    }
22866    if (!this._streaming) {
22867      do {
22868        result = this._decoder.handler(input_stream, input_stream.read());
22869        if (result === finished)
22870          break;
22871        if (result === null)
22872          continue;
22873        if (Array.isArray(result))
22874          code_points.push.apply(code_points, /**@type {!Array.<number>}*/(result));
22875        else
22876          code_points.push(result);
22877      } while (!input_stream.endOfStream());
22878      this._decoder = null;
22879    }
22880
22881    if (code_points.length) {
22882      // If encoding is one of utf-8, utf-16be, and utf-16le, and
22883      // ignore BOM flag and BOM seen flag are unset, run these
22884      // subsubsteps:
22885      if (['utf-8'].indexOf(this.encoding) !== -1 &&
22886          !this._ignoreBOM && !this._BOMseen) {
22887        // If token is U+FEFF, set BOM seen flag.
22888        if (code_points[0] === 0xFEFF) {
22889          this._BOMseen = true;
22890          code_points.shift();
22891        } else {
22892          // Otherwise, if token is not end-of-stream, set BOM seen
22893          // flag and append token to output.
22894          this._BOMseen = true;
22895        }
22896      }
22897    }
22898
22899    return codePointsToString(code_points);
22900  }
22901};
22902
22903// 7.2 Interface TextEncoder
22904
22905/**
22906 * @constructor
22907 * @param {string=} encoding The label of the encoding;
22908 *     defaults to 'utf-8'.
22909 * @param {Object=} options
22910 */
22911function TextEncoder(encoding, options) {
22912  if (!(this instanceof TextEncoder))
22913    return new TextEncoder(encoding, options);
22914  encoding = encoding !== undefined ? String(encoding).toLowerCase() : DEFAULT_ENCODING;
22915  if (encoding !== DEFAULT_ENCODING) {
22916    throw new Error('Encoding not supported. Only utf-8 is supported');
22917  }
22918  options = ToDictionary(options);
22919
22920  /** @private @type {boolean} */
22921  this._streaming = false;
22922  /** @private @type {?Encoder} */
22923  this._encoder = null;
22924  /** @private @type {{fatal: boolean}} */
22925  this._options = {fatal: Boolean(options['fatal'])};
22926
22927  Object.defineProperty(this, 'encoding', {value: 'utf-8'});
22928}
22929
22930TextEncoder.prototype = {
22931  /**
22932   * @param {string=} opt_string The string to encode.
22933   * @param {Object=} options
22934   * @return {Uint8Array} Encoded bytes, as a Uint8Array.
22935   */
22936  encode: function encode(opt_string, options) {
22937    opt_string = opt_string ? String(opt_string) : '';
22938    options = ToDictionary(options);
22939
22940    // NOTE: This option is nonstandard. None of the encodings
22941    // permitted for encoding (i.e. UTF-8, UTF-16) are stateful,
22942    // so streaming is not necessary.
22943    if (!this._streaming)
22944      this._encoder = new UTF8Encoder(this._options);
22945    this._streaming = Boolean(options['stream']);
22946
22947    var bytes = [];
22948    var input_stream = new Stream(stringToCodePoints(opt_string));
22949    /** @type {?(number|!Array.<number>)} */
22950    var result;
22951    while (!input_stream.endOfStream()) {
22952      result = this._encoder.handler(input_stream, input_stream.read());
22953      if (result === finished)
22954        break;
22955      if (Array.isArray(result))
22956        bytes.push.apply(bytes, /**@type {!Array.<number>}*/(result));
22957      else
22958        bytes.push(result);
22959    }
22960    if (!this._streaming) {
22961      while (true) {
22962        result = this._encoder.handler(input_stream, input_stream.read());
22963        if (result === finished)
22964          break;
22965        if (Array.isArray(result))
22966          bytes.push.apply(bytes, /**@type {!Array.<number>}*/(result));
22967        else
22968          bytes.push(result);
22969      }
22970      this._encoder = null;
22971    }
22972    return new Uint8Array(bytes);
22973  }
22974};
22975
22976//
22977// 8. The encoding
22978//
22979
22980// 8.1 utf-8
22981
22982/**
22983 * @constructor
22984 * @implements {Decoder}
22985 * @param {{fatal: boolean}} options
22986 */
22987function UTF8Decoder(options) {
22988  var fatal = options.fatal;
22989
22990  // utf-8's decoder's has an associated utf-8 code point, utf-8
22991  // bytes seen, and utf-8 bytes needed (all initially 0), a utf-8
22992  // lower boundary (initially 0x80), and a utf-8 upper boundary
22993  // (initially 0xBF).
22994  var /** @type {number} */ utf8_code_point = 0,
22995      /** @type {number} */ utf8_bytes_seen = 0,
22996      /** @type {number} */ utf8_bytes_needed = 0,
22997      /** @type {number} */ utf8_lower_boundary = 0x80,
22998      /** @type {number} */ utf8_upper_boundary = 0xBF;
22999
23000  /**
23001   * @param {Stream} stream The stream of bytes being decoded.
23002   * @param {number} bite The next byte read from the stream.
23003   * @return {?(number|!Array.<number>)} The next code point(s)
23004   *     decoded, or null if not enough data exists in the input
23005   *     stream to decode a complete code point.
23006   */
23007  this.handler = function(stream, bite) {
23008    // 1. If byte is end-of-stream and utf-8 bytes needed is not 0,
23009    // set utf-8 bytes needed to 0 and return error.
23010    if (bite === end_of_stream && utf8_bytes_needed !== 0) {
23011      utf8_bytes_needed = 0;
23012      return decoderError(fatal);
23013    }
23014
23015    // 2. If byte is end-of-stream, return finished.
23016    if (bite === end_of_stream)
23017      return finished;
23018
23019    // 3. If utf-8 bytes needed is 0, based on byte:
23020    if (utf8_bytes_needed === 0) {
23021
23022      // 0x00 to 0x7F
23023      if (inRange(bite, 0x00, 0x7F)) {
23024        // Return a code point whose value is byte.
23025        return bite;
23026      }
23027
23028      // 0xC2 to 0xDF
23029      if (inRange(bite, 0xC2, 0xDF)) {
23030        // Set utf-8 bytes needed to 1 and utf-8 code point to byte
23031        // − 0xC0.
23032        utf8_bytes_needed = 1;
23033        utf8_code_point = bite - 0xC0;
23034      }
23035
23036      // 0xE0 to 0xEF
23037      else if (inRange(bite, 0xE0, 0xEF)) {
23038        // 1. If byte is 0xE0, set utf-8 lower boundary to 0xA0.
23039        if (bite === 0xE0)
23040          utf8_lower_boundary = 0xA0;
23041        // 2. If byte is 0xED, set utf-8 upper boundary to 0x9F.
23042        if (bite === 0xED)
23043          utf8_upper_boundary = 0x9F;
23044        // 3. Set utf-8 bytes needed to 2 and utf-8 code point to
23045        // byte − 0xE0.
23046        utf8_bytes_needed = 2;
23047        utf8_code_point = bite - 0xE0;
23048      }
23049
23050      // 0xF0 to 0xF4
23051      else if (inRange(bite, 0xF0, 0xF4)) {
23052        // 1. If byte is 0xF0, set utf-8 lower boundary to 0x90.
23053        if (bite === 0xF0)
23054          utf8_lower_boundary = 0x90;
23055        // 2. If byte is 0xF4, set utf-8 upper boundary to 0x8F.
23056        if (bite === 0xF4)
23057          utf8_upper_boundary = 0x8F;
23058        // 3. Set utf-8 bytes needed to 3 and utf-8 code point to
23059        // byte − 0xF0.
23060        utf8_bytes_needed = 3;
23061        utf8_code_point = bite - 0xF0;
23062      }
23063
23064      // Otherwise
23065      else {
23066        // Return error.
23067        return decoderError(fatal);
23068      }
23069
23070      // Then (byte is in the range 0xC2 to 0xF4) set utf-8 code
23071      // point to utf-8 code point << (6 × utf-8 bytes needed) and
23072      // return continue.
23073      utf8_code_point = utf8_code_point << (6 * utf8_bytes_needed);
23074      return null;
23075    }
23076
23077    // 4. If byte is not in the range utf-8 lower boundary to utf-8
23078    // upper boundary, run these substeps:
23079    if (!inRange(bite, utf8_lower_boundary, utf8_upper_boundary)) {
23080
23081      // 1. Set utf-8 code point, utf-8 bytes needed, and utf-8
23082      // bytes seen to 0, set utf-8 lower boundary to 0x80, and set
23083      // utf-8 upper boundary to 0xBF.
23084      utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;
23085      utf8_lower_boundary = 0x80;
23086      utf8_upper_boundary = 0xBF;
23087
23088      // 2. Prepend byte to stream.
23089      stream.prepend(bite);
23090
23091      // 3. Return error.
23092      return decoderError(fatal);
23093    }
23094
23095    // 5. Set utf-8 lower boundary to 0x80 and utf-8 upper boundary
23096    // to 0xBF.
23097    utf8_lower_boundary = 0x80;
23098    utf8_upper_boundary = 0xBF;
23099
23100    // 6. Increase utf-8 bytes seen by one and set utf-8 code point
23101    // to utf-8 code point + (byte − 0x80) << (6 × (utf-8 bytes
23102    // needed − utf-8 bytes seen)).
23103    utf8_bytes_seen += 1;
23104    utf8_code_point += (bite - 0x80) << (6 * (utf8_bytes_needed - utf8_bytes_seen));
23105
23106    // 7. If utf-8 bytes seen is not equal to utf-8 bytes needed,
23107    // continue.
23108    if (utf8_bytes_seen !== utf8_bytes_needed)
23109      return null;
23110
23111    // 8. Let code point be utf-8 code point.
23112    var code_point = utf8_code_point;
23113
23114    // 9. Set utf-8 code point, utf-8 bytes needed, and utf-8 bytes
23115    // seen to 0.
23116    utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;
23117
23118    // 10. Return a code point whose value is code point.
23119    return code_point;
23120  };
23121}
23122
23123/**
23124 * @constructor
23125 * @implements {Encoder}
23126 * @param {{fatal: boolean}} options
23127 */
23128function UTF8Encoder(options) {
23129  var fatal = options.fatal;
23130  /**
23131   * @param {Stream} stream Input stream.
23132   * @param {number} code_point Next code point read from the stream.
23133   * @return {(number|!Array.<number>)} Byte(s) to emit.
23134   */
23135  this.handler = function(stream, code_point) {
23136    // 1. If code point is end-of-stream, return finished.
23137    if (code_point === end_of_stream)
23138      return finished;
23139
23140    // 2. If code point is in the range U+0000 to U+007F, return a
23141    // byte whose value is code point.
23142    if (inRange(code_point, 0x0000, 0x007f))
23143      return code_point;
23144
23145    // 3. Set count and offset based on the range code point is in:
23146    var count, offset;
23147    // U+0080 to U+07FF:    1 and 0xC0
23148    if (inRange(code_point, 0x0080, 0x07FF)) {
23149      count = 1;
23150      offset = 0xC0;
23151    }
23152    // U+0800 to U+FFFF:    2 and 0xE0
23153    else if (inRange(code_point, 0x0800, 0xFFFF)) {
23154      count = 2;
23155      offset = 0xE0;
23156    }
23157    // U+10000 to U+10FFFF: 3 and 0xF0
23158    else if (inRange(code_point, 0x10000, 0x10FFFF)) {
23159      count = 3;
23160      offset = 0xF0;
23161    }
23162
23163    // 4.Let bytes be a byte sequence whose first byte is (code
23164    // point >> (6 × count)) + offset.
23165    var bytes = [(code_point >> (6 * count)) + offset];
23166
23167    // 5. Run these substeps while count is greater than 0:
23168    while (count > 0) {
23169
23170      // 1. Set temp to code point >> (6 × (count − 1)).
23171      var temp = code_point >> (6 * (count - 1));
23172
23173      // 2. Append to bytes 0x80 | (temp & 0x3F).
23174      bytes.push(0x80 | (temp & 0x3F));
23175
23176      // 3. Decrease count by one.
23177      count -= 1;
23178    }
23179
23180    // 6. Return bytes bytes, in order.
23181    return bytes;
23182  };
23183}
23184
23185exports.TextEncoder = TextEncoder;
23186exports.TextDecoder = TextDecoder;
23187},{}],73:[function(require,module,exports){
23188/*jshint bitwise: false*/
23189
23190(function(nacl) {
23191'use strict';
23192
23193// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
23194// Public domain.
23195//
23196// Implementation derived from TweetNaCl version 20140427.
23197// See for details: http://tweetnacl.cr.yp.to/
23198
23199var gf = function(init) {
23200  var i, r = new Float64Array(16);
23201  if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
23202  return r;
23203};
23204
23205//  Pluggable, initialized in high-level API below.
23206var randombytes = function(/* x, n */) { throw new Error('no PRNG'); };
23207
23208var _9 = new Uint8Array(32); _9[0] = 9;
23209
23210var gf0 = gf(),
23211    gf1 = gf([1]),
23212    _121665 = gf([0xdb41, 1]),
23213    D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
23214    D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
23215    X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
23216    Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
23217    I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
23218
23219function vn(x, xi, y, yi, n) {
23220  var i,d = 0;
23221  for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];
23222  return (1 & ((d - 1) >>> 8)) - 1;
23223}
23224
23225function crypto_verify_32(x, xi, y, yi) {
23226  return vn(x,xi,y,yi,32);
23227}
23228
23229function set25519(r, a) {
23230  var i;
23231  for (i = 0; i < 16; i++) r[i] = a[i]|0;
23232}
23233
23234function car25519(o) {
23235  var i, v, c = 1;
23236  for (i = 0; i < 16; i++) {
23237    v = o[i] + c + 65535;
23238    c = Math.floor(v / 65536);
23239    o[i] = v - c * 65536;
23240  }
23241  o[0] += c-1 + 37 * (c-1);
23242}
23243
23244function sel25519(p, q, b) {
23245  var t, c = ~(b-1);
23246  for (var i = 0; i < 16; i++) {
23247    t = c & (p[i] ^ q[i]);
23248    p[i] ^= t;
23249    q[i] ^= t;
23250  }
23251}
23252
23253function pack25519(o, n) {
23254  var i, j, b;
23255  var m = gf(), t = gf();
23256  for (i = 0; i < 16; i++) t[i] = n[i];
23257  car25519(t);
23258  car25519(t);
23259  car25519(t);
23260  for (j = 0; j < 2; j++) {
23261    m[0] = t[0] - 0xffed;
23262    for (i = 1; i < 15; i++) {
23263      m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
23264      m[i-1] &= 0xffff;
23265    }
23266    m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
23267    b = (m[15]>>16) & 1;
23268    m[14] &= 0xffff;
23269    sel25519(t, m, 1-b);
23270  }
23271  for (i = 0; i < 16; i++) {
23272    o[2*i] = t[i] & 0xff;
23273    o[2*i+1] = t[i]>>8;
23274  }
23275}
23276
23277function neq25519(a, b) {
23278  var c = new Uint8Array(32), d = new Uint8Array(32);
23279  pack25519(c, a);
23280  pack25519(d, b);
23281  return crypto_verify_32(c, 0, d, 0);
23282}
23283
23284function par25519(a) {
23285  var d = new Uint8Array(32);
23286  pack25519(d, a);
23287  return d[0] & 1;
23288}
23289
23290function unpack25519(o, n) {
23291  var i;
23292  for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);
23293  o[15] &= 0x7fff;
23294}
23295
23296function A(o, a, b) {
23297  for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
23298}
23299
23300function Z(o, a, b) {
23301  for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
23302}
23303
23304function M(o, a, b) {
23305  var v, c,
23306     t0 = 0,  t1 = 0,  t2 = 0,  t3 = 0,  t4 = 0,  t5 = 0,  t6 = 0,  t7 = 0,
23307     t8 = 0,  t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
23308    t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
23309    t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
23310    b0 = b[0],
23311    b1 = b[1],
23312    b2 = b[2],
23313    b3 = b[3],
23314    b4 = b[4],
23315    b5 = b[5],
23316    b6 = b[6],
23317    b7 = b[7],
23318    b8 = b[8],
23319    b9 = b[9],
23320    b10 = b[10],
23321    b11 = b[11],
23322    b12 = b[12],
23323    b13 = b[13],
23324    b14 = b[14],
23325    b15 = b[15];
23326
23327  v = a[0];
23328  t0 += v * b0;
23329  t1 += v * b1;
23330  t2 += v * b2;
23331  t3 += v * b3;
23332  t4 += v * b4;
23333  t5 += v * b5;
23334  t6 += v * b6;
23335  t7 += v * b7;
23336  t8 += v * b8;
23337  t9 += v * b9;
23338  t10 += v * b10;
23339  t11 += v * b11;
23340  t12 += v * b12;
23341  t13 += v * b13;
23342  t14 += v * b14;
23343  t15 += v * b15;
23344  v = a[1];
23345  t1 += v * b0;
23346  t2 += v * b1;
23347  t3 += v * b2;
23348  t4 += v * b3;
23349  t5 += v * b4;
23350  t6 += v * b5;
23351  t7 += v * b6;
23352  t8 += v * b7;
23353  t9 += v * b8;
23354  t10 += v * b9;
23355  t11 += v * b10;
23356  t12 += v * b11;
23357  t13 += v * b12;
23358  t14 += v * b13;
23359  t15 += v * b14;
23360  t16 += v * b15;
23361  v = a[2];
23362  t2 += v * b0;
23363  t3 += v * b1;
23364  t4 += v * b2;
23365  t5 += v * b3;
23366  t6 += v * b4;
23367  t7 += v * b5;
23368  t8 += v * b6;
23369  t9 += v * b7;
23370  t10 += v * b8;
23371  t11 += v * b9;
23372  t12 += v * b10;
23373  t13 += v * b11;
23374  t14 += v * b12;
23375  t15 += v * b13;
23376  t16 += v * b14;
23377  t17 += v * b15;
23378  v = a[3];
23379  t3 += v * b0;
23380  t4 += v * b1;
23381  t5 += v * b2;
23382  t6 += v * b3;
23383  t7 += v * b4;
23384  t8 += v * b5;
23385  t9 += v * b6;
23386  t10 += v * b7;
23387  t11 += v * b8;
23388  t12 += v * b9;
23389  t13 += v * b10;
23390  t14 += v * b11;
23391  t15 += v * b12;
23392  t16 += v * b13;
23393  t17 += v * b14;
23394  t18 += v * b15;
23395  v = a[4];
23396  t4 += v * b0;
23397  t5 += v * b1;
23398  t6 += v * b2;
23399  t7 += v * b3;
23400  t8 += v * b4;
23401  t9 += v * b5;
23402  t10 += v * b6;
23403  t11 += v * b7;
23404  t12 += v * b8;
23405  t13 += v * b9;
23406  t14 += v * b10;
23407  t15 += v * b11;
23408  t16 += v * b12;
23409  t17 += v * b13;
23410  t18 += v * b14;
23411  t19 += v * b15;
23412  v = a[5];
23413  t5 += v * b0;
23414  t6 += v * b1;
23415  t7 += v * b2;
23416  t8 += v * b3;
23417  t9 += v * b4;
23418  t10 += v * b5;
23419  t11 += v * b6;
23420  t12 += v * b7;
23421  t13 += v * b8;
23422  t14 += v * b9;
23423  t15 += v * b10;
23424  t16 += v * b11;
23425  t17 += v * b12;
23426  t18 += v * b13;
23427  t19 += v * b14;
23428  t20 += v * b15;
23429  v = a[6];
23430  t6 += v * b0;
23431  t7 += v * b1;
23432  t8 += v * b2;
23433  t9 += v * b3;
23434  t10 += v * b4;
23435  t11 += v * b5;
23436  t12 += v * b6;
23437  t13 += v * b7;
23438  t14 += v * b8;
23439  t15 += v * b9;
23440  t16 += v * b10;
23441  t17 += v * b11;
23442  t18 += v * b12;
23443  t19 += v * b13;
23444  t20 += v * b14;
23445  t21 += v * b15;
23446  v = a[7];
23447  t7 += v * b0;
23448  t8 += v * b1;
23449  t9 += v * b2;
23450  t10 += v * b3;
23451  t11 += v * b4;
23452  t12 += v * b5;
23453  t13 += v * b6;
23454  t14 += v * b7;
23455  t15 += v * b8;
23456  t16 += v * b9;
23457  t17 += v * b10;
23458  t18 += v * b11;
23459  t19 += v * b12;
23460  t20 += v * b13;
23461  t21 += v * b14;
23462  t22 += v * b15;
23463  v = a[8];
23464  t8 += v * b0;
23465  t9 += v * b1;
23466  t10 += v * b2;
23467  t11 += v * b3;
23468  t12 += v * b4;
23469  t13 += v * b5;
23470  t14 += v * b6;
23471  t15 += v * b7;
23472  t16 += v * b8;
23473  t17 += v * b9;
23474  t18 += v * b10;
23475  t19 += v * b11;
23476  t20 += v * b12;
23477  t21 += v * b13;
23478  t22 += v * b14;
23479  t23 += v * b15;
23480  v = a[9];
23481  t9 += v * b0;
23482  t10 += v * b1;
23483  t11 += v * b2;
23484  t12 += v * b3;
23485  t13 += v * b4;
23486  t14 += v * b5;
23487  t15 += v * b6;
23488  t16 += v * b7;
23489  t17 += v * b8;
23490  t18 += v * b9;
23491  t19 += v * b10;
23492  t20 += v * b11;
23493  t21 += v * b12;
23494  t22 += v * b13;
23495  t23 += v * b14;
23496  t24 += v * b15;
23497  v = a[10];
23498  t10 += v * b0;
23499  t11 += v * b1;
23500  t12 += v * b2;
23501  t13 += v * b3;
23502  t14 += v * b4;
23503  t15 += v * b5;
23504  t16 += v * b6;
23505  t17 += v * b7;
23506  t18 += v * b8;
23507  t19 += v * b9;
23508  t20 += v * b10;
23509  t21 += v * b11;
23510  t22 += v * b12;
23511  t23 += v * b13;
23512  t24 += v * b14;
23513  t25 += v * b15;
23514  v = a[11];
23515  t11 += v * b0;
23516  t12 += v * b1;
23517  t13 += v * b2;
23518  t14 += v * b3;
23519  t15 += v * b4;
23520  t16 += v * b5;
23521  t17 += v * b6;
23522  t18 += v * b7;
23523  t19 += v * b8;
23524  t20 += v * b9;
23525  t21 += v * b10;
23526  t22 += v * b11;
23527  t23 += v * b12;
23528  t24 += v * b13;
23529  t25 += v * b14;
23530  t26 += v * b15;
23531  v = a[12];
23532  t12 += v * b0;
23533  t13 += v * b1;
23534  t14 += v * b2;
23535  t15 += v * b3;
23536  t16 += v * b4;
23537  t17 += v * b5;
23538  t18 += v * b6;
23539  t19 += v * b7;
23540  t20 += v * b8;
23541  t21 += v * b9;
23542  t22 += v * b10;
23543  t23 += v * b11;
23544  t24 += v * b12;
23545  t25 += v * b13;
23546  t26 += v * b14;
23547  t27 += v * b15;
23548  v = a[13];
23549  t13 += v * b0;
23550  t14 += v * b1;
23551  t15 += v * b2;
23552  t16 += v * b3;
23553  t17 += v * b4;
23554  t18 += v * b5;
23555  t19 += v * b6;
23556  t20 += v * b7;
23557  t21 += v * b8;
23558  t22 += v * b9;
23559  t23 += v * b10;
23560  t24 += v * b11;
23561  t25 += v * b12;
23562  t26 += v * b13;
23563  t27 += v * b14;
23564  t28 += v * b15;
23565  v = a[14];
23566  t14 += v * b0;
23567  t15 += v * b1;
23568  t16 += v * b2;
23569  t17 += v * b3;
23570  t18 += v * b4;
23571  t19 += v * b5;
23572  t20 += v * b6;
23573  t21 += v * b7;
23574  t22 += v * b8;
23575  t23 += v * b9;
23576  t24 += v * b10;
23577  t25 += v * b11;
23578  t26 += v * b12;
23579  t27 += v * b13;
23580  t28 += v * b14;
23581  t29 += v * b15;
23582  v = a[15];
23583  t15 += v * b0;
23584  t16 += v * b1;
23585  t17 += v * b2;
23586  t18 += v * b3;
23587  t19 += v * b4;
23588  t20 += v * b5;
23589  t21 += v * b6;
23590  t22 += v * b7;
23591  t23 += v * b8;
23592  t24 += v * b9;
23593  t25 += v * b10;
23594  t26 += v * b11;
23595  t27 += v * b12;
23596  t28 += v * b13;
23597  t29 += v * b14;
23598  t30 += v * b15;
23599
23600  t0  += 38 * t16;
23601  t1  += 38 * t17;
23602  t2  += 38 * t18;
23603  t3  += 38 * t19;
23604  t4  += 38 * t20;
23605  t5  += 38 * t21;
23606  t6  += 38 * t22;
23607  t7  += 38 * t23;
23608  t8  += 38 * t24;
23609  t9  += 38 * t25;
23610  t10 += 38 * t26;
23611  t11 += 38 * t27;
23612  t12 += 38 * t28;
23613  t13 += 38 * t29;
23614  t14 += 38 * t30;
23615  // t15 left as is
23616
23617  // first car
23618  c = 1;
23619  v =  t0 + c + 65535; c = Math.floor(v / 65536);  t0 = v - c * 65536;
23620  v =  t1 + c + 65535; c = Math.floor(v / 65536);  t1 = v - c * 65536;
23621  v =  t2 + c + 65535; c = Math.floor(v / 65536);  t2 = v - c * 65536;
23622  v =  t3 + c + 65535; c = Math.floor(v / 65536);  t3 = v - c * 65536;
23623  v =  t4 + c + 65535; c = Math.floor(v / 65536);  t4 = v - c * 65536;
23624  v =  t5 + c + 65535; c = Math.floor(v / 65536);  t5 = v - c * 65536;
23625  v =  t6 + c + 65535; c = Math.floor(v / 65536);  t6 = v - c * 65536;
23626  v =  t7 + c + 65535; c = Math.floor(v / 65536);  t7 = v - c * 65536;
23627  v =  t8 + c + 65535; c = Math.floor(v / 65536);  t8 = v - c * 65536;
23628  v =  t9 + c + 65535; c = Math.floor(v / 65536);  t9 = v - c * 65536;
23629  v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
23630  v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
23631  v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
23632  v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
23633  v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
23634  v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
23635  t0 += c-1 + 37 * (c-1);
23636
23637  // second car
23638  c = 1;
23639  v =  t0 + c + 65535; c = Math.floor(v / 65536);  t0 = v - c * 65536;
23640  v =  t1 + c + 65535; c = Math.floor(v / 65536);  t1 = v - c * 65536;
23641  v =  t2 + c + 65535; c = Math.floor(v / 65536);  t2 = v - c * 65536;
23642  v =  t3 + c + 65535; c = Math.floor(v / 65536);  t3 = v - c * 65536;
23643  v =  t4 + c + 65535; c = Math.floor(v / 65536);  t4 = v - c * 65536;
23644  v =  t5 + c + 65535; c = Math.floor(v / 65536);  t5 = v - c * 65536;
23645  v =  t6 + c + 65535; c = Math.floor(v / 65536);  t6 = v - c * 65536;
23646  v =  t7 + c + 65535; c = Math.floor(v / 65536);  t7 = v - c * 65536;
23647  v =  t8 + c + 65535; c = Math.floor(v / 65536);  t8 = v - c * 65536;
23648  v =  t9 + c + 65535; c = Math.floor(v / 65536);  t9 = v - c * 65536;
23649  v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
23650  v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
23651  v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
23652  v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
23653  v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
23654  v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
23655  t0 += c-1 + 37 * (c-1);
23656
23657  o[ 0] = t0;
23658  o[ 1] = t1;
23659  o[ 2] = t2;
23660  o[ 3] = t3;
23661  o[ 4] = t4;
23662  o[ 5] = t5;
23663  o[ 6] = t6;
23664  o[ 7] = t7;
23665  o[ 8] = t8;
23666  o[ 9] = t9;
23667  o[10] = t10;
23668  o[11] = t11;
23669  o[12] = t12;
23670  o[13] = t13;
23671  o[14] = t14;
23672  o[15] = t15;
23673}
23674
23675function S(o, a) {
23676  M(o, a, a);
23677}
23678
23679function inv25519(o, i) {
23680  var c = gf();
23681  var a;
23682  for (a = 0; a < 16; a++) c[a] = i[a];
23683  for (a = 253; a >= 0; a--) {
23684    S(c, c);
23685    if(a !== 2 && a !== 4) M(c, c, i);
23686  }
23687  for (a = 0; a < 16; a++) o[a] = c[a];
23688}
23689
23690function pow2523(o, i) {
23691  var c = gf();
23692  var a;
23693  for (a = 0; a < 16; a++) c[a] = i[a];
23694  for (a = 250; a >= 0; a--) {
23695      S(c, c);
23696      if(a !== 1) M(c, c, i);
23697  }
23698  for (a = 0; a < 16; a++) o[a] = c[a];
23699}
23700
23701function crypto_scalarmult(q, n, p) {
23702  var z = new Uint8Array(32);
23703  var x = new Float64Array(80), r, i;
23704  var a = gf(), b = gf(), c = gf(),
23705      d = gf(), e = gf(), f = gf();
23706  for (i = 0; i < 31; i++) z[i] = n[i];
23707  z[31]=(n[31]&127)|64;
23708  z[0]&=248;
23709  unpack25519(x,p);
23710  for (i = 0; i < 16; i++) {
23711    b[i]=x[i];
23712    d[i]=a[i]=c[i]=0;
23713  }
23714  a[0]=d[0]=1;
23715  for (i=254; i>=0; --i) {
23716    r=(z[i>>>3]>>>(i&7))&1;
23717    sel25519(a,b,r);
23718    sel25519(c,d,r);
23719    A(e,a,c);
23720    Z(a,a,c);
23721    A(c,b,d);
23722    Z(b,b,d);
23723    S(d,e);
23724    S(f,a);
23725    M(a,c,a);
23726    M(c,b,e);
23727    A(e,a,c);
23728    Z(a,a,c);
23729    S(b,a);
23730    Z(c,d,f);
23731    M(a,c,_121665);
23732    A(a,a,d);
23733    M(c,c,a);
23734    M(a,d,f);
23735    M(d,b,x);
23736    S(b,e);
23737    sel25519(a,b,r);
23738    sel25519(c,d,r);
23739  }
23740  for (i = 0; i < 16; i++) {
23741    x[i+16]=a[i];
23742    x[i+32]=c[i];
23743    x[i+48]=b[i];
23744    x[i+64]=d[i];
23745  }
23746  var x32 = x.subarray(32);
23747  var x16 = x.subarray(16);
23748  inv25519(x32,x32);
23749  M(x16,x16,x32);
23750  pack25519(q,x16);
23751  return 0;
23752}
23753
23754function crypto_scalarmult_base(q, n) {
23755  return crypto_scalarmult(q, n, _9);
23756}
23757
23758function crypto_box_keypair(y, x) {
23759  randombytes(x, 32);
23760  return crypto_scalarmult_base(y, x);
23761}
23762
23763function add(p, q) {
23764  var a = gf(), b = gf(), c = gf(),
23765      d = gf(), e = gf(), f = gf(),
23766      g = gf(), h = gf(), t = gf();
23767
23768  Z(a, p[1], p[0]);
23769  Z(t, q[1], q[0]);
23770  M(a, a, t);
23771  A(b, p[0], p[1]);
23772  A(t, q[0], q[1]);
23773  M(b, b, t);
23774  M(c, p[3], q[3]);
23775  M(c, c, D2);
23776  M(d, p[2], q[2]);
23777  A(d, d, d);
23778  Z(e, b, a);
23779  Z(f, d, c);
23780  A(g, d, c);
23781  A(h, b, a);
23782
23783  M(p[0], e, f);
23784  M(p[1], h, g);
23785  M(p[2], g, f);
23786  M(p[3], e, h);
23787}
23788
23789function cswap(p, q, b) {
23790  var i;
23791  for (i = 0; i < 4; i++) {
23792    sel25519(p[i], q[i], b);
23793  }
23794}
23795
23796function pack(r, p) {
23797  var tx = gf(), ty = gf(), zi = gf();
23798  inv25519(zi, p[2]);
23799  M(tx, p[0], zi);
23800  M(ty, p[1], zi);
23801  pack25519(r, ty);
23802  r[31] ^= par25519(tx) << 7;
23803}
23804
23805function scalarmult(p, q, s) {
23806  var b, i;
23807  set25519(p[0], gf0);
23808  set25519(p[1], gf1);
23809  set25519(p[2], gf1);
23810  set25519(p[3], gf0);
23811  for (i = 255; i >= 0; --i) {
23812    b = (s[(i/8)|0] >> (i&7)) & 1;
23813    cswap(p, q, b);
23814    add(q, p);
23815    add(p, p);
23816    cswap(p, q, b);
23817  }
23818}
23819
23820function scalarbase(p, s) {
23821  var q = [gf(), gf(), gf(), gf()];
23822  set25519(q[0], X);
23823  set25519(q[1], Y);
23824  set25519(q[2], gf1);
23825  M(q[3], X, Y);
23826  scalarmult(p, q, s);
23827}
23828
23829function crypto_sign_keypair(pk, sk, seeded) {
23830  var d;
23831  var p = [gf(), gf(), gf(), gf()];
23832  var i;
23833
23834  if (!seeded) randombytes(sk, 32);
23835  d = nacl.hash(sk.subarray(0, 32));
23836  d[0] &= 248;
23837  d[31] &= 127;
23838  d[31] |= 64;
23839
23840  scalarbase(p, d);
23841  pack(pk, p);
23842
23843  for (i = 0; i < 32; i++) sk[i+32] = pk[i];
23844  return 0;
23845}
23846
23847var 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]);
23848
23849function modL(r, x) {
23850  var carry, i, j, k;
23851  for (i = 63; i >= 32; --i) {
23852    carry = 0;
23853    for (j = i - 32, k = i - 12; j < k; ++j) {
23854      x[j] += carry - 16 * x[i] * L[j - (i - 32)];
23855      carry = (x[j] + 128) >> 8;
23856      x[j] -= carry * 256;
23857    }
23858    x[j] += carry;
23859    x[i] = 0;
23860  }
23861  carry = 0;
23862  for (j = 0; j < 32; j++) {
23863    x[j] += carry - (x[31] >> 4) * L[j];
23864    carry = x[j] >> 8;
23865    x[j] &= 255;
23866  }
23867  for (j = 0; j < 32; j++) x[j] -= carry * L[j];
23868  for (i = 0; i < 32; i++) {
23869    x[i+1] += x[i] >> 8;
23870    r[i] = x[i] & 255;
23871  }
23872}
23873
23874function reduce(r) {
23875  var x = new Float64Array(64), i;
23876  for (i = 0; i < 64; i++) x[i] = r[i];
23877  for (i = 0; i < 64; i++) r[i] = 0;
23878  modL(r, x);
23879}
23880
23881// Note: difference from C - smlen returned, not passed as argument.
23882function crypto_sign(sm, m, n, sk) {
23883  var d, h, r;
23884  var i, j, x = new Float64Array(64);
23885  var p = [gf(), gf(), gf(), gf()];
23886
23887  d = nacl.hash(sk.subarray(0, 32));
23888  d[0] &= 248;
23889  d[31] &= 127;
23890  d[31] |= 64;
23891
23892  var smlen = n + 64;
23893  for (i = 0; i < n; i++) sm[64 + i] = m[i];
23894  for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
23895
23896  r = nacl.hash(sm.subarray(32, smlen));
23897  reduce(r);
23898  scalarbase(p, r);
23899  pack(sm, p);
23900
23901  for (i = 32; i < 64; i++) sm[i] = sk[i];
23902  h = nacl.hash(sm.subarray(0, smlen));
23903  reduce(h);
23904
23905  for (i = 0; i < 64; i++) x[i] = 0;
23906  for (i = 0; i < 32; i++) x[i] = r[i];
23907  for (i = 0; i < 32; i++) {
23908    for (j = 0; j < 32; j++) {
23909      x[i+j] += h[i] * d[j];
23910    }
23911  }
23912
23913  modL(sm.subarray(32), x);
23914  return smlen;
23915}
23916
23917function unpackneg(r, p) {
23918  var t = gf(), chk = gf(), num = gf(),
23919      den = gf(), den2 = gf(), den4 = gf(),
23920      den6 = gf();
23921
23922  set25519(r[2], gf1);
23923  unpack25519(r[1], p);
23924  S(num, r[1]);
23925  M(den, num, D);
23926  Z(num, num, r[2]);
23927  A(den, r[2], den);
23928
23929  S(den2, den);
23930  S(den4, den2);
23931  M(den6, den4, den2);
23932  M(t, den6, num);
23933  M(t, t, den);
23934
23935  pow2523(t, t);
23936  M(t, t, num);
23937  M(t, t, den);
23938  M(t, t, den);
23939  M(r[0], t, den);
23940
23941  S(chk, r[0]);
23942  M(chk, chk, den);
23943  if (neq25519(chk, num)) M(r[0], r[0], I);
23944
23945  S(chk, r[0]);
23946  M(chk, chk, den);
23947  if (neq25519(chk, num)) return -1;
23948
23949  if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);
23950
23951  M(r[3], r[0], r[1]);
23952  return 0;
23953}
23954
23955function crypto_sign_open(m, sm, n, pk) {
23956  var i, mlen;
23957  var t = new Uint8Array(32), h;
23958  var p = [gf(), gf(), gf(), gf()],
23959      q = [gf(), gf(), gf(), gf()];
23960
23961  mlen = -1;
23962  if (n < 64) return -1;
23963
23964  if (unpackneg(q, pk)) return -1;
23965
23966  for (i = 0; i < n; i++) m[i] = sm[i];
23967  for (i = 0; i < 32; i++) m[i+32] = pk[i];
23968  h = nacl.hash(m.subarray(0, n));
23969  reduce(h);
23970  scalarmult(p, q, h);
23971
23972  scalarbase(q, sm.subarray(32));
23973  add(p, q);
23974  pack(t, p);
23975
23976  n -= 64;
23977  if (crypto_verify_32(sm, 0, t, 0)) {
23978    for (i = 0; i < n; i++) m[i] = 0;
23979    return -1;
23980  }
23981
23982  for (i = 0; i < n; i++) m[i] = sm[i + 64];
23983  mlen = n;
23984  return mlen;
23985}
23986
23987var crypto_scalarmult_BYTES = 32,
23988    crypto_scalarmult_SCALARBYTES = 32,
23989    crypto_box_PUBLICKEYBYTES = 32,
23990    crypto_box_SECRETKEYBYTES = 32,
23991    crypto_sign_BYTES = 64,
23992    crypto_sign_PUBLICKEYBYTES = 32,
23993    crypto_sign_SECRETKEYBYTES = 64,
23994    crypto_sign_SEEDBYTES = 32;
23995
23996function checkArrayTypes() {
23997  for (var i = 0; i < arguments.length; i++) {
23998    if (!(arguments[i] instanceof Uint8Array))
23999      throw new TypeError('unexpected type, use Uint8Array');
24000  }
24001}
24002
24003function cleanup(arr) {
24004  for (var i = 0; i < arr.length; i++) arr[i] = 0;
24005}
24006
24007nacl.scalarMult = function(n, p) {
24008  checkArrayTypes(n, p);
24009  if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
24010  if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
24011  var q = new Uint8Array(crypto_scalarmult_BYTES);
24012  crypto_scalarmult(q, n, p);
24013  return q;
24014};
24015
24016nacl.box = {};
24017
24018nacl.box.keyPair = function() {
24019  var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
24020  var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
24021  crypto_box_keypair(pk, sk);
24022  return {publicKey: pk, secretKey: sk};
24023};
24024
24025nacl.box.keyPair.fromSecretKey = function(secretKey) {
24026  checkArrayTypes(secretKey);
24027  if (secretKey.length !== crypto_box_SECRETKEYBYTES)
24028    throw new Error('bad secret key size');
24029  var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
24030  crypto_scalarmult_base(pk, secretKey);
24031  return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
24032};
24033
24034nacl.sign = function(msg, secretKey) {
24035  checkArrayTypes(msg, secretKey);
24036  if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
24037    throw new Error('bad secret key size');
24038  var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
24039  crypto_sign(signedMsg, msg, msg.length, secretKey);
24040  return signedMsg;
24041};
24042
24043nacl.sign.detached = function(msg, secretKey) {
24044  var signedMsg = nacl.sign(msg, secretKey);
24045  var sig = new Uint8Array(crypto_sign_BYTES);
24046  for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
24047  return sig;
24048};
24049
24050nacl.sign.detached.verify = function(msg, sig, publicKey) {
24051  checkArrayTypes(msg, sig, publicKey);
24052  if (sig.length !== crypto_sign_BYTES)
24053    throw new Error('bad signature size');
24054  if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
24055    throw new Error('bad public key size');
24056  var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
24057  var m = new Uint8Array(crypto_sign_BYTES + msg.length);
24058  var i;
24059  for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
24060  for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
24061  return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
24062};
24063
24064nacl.sign.keyPair = function() {
24065  var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
24066  var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
24067  crypto_sign_keypair(pk, sk);
24068  return {publicKey: pk, secretKey: sk};
24069};
24070
24071nacl.sign.keyPair.fromSecretKey = function(secretKey) {
24072  checkArrayTypes(secretKey);
24073  if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
24074    throw new Error('bad secret key size');
24075  var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
24076  for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
24077  return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
24078};
24079
24080nacl.sign.keyPair.fromSeed = function(seed) {
24081  checkArrayTypes(seed);
24082  if (seed.length !== crypto_sign_SEEDBYTES)
24083    throw new Error('bad seed size');
24084  var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
24085  var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
24086  for (var i = 0; i < 32; i++) sk[i] = seed[i];
24087  crypto_sign_keypair(pk, sk, true);
24088  return {publicKey: pk, secretKey: sk};
24089};
24090
24091nacl.setPRNG = function(fn) {
24092  randombytes = fn;
24093};
24094
24095(function() {
24096  // Initialize PRNG if environment provides CSPRNG.
24097  // If not, methods calling randombytes will throw.
24098  var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
24099  if (crypto && crypto.getRandomValues) {
24100    // Browsers.
24101    var QUOTA = 65536;
24102    nacl.setPRNG(function(x, n) {
24103      var i, v = new Uint8Array(n);
24104      for (i = 0; i < n; i += QUOTA) {
24105        crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
24106      }
24107      for (i = 0; i < n; i++) x[i] = v[i];
24108      cleanup(v);
24109    });
24110  } else if (typeof require !== 'undefined') {
24111    // Node.js.
24112    crypto = require('crypto');
24113    if (crypto && crypto.randomBytes) {
24114      nacl.setPRNG(function(x, n) {
24115        var i, v = crypto.randomBytes(n);
24116        for (i = 0; i < n; i++) x[i] = v[i];
24117        cleanup(v);
24118      });
24119    }
24120  }
24121})();
24122
24123})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));
24124
24125},{"crypto":"crypto"}],74:[function(require,module,exports){
24126'use strict';
24127
24128Object.defineProperty(exports, "__esModule", {
24129  value: true
24130});
24131exports.webToNode = exports.nodeToWeb = undefined;
24132
24133var _streams = require('./streams');
24134
24135var _streams2 = _interopRequireDefault(_streams);
24136
24137function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24138
24139const NodeReadableStream = typeof window === 'undefined' && require('stream').Readable;
24140
24141/**
24142 * Web / node stream conversion functions
24143 * From https://github.com/gwicke/node-web-streams
24144 */
24145
24146let nodeToWeb;
24147let webToNode;
24148
24149if (NodeReadableStream) {
24150
24151  /**
24152   * Convert a Node Readable Stream to a Web ReadableStream
24153   * @param {Readable} nodeStream
24154   * @returns {ReadableStream}
24155   */
24156  exports.nodeToWeb = nodeToWeb = function nodeToWeb(nodeStream) {
24157    return new ReadableStream({
24158      start(controller) {
24159        nodeStream.pause();
24160        nodeStream.on('data', chunk => {
24161          controller.enqueue(chunk);
24162          nodeStream.pause();
24163        });
24164        nodeStream.on('end', () => controller.close());
24165        nodeStream.on('error', e => controller.error(e));
24166      },
24167      pull() {
24168        nodeStream.resume();
24169      },
24170      cancel(reason) {
24171        nodeStream.pause();
24172        if (nodeStream.cancel) {
24173          return nodeStream.cancel(reason);
24174        }
24175      }
24176    });
24177  };
24178
24179  class NodeReadable extends NodeReadableStream {
24180    constructor(webStream, options) {
24181      super(options);
24182      this._webStream = webStream;
24183      this._reader = _streams2.default.getReader(webStream);
24184      this._reading = false;
24185      this._doneReadingPromise = Promise.resolve();
24186      this._cancelling = false;
24187    }
24188
24189    _read(size) {
24190      if (this._reading || this._cancelling) {
24191        return;
24192      }
24193      this._reading = true;
24194      const doRead = async () => {
24195        try {
24196          while (true) {
24197            var _ref = await this._reader.read();
24198
24199            const done = _ref.done,
24200                  value = _ref.value;
24201
24202            if (done) {
24203              this.push(null);
24204              break;
24205            }
24206            if (!this.push(value) || this._cancelling) {
24207              this._reading = false;
24208              break;
24209            }
24210          }
24211        } catch (e) {
24212          this.emit('error', e);
24213        }
24214      };
24215      this._doneReadingPromise = doRead();
24216    }
24217
24218    async cancel(reason) {
24219      this._cancelling = true;
24220      await this._doneReadingPromise;
24221      this._reader.releaseLock();
24222      return this._webStream.cancel(reason);
24223    }
24224  }
24225
24226  /**
24227   * Convert a Web ReadableStream to a Node Readable Stream
24228   * @param {ReadableStream} webStream
24229   * @returns {Readable}
24230   */
24231  exports.webToNode = webToNode = function webToNode(webStream) {
24232    return new NodeReadable(webStream);
24233  };
24234}
24235
24236exports.nodeToWeb = nodeToWeb;
24237exports.webToNode = webToNode;
24238
24239},{"./streams":76,"stream":"stream"}],75:[function(require,module,exports){
24240'use strict';
24241
24242Object.defineProperty(exports, "__esModule", {
24243  value: true
24244});
24245exports.externalBuffer = exports.Reader = undefined;
24246
24247var _streams = require('./streams');
24248
24249var _streams2 = _interopRequireDefault(_streams);
24250
24251function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24252
24253const doneReadingSet = new WeakSet();
24254const externalBuffer = Symbol('externalBuffer');
24255
24256/**
24257 * A wrapper class over the native ReadableStreamDefaultReader.
24258 * This additionally implements pushing back data on the stream, which
24259 * lets us implement peeking and a host of convenience functions.
24260 * It also lets you read data other than streams, such as a Uint8Array.
24261 * @class
24262 */
24263function Reader(input) {
24264  this.stream = input;
24265  if (input[externalBuffer]) {
24266    this[externalBuffer] = input[externalBuffer].slice();
24267  }
24268  let streamType = _streams2.default.isStream(input);
24269  if (streamType === 'node') {
24270    input = _streams2.default.nodeToWeb(input);
24271  }
24272  if (streamType) {
24273    const reader = input.getReader();
24274    this._read = reader.read.bind(reader);
24275    this._releaseLock = () => {
24276      reader.closed.catch(function () {});
24277      reader.releaseLock();
24278    };
24279    return;
24280  }
24281  let doneReading = false;
24282  this._read = async () => {
24283    if (doneReading || doneReadingSet.has(input)) {
24284      return { value: undefined, done: true };
24285    }
24286    doneReading = true;
24287    return { value: input, done: false };
24288  };
24289  this._releaseLock = () => {
24290    if (doneReading) {
24291      try {
24292        doneReadingSet.add(input);
24293      } catch (e) {}
24294    }
24295  };
24296}
24297
24298/**
24299 * Read a chunk of data.
24300 * @returns {Promise<Object>} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }
24301 * @async
24302 */
24303Reader.prototype.read = async function () {
24304  if (this[externalBuffer] && this[externalBuffer].length) {
24305    const value = this[externalBuffer].shift();
24306    return { done: false, value };
24307  }
24308  return this._read();
24309};
24310
24311/**
24312 * Allow others to read the stream.
24313 */
24314Reader.prototype.releaseLock = function () {
24315  if (this[externalBuffer]) {
24316    this.stream[externalBuffer] = this[externalBuffer];
24317  }
24318  this._releaseLock();
24319};
24320
24321/**
24322 * Read up to and including the first \n character.
24323 * @returns {Promise<String|Undefined>}
24324 * @async
24325 */
24326Reader.prototype.readLine = async function () {
24327  let buffer = [];
24328  let returnVal;
24329  while (!returnVal) {
24330    var _ref = await this.read();
24331
24332    let done = _ref.done,
24333        value = _ref.value;
24334
24335    value += '';
24336    if (done) {
24337      if (buffer.length) return _streams2.default.concat(buffer);
24338      return;
24339    }
24340    const lineEndIndex = value.indexOf('\n') + 1;
24341    if (lineEndIndex) {
24342      returnVal = _streams2.default.concat(buffer.concat(value.substr(0, lineEndIndex)));
24343      buffer = [];
24344    }
24345    if (lineEndIndex !== value.length) {
24346      buffer.push(value.substr(lineEndIndex));
24347    }
24348  }
24349  this.unshift(...buffer);
24350  return returnVal;
24351};
24352
24353/**
24354 * Read a single byte/character.
24355 * @returns {Promise<Number|String|Undefined>}
24356 * @async
24357 */
24358Reader.prototype.readByte = async function () {
24359  var _ref2 = await this.read();
24360
24361  const done = _ref2.done,
24362        value = _ref2.value;
24363
24364  if (done) return;
24365  const byte = value[0];
24366  this.unshift(_streams2.default.slice(value, 1));
24367  return byte;
24368};
24369
24370/**
24371 * Read a specific amount of bytes/characters, unless the stream ends before that amount.
24372 * @returns {Promise<Uint8Array|String|Undefined>}
24373 * @async
24374 */
24375Reader.prototype.readBytes = async function (length) {
24376  const buffer = [];
24377  let bufferLength = 0;
24378  while (true) {
24379    var _ref3 = await this.read();
24380
24381    const done = _ref3.done,
24382          value = _ref3.value;
24383
24384    if (done) {
24385      if (buffer.length) return _streams2.default.concat(buffer);
24386      return;
24387    }
24388    buffer.push(value);
24389    bufferLength += value.length;
24390    if (bufferLength >= length) {
24391      const bufferConcat = _streams2.default.concat(buffer);
24392      this.unshift(_streams2.default.slice(bufferConcat, length));
24393      return _streams2.default.slice(bufferConcat, 0, length);
24394    }
24395  }
24396};
24397
24398/**
24399 * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.
24400 * @returns {Promise<Uint8Array|String|Undefined>}
24401 * @async
24402 */
24403Reader.prototype.peekBytes = async function (length) {
24404  const bytes = await this.readBytes(length);
24405  this.unshift(bytes);
24406  return bytes;
24407};
24408
24409/**
24410 * Push data to the front of the stream.
24411 * @param {...(Uint8Array|String|Undefined)} values
24412 */
24413Reader.prototype.unshift = function (...values) {
24414  if (!this[externalBuffer]) {
24415    this[externalBuffer] = [];
24416  }
24417  this[externalBuffer].unshift(...values.filter(value => value && value.length));
24418};
24419
24420/**
24421 * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).
24422 * @param {Function} join
24423 * @returns {Promise<Uint8array|String|Any>} the return value of join()
24424 * @async
24425 */
24426Reader.prototype.readToEnd = async function (join = _streams2.default.concat) {
24427  const result = [];
24428  while (true) {
24429    var _ref4 = await this.read();
24430
24431    const done = _ref4.done,
24432          value = _ref4.value;
24433
24434    if (done) break;
24435    result.push(value);
24436  }
24437  return join(result);
24438};
24439
24440exports.Reader = Reader;
24441exports.externalBuffer = externalBuffer;
24442
24443},{"./streams":76}],76:[function(require,module,exports){
24444(function (process){
24445'use strict';
24446
24447Object.defineProperty(exports, "__esModule", {
24448  value: true
24449});
24450
24451var _util = require('./util');
24452
24453var _nodeConversions = require('./node-conversions');
24454
24455var _reader = require('./reader');
24456
24457const NodeBuffer = typeof window === 'undefined' && require('buffer').Buffer;
24458
24459/**
24460 * Convert data to Stream
24461 * @param {ReadableStream|Uint8array|String} input  data to convert
24462 * @returns {ReadableStream} Converted data
24463 */
24464function toStream(input) {
24465  let streamType = (0, _util.isStream)(input);
24466  if (streamType === 'node') {
24467    return (0, _nodeConversions.nodeToWeb)(input);
24468  } else if (streamType) {
24469    return input;
24470  }
24471  return new ReadableStream({
24472    start(controller) {
24473      controller.enqueue(input);
24474      controller.close();
24475    }
24476  });
24477}
24478
24479/**
24480 * Concat a list of Uint8Arrays, Strings or Streams
24481 * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
24482 * @param {Array<Uint8array|String|ReadableStream>} Array of Uint8Arrays/Strings/Streams to concatenate
24483 * @returns {Uint8array|String|ReadableStream} Concatenated array
24484 */
24485function concat(list) {
24486  if (list.some(_util.isStream)) {
24487    return concatStream(list);
24488  }
24489  if (typeof list[0] === 'string') {
24490    return list.join('');
24491  }
24492  if (NodeBuffer && NodeBuffer.isBuffer(list[0])) {
24493    return NodeBuffer.concat(list);
24494  }
24495  return (0, _util.concatUint8Array)(list);
24496}
24497
24498/**
24499 * Concat a list of Streams
24500 * @param {Array<ReadableStream|Uint8array|String>} list  Array of Uint8Arrays/Strings/Streams to concatenate
24501 * @returns {ReadableStream} Concatenated list
24502 */
24503function concatStream(list) {
24504  list = list.map(toStream);
24505  const transform = transformWithCancel(async function (reason) {
24506    await Promise.all(transforms.map(stream => cancel(stream, reason)));
24507  });
24508  let prev = Promise.resolve();
24509  const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {
24510    prev = prev.then(() => pipe(readable, transform.writable, {
24511      preventClose: i !== list.length - 1
24512    }));
24513    return prev;
24514  }));
24515  return transform.readable;
24516}
24517
24518/**
24519 * Get a Reader
24520 * @param {ReadableStream|Uint8array|String} input
24521 * @returns {Reader}
24522 */
24523function getReader(input) {
24524  return new _reader.Reader(input);
24525}
24526
24527/**
24528 * Get a Writer
24529 * @param {WritableStream} input
24530 * @returns {WritableStreamDefaultWriter}
24531 */
24532function getWriter(input) {
24533  const writer = input.getWriter();
24534  const releaseLock = writer.releaseLock;
24535  writer.releaseLock = () => {
24536    writer.closed.catch(function () {});
24537    releaseLock.call(writer);
24538  };
24539  return writer;
24540}
24541
24542/**
24543 * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.
24544 * @param {ReadableStream|Uint8array|String} input
24545 * @param {WritableStream} target
24546 * @param {Object} (optional) options
24547 * @returns {Promise<undefined>} Promise indicating when piping has finished (input stream closed or errored)
24548 * @async
24549 */
24550async function pipe(input, target, options) {
24551  input = toStream(input);
24552  try {
24553    if (input[_reader.externalBuffer]) {
24554      const writer = getWriter(target);
24555      for (let i = 0; i < input[_reader.externalBuffer].length; i++) {
24556        await writer.ready;
24557        await writer.write(input[_reader.externalBuffer][i]);
24558      }
24559      writer.releaseLock();
24560    }
24561    return await input.pipeTo(target, options);
24562  } catch (e) {}
24563}
24564
24565/**
24566 * Pipe a readable stream through a transform stream.
24567 * @param {ReadableStream|Uint8array|String} input
24568 * @param {Object} (optional) options
24569 * @returns {ReadableStream} transformed stream
24570 */
24571function transformRaw(input, options) {
24572  const transformStream = new TransformStream(options);
24573  pipe(input, transformStream.writable);
24574  return transformStream.readable;
24575}
24576
24577/**
24578 * Create a cancelable TransformStream.
24579 * @param {Function} cancel
24580 * @returns {TransformStream}
24581 */
24582function transformWithCancel(cancel) {
24583  let pulled = false;
24584  let backpressureChangePromiseResolve;
24585  let outputController;
24586  return {
24587    readable: new ReadableStream({
24588      start(controller) {
24589        outputController = controller;
24590      },
24591      pull() {
24592        if (backpressureChangePromiseResolve) {
24593          backpressureChangePromiseResolve();
24594        } else {
24595          pulled = true;
24596        }
24597      },
24598      cancel
24599    }, { highWaterMark: 0 }),
24600    writable: new WritableStream({
24601      write: async function write(chunk) {
24602        outputController.enqueue(chunk);
24603        if (!pulled) {
24604          await new Promise(resolve => {
24605            backpressureChangePromiseResolve = resolve;
24606          });
24607          backpressureChangePromiseResolve = null;
24608        } else {
24609          pulled = false;
24610        }
24611      },
24612      close: outputController.close.bind(outputController),
24613      abort: outputController.error.bind(outputController)
24614    })
24615  };
24616}
24617
24618/**
24619 * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.
24620 * @param {ReadableStream|Uint8array|String} input
24621 * @param {Function} process
24622 * @param {Function} finish
24623 * @returns {ReadableStream|Uint8array|String}
24624 */
24625function transform(input, process = () => undefined, finish = () => undefined) {
24626  if ((0, _util.isStream)(input)) {
24627    return transformRaw(input, {
24628      async transform(value, controller) {
24629        try {
24630          const result = await process(value);
24631          if (result !== undefined) controller.enqueue(result);
24632        } catch (e) {
24633          controller.error(e);
24634        }
24635      },
24636      async flush(controller) {
24637        try {
24638          const result = await finish();
24639          if (result !== undefined) controller.enqueue(result);
24640        } catch (e) {
24641          controller.error(e);
24642        }
24643      }
24644    });
24645  }
24646  const result1 = process(input);
24647  const result2 = finish();
24648  if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);
24649  return result1 !== undefined ? result1 : result2;
24650}
24651
24652/**
24653 * Transform a stream using a helper function which is passed a readable and a writable stream.
24654 *   This function also maintains the possibility to cancel the input stream,
24655 *   and does so on cancelation of the output stream, despite cancelation
24656 *   normally being impossible when the input stream is being read from.
24657 * @param {ReadableStream|Uint8array|String} input
24658 * @param {Function} fn
24659 * @returns {ReadableStream}
24660 */
24661function transformPair(input, fn) {
24662  let incomingTransformController;
24663  const incoming = new TransformStream({
24664    start(controller) {
24665      incomingTransformController = controller;
24666    }
24667  });
24668
24669  const pipeDonePromise = pipe(input, incoming.writable);
24670
24671  const outgoing = transformWithCancel(async function () {
24672    incomingTransformController.error(new Error('Readable side was canceled.'));
24673    await pipeDonePromise;
24674    await new Promise(setTimeout);
24675  });
24676  fn(incoming.readable, outgoing.writable);
24677  return outgoing.readable;
24678}
24679
24680/**
24681 * Parse a stream using a helper function which is passed a Reader.
24682 *   The reader additionally has a remainder() method which returns a
24683 *   stream pointing to the remainder of input, and is linked to input
24684 *   for cancelation.
24685 * @param {ReadableStream|Uint8array|String} input
24686 * @param {Function} fn
24687 * @returns {Any} the return value of fn()
24688 */
24689function parse(input, fn) {
24690  let returnValue;
24691  const transformed = transformPair(input, (readable, writable) => {
24692    const reader = getReader(readable);
24693    reader.remainder = () => {
24694      reader.releaseLock();
24695      pipe(readable, writable);
24696      return transformed;
24697    };
24698    returnValue = fn(reader);
24699  });
24700  return returnValue;
24701}
24702
24703/**
24704 * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.
24705 *   Reading either of the two returned streams will pull from the input stream.
24706 *   The input stream will only be canceled if both of the returned streams are canceled.
24707 * @param {ReadableStream|Uint8array|String} input
24708 * @returns {Array<ReadableStream|Uint8array|String>} array containing two copies of input
24709 */
24710function tee(input) {
24711  if ((0, _util.isStream)(input)) {
24712    const teed = toStream(input).tee();
24713    teed[0][_reader.externalBuffer] = teed[1][_reader.externalBuffer] = input[_reader.externalBuffer];
24714    return teed;
24715  }
24716  return [slice(input), slice(input)];
24717}
24718
24719/**
24720 * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.
24721 *   Reading from the clone will pull from the input stream.
24722 *   The input stream will only be canceled if both the clone and the input stream are canceled.
24723 * @param {ReadableStream|Uint8array|String} input
24724 * @returns {ReadableStream|Uint8array|String} cloned input
24725 */
24726function clone(input) {
24727  if ((0, _util.isStream)(input)) {
24728    const teed = tee(input);
24729    overwrite(input, teed[0]);
24730    return teed[1];
24731  }
24732  return slice(input);
24733}
24734
24735/**
24736 * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.
24737 *   Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.
24738 *   The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.
24739 *   If the input stream is canceled, the clone will be errored.
24740 * @param {ReadableStream|Uint8array|String} input
24741 * @returns {ReadableStream|Uint8array|String} cloned input
24742 */
24743function passiveClone(input) {
24744  if ((0, _util.isStream)(input)) {
24745    return new ReadableStream({
24746      start(controller) {
24747        const transformed = transformPair(input, async (readable, writable) => {
24748          const reader = getReader(readable);
24749          const writer = getWriter(writable);
24750          try {
24751            while (true) {
24752              await writer.ready;
24753
24754              var _ref = await reader.read();
24755
24756              const done = _ref.done,
24757                    value = _ref.value;
24758
24759              if (done) {
24760                try {
24761                  controller.close();
24762                } catch (e) {}
24763                await writer.close();
24764                return;
24765              }
24766              try {
24767                controller.enqueue(value);
24768              } catch (e) {}
24769              await writer.write(value);
24770            }
24771          } catch (e) {
24772            controller.error(e);
24773            await writer.abort(e);
24774          }
24775        });
24776        overwrite(input, transformed);
24777      }
24778    });
24779  }
24780  return slice(input);
24781}
24782
24783/**
24784 * Modify a stream object to point to a different stream object.
24785 *   This is used internally by clone() and passiveClone() to provide an abstraction over tee().
24786 * @param {ReadableStream} input
24787 * @param {ReadableStream} clone
24788 */
24789function overwrite(input, clone) {
24790  // Overwrite input.getReader, input.locked, etc to point to clone
24791  Object.entries(Object.getOwnPropertyDescriptors(ReadableStream.prototype)).forEach(([name, descriptor]) => {
24792    if (name === 'constructor') {
24793      return;
24794    }
24795    if (descriptor.value) {
24796      descriptor.value = descriptor.value.bind(clone);
24797    } else {
24798      descriptor.get = descriptor.get.bind(clone);
24799    }
24800    Object.defineProperty(input, name, descriptor);
24801  });
24802}
24803
24804/**
24805 * Return a stream pointing to a part of the input stream.
24806 * @param {ReadableStream|Uint8array|String} input
24807 * @returns {ReadableStream|Uint8array|String} clone
24808 */
24809function slice(input, begin = 0, end = Infinity) {
24810  if ((0, _util.isStream)(input)) {
24811    if (begin >= 0 && end >= 0) {
24812      let bytesRead = 0;
24813      return transformRaw(input, {
24814        transform(value, controller) {
24815          if (bytesRead < end) {
24816            if (bytesRead + value.length >= begin) {
24817              controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));
24818            }
24819            bytesRead += value.length;
24820          } else {
24821            controller.terminate();
24822          }
24823        }
24824      });
24825    }
24826    if (begin < 0 && (end < 0 || end === Infinity)) {
24827      let lastBytes = [];
24828      return transform(input, value => {
24829        if (value.length >= -begin) lastBytes = [value];else lastBytes.push(value);
24830      }, () => slice(concat(lastBytes), begin, end));
24831    }
24832    if (begin === 0 && end < 0) {
24833      let lastBytes;
24834      return transform(input, value => {
24835        const returnValue = lastBytes ? concat([lastBytes, value]) : value;
24836        if (returnValue.length >= -end) {
24837          lastBytes = slice(returnValue, end);
24838          return slice(returnValue, begin, end);
24839        } else {
24840          lastBytes = returnValue;
24841        }
24842      });
24843    }
24844    console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);
24845    return fromAsync(async () => slice((await readToEnd(input)), begin, end));
24846  }
24847  if (input[_reader.externalBuffer]) {
24848    input = concat(input[_reader.externalBuffer].concat([input]));
24849  }
24850  if ((0, _util.isUint8Array)(input) && !(NodeBuffer && NodeBuffer.isBuffer(input))) {
24851    if (end === Infinity) end = input.length;
24852    return input.subarray(begin, end);
24853  }
24854  return input.slice(begin, end);
24855}
24856
24857/**
24858 * Read a stream to the end and return its contents, concatenated by the concat function (defaults to concat).
24859 * @param {ReadableStream|Uint8array|String} input
24860 * @param {Function} concat
24861 * @returns {Promise<Uint8array|String|Any>} the return value of concat()
24862 * @async
24863 */
24864async function readToEnd(input, concat) {
24865  if ((0, _util.isStream)(input)) {
24866    return getReader(input).readToEnd(concat);
24867  }
24868  return input;
24869}
24870
24871/**
24872 * Cancel a stream.
24873 * @param {ReadableStream|Uint8array|String} input
24874 * @param {Any} reason
24875 * @returns {Promise<Any>} indicates when the stream has been canceled
24876 * @async
24877 */
24878async function cancel(input, reason) {
24879  if ((0, _util.isStream)(input) && input.cancel) {
24880    return input.cancel(reason);
24881  }
24882}
24883
24884/**
24885 * Convert an async function to a Stream. When the function returns, its return value is enqueued to the stream.
24886 * @param {Function} fn
24887 * @returns {ReadableStream}
24888 */
24889function fromAsync(fn) {
24890  return new ReadableStream({
24891    pull: async controller => {
24892      try {
24893        controller.enqueue((await fn()));
24894        controller.close();
24895      } catch (e) {
24896        controller.error(e);
24897      }
24898    }
24899  });
24900}
24901
24902exports.default = { isStream: _util.isStream, isUint8Array: _util.isUint8Array, toStream, concatUint8Array: _util.concatUint8Array, concatStream, concat, getReader, getWriter, pipe, transformRaw, transform, transformPair, parse, clone, passiveClone, slice, readToEnd, cancel, fromAsync, nodeToWeb: _nodeConversions.nodeToWeb, webToNode: _nodeConversions.webToNode };
24903
24904}).call(this,require('_process'))
24905},{"./node-conversions":74,"./reader":75,"./util":77,"_process":67,"buffer":"buffer"}],77:[function(require,module,exports){
24906'use strict';
24907
24908Object.defineProperty(exports, "__esModule", {
24909  value: true
24910});
24911const NodeReadableStream = typeof window === 'undefined' && require('stream').Readable;
24912
24913/**
24914 * Check whether data is a Stream, and if so of which type
24915 * @param {Any} input  data to check
24916 * @returns {'web'|'node'|false}
24917 */
24918function isStream(input) {
24919  if (ReadableStream.prototype.isPrototypeOf(input)) {
24920    return 'web';
24921  }
24922  if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) {
24923    return 'node';
24924  }
24925  return false;
24926}
24927
24928/**
24929 * Check whether data is a Uint8Array
24930 * @param {Any} input  data to check
24931 * @returns {Boolean}
24932 */
24933function isUint8Array(input) {
24934  return Uint8Array.prototype.isPrototypeOf(input);
24935}
24936
24937/**
24938 * Concat Uint8Arrays
24939 * @param {Array<Uint8array>} Array of Uint8Arrays to concatenate
24940 * @returns {Uint8array} Concatenated array
24941 */
24942function concatUint8Array(arrays) {
24943  if (arrays.length === 1) return arrays[0];
24944
24945  let totalLength = 0;
24946  for (let i = 0; i < arrays.length; i++) {
24947    if (!isUint8Array(arrays[i])) {
24948      throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');
24949    }
24950
24951    totalLength += arrays[i].length;
24952  }
24953
24954  const result = new Uint8Array(totalLength);
24955  let pos = 0;
24956  arrays.forEach(function (element) {
24957    result.set(element, pos);
24958    pos += element.length;
24959  });
24960
24961  return result;
24962}
24963
24964exports.isStream = isStream;
24965exports.isUint8Array = isUint8Array;
24966exports.concatUint8Array = concatUint8Array;
24967
24968},{"stream":"stream"}],78:[function(require,module,exports){
24969'use strict';
24970
24971Object.defineProperty(exports, "__esModule", {
24972  value: true
24973});
24974exports.CleartextMessage = CleartextMessage;
24975exports.readArmored = readArmored;
24976exports.fromText = fromText;
24977
24978var _armor = require('./encoding/armor');
24979
24980var _armor2 = _interopRequireDefault(_armor);
24981
24982var _enums = require('./enums');
24983
24984var _enums2 = _interopRequireDefault(_enums);
24985
24986var _util = require('./util');
24987
24988var _util2 = _interopRequireDefault(_util);
24989
24990var _packet = require('./packet');
24991
24992var _packet2 = _interopRequireDefault(_packet);
24993
24994var _signature = require('./signature');
24995
24996var _message = require('./message');
24997
24998function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24999
25000/**
25001 * @class
25002 * @classdesc Class that represents an OpenPGP cleartext signed message.
25003 * See {@link https://tools.ietf.org/html/rfc4880#section-7}
25004 * @param  {String}           text       The cleartext of the signed message
25005 * @param  {module:signature.Signature} signature  The detached signature or an empty signature for unsigned messages
25006 */
25007// GPG4Browsers - An OpenPGP implementation in javascript
25008// Copyright (C) 2011 Recurity Labs GmbH
25009//
25010// This library is free software; you can redistribute it and/or
25011// modify it under the terms of the GNU Lesser General Public
25012// License as published by the Free Software Foundation; either
25013// version 3.0 of the License, or (at your option) any later version.
25014//
25015// This library is distributed in the hope that it will be useful,
25016// but WITHOUT ANY WARRANTY; without even the implied warranty of
25017// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25018// Lesser General Public License for more details.
25019//
25020// You should have received a copy of the GNU Lesser General Public
25021// License along with this library; if not, write to the Free Software
25022// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
25023
25024/**
25025 * @requires encoding/armor
25026 * @requires enums
25027 * @requires util
25028 * @requires packet
25029 * @requires signature
25030 * @module cleartext
25031 */
25032
25033function CleartextMessage(text, signature) {
25034  if (!(this instanceof CleartextMessage)) {
25035    return new CleartextMessage(text, signature);
25036  }
25037  // normalize EOL to canonical form <CR><LF>
25038  this.text = _util2.default.canonicalizeEOL(_util2.default.removeTrailingSpaces(text));
25039  if (signature && !(signature instanceof _signature.Signature)) {
25040    throw new Error('Invalid signature input');
25041  }
25042  this.signature = signature || new _signature.Signature(new _packet2.default.List());
25043}
25044
25045/**
25046 * Returns the key IDs of the keys that signed the cleartext message
25047 * @returns {Array<module:type/keyid>} array of keyid objects
25048 */
25049CleartextMessage.prototype.getSigningKeyIds = function () {
25050  const keyIds = [];
25051  const signatureList = this.signature.packets;
25052  signatureList.forEach(function (packet) {
25053    keyIds.push(packet.issuerKeyId);
25054  });
25055  return keyIds;
25056};
25057
25058/**
25059 * Sign the cleartext message
25060 * @param  {Array<module:key.Key>} privateKeys private keys with decrypted secret key data for signing
25061 * @param  {Signature} signature             (optional) any existing detached signature
25062 * @param  {Date} date                       (optional) The creation time of the signature that should be created
25063 * @param  {Array} userIds                   (optional) user IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
25064 * @returns {Promise<module:cleartext.CleartextMessage>} new cleartext message with signed content
25065 * @async
25066 */
25067CleartextMessage.prototype.sign = async function (privateKeys, signature = null, date = new Date(), userIds = []) {
25068  return new CleartextMessage(this.text, (await this.signDetached(privateKeys, signature, date, userIds)));
25069};
25070
25071/**
25072 * Sign the cleartext message
25073 * @param  {Array<module:key.Key>} privateKeys private keys with decrypted secret key data for signing
25074 * @param  {Signature} signature             (optional) any existing detached signature
25075 * @param  {Date} date                       (optional) The creation time of the signature that should be created
25076 * @param  {Array} userIds                   (optional) user IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
25077 * @returns {Promise<module:signature.Signature>}      new detached signature of message content
25078 * @async
25079 */
25080CleartextMessage.prototype.signDetached = async function (privateKeys, signature = null, date = new Date(), userIds = []) {
25081  const literalDataPacket = new _packet2.default.Literal();
25082  literalDataPacket.setText(this.text);
25083
25084  return new _signature.Signature((await (0, _message.createSignaturePackets)(literalDataPacket, privateKeys, signature, date, userIds)));
25085};
25086
25087/**
25088 * Verify signatures of cleartext signed message
25089 * @param {Array<module:key.Key>} keys array of keys to verify signatures
25090 * @param {Date} date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time
25091 * @returns {Promise<Array<{keyid: module:type/keyid, valid: Boolean}>>} list of signer's keyid and validity of signature
25092 * @async
25093 */
25094CleartextMessage.prototype.verify = function (keys, date = new Date()) {
25095  return this.verifyDetached(this.signature, keys, date);
25096};
25097
25098/**
25099 * Verify signatures of cleartext signed message
25100 * @param {Array<module:key.Key>} keys array of keys to verify signatures
25101 * @param {Date} date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time
25102 * @returns {Promise<Array<{keyid: module:type/keyid, valid: Boolean}>>} list of signer's keyid and validity of signature
25103 * @async
25104 */
25105CleartextMessage.prototype.verifyDetached = function (signature, keys, date = new Date()) {
25106  const signatureList = signature.packets;
25107  const literalDataPacket = new _packet2.default.Literal();
25108  // we assume that cleartext signature is generated based on UTF8 cleartext
25109  literalDataPacket.setText(this.text);
25110  return (0, _message.createVerificationObjects)(signatureList, [literalDataPacket], keys, date);
25111};
25112
25113/**
25114 * Get cleartext
25115 * @returns {String} cleartext of message
25116 */
25117CleartextMessage.prototype.getText = function () {
25118  // normalize end of line to \n
25119  return _util2.default.nativeEOL(this.text);
25120};
25121
25122/**
25123 * Returns ASCII armored text of cleartext signed message
25124 * @returns {String | ReadableStream<String>} ASCII armor
25125 */
25126CleartextMessage.prototype.armor = function () {
25127  let hashes = this.signature.packets.map(function (packet) {
25128    return _enums2.default.read(_enums2.default.hash, packet.hashAlgorithm).toUpperCase();
25129  });
25130  hashes = hashes.filter(function (item, i, ar) {
25131    return ar.indexOf(item) === i;
25132  });
25133  const body = {
25134    hash: hashes.join(),
25135    text: this.text,
25136    data: this.signature.packets.write()
25137  };
25138  return _armor2.default.encode(_enums2.default.armor.signed, body);
25139};
25140
25141/**
25142 * reads an OpenPGP cleartext signed message and returns a CleartextMessage object
25143 * @param {String | ReadableStream<String>} armoredText text to be parsed
25144 * @returns {module:cleartext.CleartextMessage} new cleartext message object
25145 * @async
25146 * @static
25147 */
25148async function readArmored(armoredText) {
25149  const input = await _armor2.default.decode(armoredText);
25150  if (input.type !== _enums2.default.armor.signed) {
25151    throw new Error('No cleartext signed message.');
25152  }
25153  const packetlist = new _packet2.default.List();
25154  await packetlist.read(input.data);
25155  verifyHeaders(input.headers, packetlist);
25156  const signature = new _signature.Signature(packetlist);
25157  return new CleartextMessage(input.text, signature);
25158}
25159
25160/**
25161 * Compare hash algorithm specified in the armor header with signatures
25162 * @param  {Array<String>} headers    Armor headers
25163 * @param  {module:packet.List} packetlist The packetlist with signature packets
25164 * @private
25165 */
25166function verifyHeaders(headers, packetlist) {
25167  const checkHashAlgos = function checkHashAlgos(hashAlgos) {
25168    const check = packet => algo => packet.hashAlgorithm === algo;
25169
25170    for (let i = 0; i < packetlist.length; i++) {
25171      if (packetlist[i].tag === _enums2.default.packet.signature && !hashAlgos.some(check(packetlist[i]))) {
25172        return false;
25173      }
25174    }
25175    return true;
25176  };
25177
25178  let oneHeader = null;
25179  let hashAlgos = [];
25180  headers.forEach(function (header) {
25181    oneHeader = header.match(/Hash: (.+)/); // get header value
25182    if (oneHeader) {
25183      oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace
25184      oneHeader = oneHeader.split(',');
25185      oneHeader = oneHeader.map(function (hash) {
25186        hash = hash.toLowerCase();
25187        try {
25188          return _enums2.default.write(_enums2.default.hash, hash);
25189        } catch (e) {
25190          throw new Error('Unknown hash algorithm in armor header: ' + hash);
25191        }
25192      });
25193      hashAlgos = hashAlgos.concat(oneHeader);
25194    } else {
25195      throw new Error('Only "Hash" header allowed in cleartext signed message');
25196    }
25197  });
25198
25199  if (!hashAlgos.length && !checkHashAlgos([_enums2.default.hash.md5])) {
25200    throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed');
25201  } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {
25202    throw new Error('Hash algorithm mismatch in armor header and signature');
25203  }
25204}
25205
25206/**
25207 * Creates a new CleartextMessage object from text
25208 * @param {String} text
25209 * @static
25210 */
25211function fromText(text) {
25212  return new CleartextMessage(text);
25213}
25214
25215},{"./encoding/armor":112,"./enums":114,"./message":121,"./packet":126,"./signature":146,"./util":153}],79:[function(require,module,exports){
25216"use strict";
25217
25218Object.defineProperty(exports, "__esModule", {
25219  value: true
25220});
25221
25222var _enums = require("../enums");
25223
25224var _enums2 = _interopRequireDefault(_enums);
25225
25226function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
25227
25228exports.default = {
25229  /**
25230   * @memberof module:config
25231   * @property {Integer} prefer_hash_algorithm Default hash algorithm {@link module:enums.hash}
25232   */
25233  prefer_hash_algorithm: _enums2.default.hash.sha256,
25234  /**
25235   * @memberof module:config
25236   * @property {Integer} encryption_cipher Default encryption cipher {@link module:enums.symmetric}
25237   */
25238  encryption_cipher: _enums2.default.symmetric.aes256,
25239  /**
25240   * @memberof module:config
25241   * @property {Integer} compression Default compression algorithm {@link module:enums.compression}
25242   */
25243  compression: _enums2.default.compression.uncompressed,
25244  /**
25245   * @memberof module:config
25246   * @property {Integer} deflate_level Default zip/zlib compression level, between 1 and 9
25247   */
25248  deflate_level: 6,
25249
25250  /**
25251   * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.
25252   * **NOT INTEROPERABLE WITH OTHER OPENPGP IMPLEMENTATIONS**
25253   * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
25254   * @memberof module:config
25255   * @property {Boolean} aead_protect
25256   */
25257  aead_protect: false,
25258  /**
25259   * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.
25260   * 0 means we implement a variant of {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00|this IETF draft}.
25261   * 4 means we implement {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04|RFC4880bis-04}.
25262   * Note that this determines how AEAD packets are parsed even when aead_protect is set to false
25263   * @memberof module:config
25264   * @property {Integer} aead_protect_version
25265   */
25266  aead_protect_version: 4,
25267  /**
25268   * Default Authenticated Encryption with Additional Data (AEAD) encryption mode
25269   * Only has an effect when aead_protect is set to true.
25270   * @memberof module:config
25271   * @property {Integer} aead_mode Default AEAD mode {@link module:enums.aead}
25272   */
25273  aead_mode: _enums2.default.aead.eax,
25274  /**
25275   * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode
25276   * Only has an effect when aead_protect is set to true.
25277   * Must be an integer value from 0 to 56.
25278   * @memberof module:config
25279   * @property {Integer} aead_chunk_size_byte
25280   */
25281  aead_chunk_size_byte: 12,
25282  /**
25283   * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}:
25284   * Iteration Count Byte for S2K (String to Key)
25285   * @memberof module:config
25286   * @property {Integer} s2k_iteration_count_byte
25287   */
25288  s2k_iteration_count_byte: 224,
25289  /** Use integrity protection for symmetric encryption
25290   * @memberof module:config
25291   * @property {Boolean} integrity_protect
25292   */
25293  integrity_protect: true,
25294  /**
25295   * @memberof module:config
25296   * @property {Boolean} ignore_mdc_error Fail on decrypt if message is not integrity protected
25297   */
25298  ignore_mdc_error: false,
25299  /**
25300   * @memberof module:config
25301   * @property {Boolean} allow_unauthenticated_stream Stream unauthenticated data before integrity has been checked
25302   */
25303  allow_unauthenticated_stream: false,
25304  /**
25305   * @memberof module:config
25306   * @property {Boolean} checksum_required Do not throw error when armor is missing a checksum
25307   */
25308  checksum_required: false,
25309  /**
25310   * @memberof module:config
25311   * @property {Boolean} rsa_blinding
25312   */
25313  rsa_blinding: true,
25314  /**
25315   * Work-around for rare GPG decryption bug when encrypting with multiple passwords.
25316   * **Slower and slightly less secure**
25317   * @memberof module:config
25318   * @property {Boolean} password_collision_check
25319   */
25320  password_collision_check: false,
25321  /**
25322   * @memberof module:config
25323   * @property {Boolean} revocations_expire If true, expired revocation signatures are ignored
25324   */
25325  revocations_expire: false,
25326
25327  /**
25328   * @memberof module:config
25329   * @property {Boolean} use_native Use native Node.js crypto/zlib and WebCrypto APIs when available
25330   */
25331  use_native: true,
25332  /**
25333   * @memberof module:config
25334   * @property {Integer} min_bytes_for_web_crypto The minimum amount of bytes for which to use native WebCrypto APIs when available
25335   */
25336  min_bytes_for_web_crypto: 1000,
25337  /**
25338   * @memberof module:config
25339   * @property {Boolean} Use transferable objects between the Web Worker and main thread
25340   */
25341  zero_copy: false,
25342  /**
25343   * @memberof module:config
25344   * @property {Boolean} debug If enabled, debug messages will be printed
25345   */
25346  debug: false,
25347  /**
25348   * @memberof module:config
25349   * @property {Boolean} tolerant Ignore unsupported/unrecognizable packets instead of throwing an error
25350   */
25351  tolerant: true,
25352
25353  /**
25354   * @memberof module:config
25355   * @property {Boolean} show_version Whether to include {@link module:config/config.versionstring} in armored messages
25356   */
25357  show_version: true,
25358  /**
25359   * @memberof module:config
25360   * @property {Boolean} show_comment Whether to include {@link module:config/config.commentstring} in armored messages
25361   */
25362  show_comment: true,
25363  /**
25364   * @memberof module:config
25365   * @property {String} versionstring A version string to be included in armored messages
25366   */
25367  versionstring: "OpenPGP.js v4.5.1",
25368  /**
25369   * @memberof module:config
25370   * @property {String} commentstring A comment string to be included in armored messages
25371   */
25372  commentstring: "https://openpgpjs.org",
25373
25374  /**
25375   * @memberof module:config
25376   * @property {String} keyserver
25377   */
25378  keyserver: "https://keyserver.ubuntu.com",
25379  /**
25380   * @memberof module:config
25381   * @property {String} node_store
25382   */
25383  node_store: "./openpgp.store",
25384  /**
25385   * Max userid string length (used for parsing)
25386   * @memberof module:config
25387   * @property {Integer} max_userid_length
25388   */
25389  max_userid_length: 1024 * 5
25390}; // GPG4Browsers - An OpenPGP implementation in javascript
25391// Copyright (C) 2011 Recurity Labs GmbH
25392//
25393// This library is free software; you can redistribute it and/or
25394// modify it under the terms of the GNU Lesser General Public
25395// License as published by the Free Software Foundation; either
25396// version 3.0 of the License, or (at your option) any later version.
25397//
25398// This library is distributed in the hope that it will be useful,
25399// but WITHOUT ANY WARRANTY; without even the implied warranty of
25400// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25401// Lesser General Public License for more details.
25402//
25403// You should have received a copy of the GNU Lesser General Public
25404// License along with this library; if not, write to the Free Software
25405// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
25406
25407/**
25408 * Global configuration values.
25409 * @requires enums
25410 */
25411
25412},{"../enums":114}],80:[function(require,module,exports){
25413'use strict';
25414
25415Object.defineProperty(exports, "__esModule", {
25416  value: true
25417});
25418
25419var _config = require('./config.js');
25420
25421Object.defineProperty(exports, 'default', {
25422  enumerable: true,
25423  get: function get() {
25424    return _interopRequireDefault(_config).default;
25425  }
25426});
25427
25428function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
25429
25430},{"./config.js":79}],81:[function(require,module,exports){
25431'use strict';
25432
25433Object.defineProperty(exports, "__esModule", {
25434  value: true
25435});
25436
25437var _cipher = require('./cipher');
25438
25439var _cipher2 = _interopRequireDefault(_cipher);
25440
25441var _util = require('../util');
25442
25443var _util2 = _interopRequireDefault(_util);
25444
25445function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
25446
25447// OpenPGP.js - An OpenPGP implementation in javascript
25448// Copyright (C) 2015-2016 Decentral
25449//
25450// This library is free software; you can redistribute it and/or
25451// modify it under the terms of the GNU Lesser General Public
25452// License as published by the Free Software Foundation; either
25453// version 3.0 of the License, or (at your option) any later version.
25454//
25455// This library is distributed in the hope that it will be useful,
25456// but WITHOUT ANY WARRANTY; without even the implied warranty of
25457// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25458// Lesser General Public License for more details.
25459//
25460// You should have received a copy of the GNU Lesser General Public
25461// License along with this library; if not, write to the Free Software
25462// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
25463
25464/**
25465 * @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions
25466 * @see module:crypto/public_key/elliptic/ecdh
25467 * @requires crypto/cipher
25468 * @requires util
25469 * @module crypto/aes_kw
25470 */
25471
25472function wrap(key, data) {
25473  const aes = new _cipher2.default["aes" + key.length * 8](key);
25474  const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
25475  const P = unpack(data);
25476  let A = IV;
25477  const R = P;
25478  const n = P.length / 2;
25479  const t = new Uint32Array([0, 0]);
25480  let B = new Uint32Array(4);
25481  for (let j = 0; j <= 5; ++j) {
25482    for (let i = 0; i < n; ++i) {
25483      t[1] = n * j + (1 + i);
25484      // B = A
25485      B[0] = A[0];
25486      B[1] = A[1];
25487      // B = A || R[i]
25488      B[2] = R[2 * i];
25489      B[3] = R[2 * i + 1];
25490      // B = AES(K, B)
25491      B = unpack(aes.encrypt(pack(B)));
25492      // A = MSB(64, B) ^ t
25493      A = B.subarray(0, 2);
25494      A[0] ^= t[0];
25495      A[1] ^= t[1];
25496      // R[i] = LSB(64, B)
25497      R[2 * i] = B[2];
25498      R[2 * i + 1] = B[3];
25499    }
25500  }
25501  return pack(A, R);
25502}
25503
25504function unwrap(key, data) {
25505  const aes = new _cipher2.default["aes" + key.length * 8](key);
25506  const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
25507  const C = unpack(data);
25508  let A = C.subarray(0, 2);
25509  const R = C.subarray(2);
25510  const n = C.length / 2 - 1;
25511  const t = new Uint32Array([0, 0]);
25512  let B = new Uint32Array(4);
25513  for (let j = 5; j >= 0; --j) {
25514    for (let i = n - 1; i >= 0; --i) {
25515      t[1] = n * j + (i + 1);
25516      // B = A ^ t
25517      B[0] = A[0] ^ t[0];
25518      B[1] = A[1] ^ t[1];
25519      // B = (A ^ t) || R[i]
25520      B[2] = R[2 * i];
25521      B[3] = R[2 * i + 1];
25522      // B = AES-1(B)
25523      B = unpack(aes.decrypt(pack(B)));
25524      // A = MSB(64, B)
25525      A = B.subarray(0, 2);
25526      // R[i] = LSB(64, B)
25527      R[2 * i] = B[2];
25528      R[2 * i + 1] = B[3];
25529    }
25530  }
25531  if (A[0] === IV[0] && A[1] === IV[1]) {
25532    return pack(R);
25533  }
25534  throw new Error("Key Data Integrity failed");
25535}
25536
25537function createArrayBuffer(data) {
25538  if (_util2.default.isString(data)) {
25539    const length = data.length;
25540
25541    const buffer = new ArrayBuffer(length);
25542    const view = new Uint8Array(buffer);
25543    for (let j = 0; j < length; ++j) {
25544      view[j] = data.charCodeAt(j);
25545    }
25546    return buffer;
25547  }
25548  return new Uint8Array(data).buffer;
25549}
25550
25551function unpack(data) {
25552  const length = data.length;
25553
25554  const buffer = createArrayBuffer(data);
25555  const view = new DataView(buffer);
25556  const arr = new Uint32Array(length / 4);
25557  for (let i = 0; i < length / 4; ++i) {
25558    arr[i] = view.getUint32(4 * i);
25559  }
25560  return arr;
25561}
25562
25563function pack() {
25564  let length = 0;
25565  for (let k = 0; k < arguments.length; ++k) {
25566    length += 4 * arguments[k].length;
25567  }
25568  const buffer = new ArrayBuffer(length);
25569  const view = new DataView(buffer);
25570  let offset = 0;
25571  for (let i = 0; i < arguments.length; ++i) {
25572    for (let j = 0; j < arguments[i].length; ++j) {
25573      view.setUint32(offset + 4 * j, arguments[i][j]);
25574    }
25575    offset += 4 * arguments[i].length;
25576  }
25577  return new Uint8Array(buffer);
25578}
25579
25580exports.default = {
25581  /**
25582   * AES key wrap
25583   * @function
25584   * @param {String} key
25585   * @param {String} data
25586   * @returns {Uint8Array}
25587   */
25588  wrap,
25589  /**
25590   * AES key unwrap
25591   * @function
25592   * @param {String} key
25593   * @param {String} data
25594   * @returns {Uint8Array}
25595   * @throws {Error}
25596   */
25597  unwrap
25598};
25599
25600},{"../util":153,"./cipher":87}],82:[function(require,module,exports){
25601'use strict';
25602
25603Object.defineProperty(exports, "__esModule", {
25604  value: true
25605});
25606
25607var _cfb = require('asmcrypto.js/dist_es5/aes/cfb');
25608
25609var _webStreamTools = require('web-stream-tools');
25610
25611var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
25612
25613var _cipher = require('./cipher');
25614
25615var _cipher2 = _interopRequireDefault(_cipher);
25616
25617var _config = require('../config');
25618
25619var _config2 = _interopRequireDefault(_config);
25620
25621var _util = require('../util');
25622
25623var _util2 = _interopRequireDefault(_util);
25624
25625function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
25626
25627const webCrypto = _util2.default.getWebCrypto(); // Modified by ProtonTech AG
25628
25629// Modified by Recurity Labs GmbH
25630
25631// modified version of https://www.hanewin.net/encrypt/PGdecode.js:
25632
25633/* OpenPGP encryption using RSA/AES
25634 * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de
25635 * version 2.0, check www.haneWIN.de for the latest version
25636
25637 * This software is provided as-is, without express or implied warranty.
25638 * Permission to use, copy, modify, distribute or sell this software, with or
25639 * without fee, for any purpose and by any individual or organization, is hereby
25640 * granted, provided that the above copyright notice and this paragraph appear
25641 * in all copies. Distribution as a part of an application or binary must
25642 * include the above copyright notice in the documentation and/or other
25643 * materials provided with the application or distribution.
25644 */
25645
25646/**
25647 * @requires web-stream-tools
25648 * @requires crypto/cipher
25649 * @requires util
25650 * @module crypto/cfb
25651 */
25652
25653const nodeCrypto = _util2.default.getNodeCrypto();
25654const Buffer = _util2.default.getNodeBuffer();
25655
25656exports.default = {
25657  encrypt: function encrypt(algo, key, plaintext, iv) {
25658    if (algo.substr(0, 3) === 'aes') {
25659      return aesEncrypt(algo, key, plaintext, iv);
25660    }
25661
25662    const cipherfn = new _cipher2.default[algo](key);
25663    const block_size = cipherfn.blockSize;
25664
25665    let blocki = new Uint8Array(block_size);
25666    const blockc = iv;
25667    let pos = 0;
25668    const ciphertext = new Uint8Array(plaintext.length);
25669    let i;
25670    let j = 0;
25671
25672    while (plaintext.length > block_size * pos) {
25673      const encblock = cipherfn.encrypt(blockc);
25674      blocki = plaintext.subarray(pos * block_size, pos * block_size + block_size);
25675      for (i = 0; i < blocki.length; i++) {
25676        blockc[i] = blocki[i] ^ encblock[i];
25677        ciphertext[j++] = blockc[i];
25678      }
25679      pos++;
25680    }
25681    return ciphertext;
25682  },
25683
25684  decrypt: async function decrypt(algo, key, ciphertext, iv) {
25685    if (algo.substr(0, 3) === 'aes') {
25686      return aesDecrypt(algo, key, ciphertext, iv);
25687    }
25688
25689    ciphertext = await _webStreamTools2.default.readToEnd(ciphertext);
25690
25691    const cipherfn = new _cipher2.default[algo](key);
25692    const block_size = cipherfn.blockSize;
25693
25694    let blockp = iv;
25695    let pos = 0;
25696    const plaintext = new Uint8Array(ciphertext.length);
25697    const offset = 0;
25698    let i;
25699    let j = 0;
25700
25701    while (ciphertext.length > block_size * pos) {
25702      const decblock = cipherfn.encrypt(blockp);
25703      blockp = ciphertext.subarray(pos * block_size + offset, pos * block_size + block_size + offset);
25704      for (i = 0; i < blockp.length; i++) {
25705        plaintext[j++] = blockp[i] ^ decblock[i];
25706      }
25707      pos++;
25708    }
25709
25710    return plaintext;
25711  }
25712};
25713
25714
25715function aesEncrypt(algo, key, pt, iv) {
25716  if (_util2.default.getWebCrypto() && key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support
25717  !_util2.default.isStream(pt) && pt.length >= 3000 * _config2.default.min_bytes_for_web_crypto // Default to a 3MB minimum. Chrome is pretty slow for small messages, see: https://bugs.chromium.org/p/chromium/issues/detail?id=701188#c2
25718  ) {
25719      // Web Crypto
25720      return webEncrypt(algo, key, pt, iv);
25721    }
25722  if (nodeCrypto) {
25723    // Node crypto library.
25724    return nodeEncrypt(algo, key, pt, iv);
25725  } // asm.js fallback
25726  const cfb = new _cfb.AES_CFB(key, iv);
25727  return _webStreamTools2.default.transform(pt, value => cfb.AES_Encrypt_process(value), () => cfb.AES_Encrypt_finish());
25728}
25729
25730function aesDecrypt(algo, key, ct, iv) {
25731  if (nodeCrypto) {
25732    // Node crypto library.
25733    return nodeDecrypt(algo, key, ct, iv);
25734  }
25735  if (_util2.default.isStream(ct)) {
25736    const cfb = new _cfb.AES_CFB(key, iv);
25737    return _webStreamTools2.default.transform(ct, value => cfb.AES_Decrypt_process(value), () => cfb.AES_Decrypt_finish());
25738  }
25739  return _cfb.AES_CFB.decrypt(ct, key, iv);
25740}
25741
25742function xorMut(a, b) {
25743  for (let i = 0; i < a.length; i++) {
25744    a[i] = a[i] ^ b[i];
25745  }
25746}
25747
25748async function webEncrypt(algo, key, pt, iv) {
25749  const ALGO = 'AES-CBC';
25750  const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt']);
25751  const blockSize = _cipher2.default[algo].blockSize;
25752
25753  const cbc_pt = _util2.default.concatUint8Array([new Uint8Array(blockSize), pt]);
25754  const ct = new Uint8Array((await webCrypto.encrypt({ name: ALGO, iv }, _key, cbc_pt))).subarray(0, pt.length);
25755  xorMut(ct, pt);
25756  return ct;
25757}
25758
25759function nodeEncrypt(algo, key, pt, iv) {
25760  key = new Buffer(key);
25761  iv = new Buffer(iv);
25762  const cipherObj = new nodeCrypto.createCipheriv('aes-' + algo.substr(3, 3) + '-cfb', key, iv);
25763  return _webStreamTools2.default.transform(pt, value => new Uint8Array(cipherObj.update(new Buffer(value))));
25764}
25765
25766function nodeDecrypt(algo, key, ct, iv) {
25767  key = new Buffer(key);
25768  iv = new Buffer(iv);
25769  const decipherObj = new nodeCrypto.createDecipheriv('aes-' + algo.substr(3, 3) + '-cfb', key, iv);
25770  return _webStreamTools2.default.transform(ct, value => new Uint8Array(decipherObj.update(new Buffer(value))));
25771}
25772
25773},{"../config":80,"../util":153,"./cipher":87,"asmcrypto.js/dist_es5/aes/cfb":6,"web-stream-tools":76}],83:[function(require,module,exports){
25774'use strict';
25775
25776Object.defineProperty(exports, "__esModule", {
25777  value: true
25778});
25779
25780var _ecb = require('asmcrypto.js/dist_es5/aes/ecb');
25781
25782// TODO use webCrypto or nodeCrypto when possible.
25783function aes(length) {
25784  const C = function C(key) {
25785    const aes_ecb = new _ecb.AES_ECB(key);
25786
25787    this.encrypt = function (block) {
25788      return aes_ecb.encrypt(block);
25789    };
25790
25791    this.decrypt = function (block) {
25792      return aes_ecb.decrypt(block);
25793    };
25794  };
25795
25796  C.blockSize = C.prototype.blockSize = 16;
25797  C.keySize = C.prototype.keySize = length / 8;
25798
25799  return C;
25800} /**
25801   * @requires asmcrypto.js
25802   */
25803
25804exports.default = aes;
25805
25806},{"asmcrypto.js/dist_es5/aes/ecb":8}],84:[function(require,module,exports){
25807"use strict";
25808
25809Object.defineProperty(exports, "__esModule", {
25810  value: true
25811});
25812/* Modified by Recurity Labs GmbH
25813 *
25814 * Originally written by nklein software (nklein.com)
25815 */
25816
25817/*
25818 * Javascript implementation based on Bruce Schneier's reference implementation.
25819 *
25820 *
25821 * The constructor doesn't do much of anything.  It's just here
25822 * so we can start defining properties and methods and such.
25823 */
25824function Blowfish() {}
25825
25826/*
25827 * Declare the block size so that protocols know what size
25828 * Initialization Vector (IV) they will need.
25829 */
25830Blowfish.prototype.BLOCKSIZE = 8;
25831
25832/*
25833 * These are the default SBOXES.
25834 */
25835Blowfish.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]];
25836
25837//*
25838//* This is the default PARRAY
25839//*
25840Blowfish.prototype.PARRAY = [0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b];
25841
25842//*
25843//* This is the number of rounds the cipher will go
25844//*
25845Blowfish.prototype.NN = 16;
25846
25847//*
25848//* This function is needed to get rid of problems
25849//* with the high-bit getting set.  If we don't do
25850//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not
25851//* equal to ( bb & 0x00FFFFFFFF ) even when they
25852//* agree bit-for-bit for the first 32 bits.
25853//*
25854Blowfish.prototype._clean = function (xx) {
25855  if (xx < 0) {
25856    const yy = xx & 0x7FFFFFFF;
25857    xx = yy + 0x80000000;
25858  }
25859  return xx;
25860};
25861
25862//*
25863//* This is the mixing function that uses the sboxes
25864//*
25865Blowfish.prototype._F = function (xx) {
25866  let yy;
25867
25868  const dd = xx & 0x00FF;
25869  xx >>>= 8;
25870  const cc = xx & 0x00FF;
25871  xx >>>= 8;
25872  const bb = xx & 0x00FF;
25873  xx >>>= 8;
25874  const aa = xx & 0x00FF;
25875
25876  yy = this.sboxes[0][aa] + this.sboxes[1][bb];
25877  yy ^= this.sboxes[2][cc];
25878  yy += this.sboxes[3][dd];
25879
25880  return yy;
25881};
25882
25883//*
25884//* This method takes an array with two values, left and right
25885//* and does NN rounds of Blowfish on them.
25886//*
25887Blowfish.prototype._encrypt_block = function (vals) {
25888  let dataL = vals[0];
25889  let dataR = vals[1];
25890
25891  let ii;
25892
25893  for (ii = 0; ii < this.NN; ++ii) {
25894    dataL ^= this.parray[ii];
25895    dataR = this._F(dataL) ^ dataR;
25896
25897    const tmp = dataL;
25898    dataL = dataR;
25899    dataR = tmp;
25900  }
25901
25902  dataL ^= this.parray[this.NN + 0];
25903  dataR ^= this.parray[this.NN + 1];
25904
25905  vals[0] = this._clean(dataR);
25906  vals[1] = this._clean(dataL);
25907};
25908
25909//*
25910//* This method takes a vector of numbers and turns them
25911//* into long words so that they can be processed by the
25912//* real algorithm.
25913//*
25914//* Maybe I should make the real algorithm above take a vector
25915//* instead.  That will involve more looping, but it won't require
25916//* the F() method to deconstruct the vector.
25917//*
25918Blowfish.prototype.encrypt_block = function (vector) {
25919  let ii;
25920  const vals = [0, 0];
25921  const off = this.BLOCKSIZE / 2;
25922  for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
25923    vals[0] = vals[0] << 8 | vector[ii + 0] & 0x00FF;
25924    vals[1] = vals[1] << 8 | vector[ii + off] & 0x00FF;
25925  }
25926
25927  this._encrypt_block(vals);
25928
25929  const ret = [];
25930  for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
25931    ret[ii + 0] = vals[0] >>> 24 - 8 * ii & 0x00FF;
25932    ret[ii + off] = vals[1] >>> 24 - 8 * ii & 0x00FF;
25933    // vals[ 0 ] = ( vals[ 0 ] >>> 8 );
25934    // vals[ 1 ] = ( vals[ 1 ] >>> 8 );
25935  }
25936
25937  return ret;
25938};
25939
25940//*
25941//* This method takes an array with two values, left and right
25942//* and undoes NN rounds of Blowfish on them.
25943//*
25944Blowfish.prototype._decrypt_block = function (vals) {
25945  let dataL = vals[0];
25946  let dataR = vals[1];
25947
25948  let ii;
25949
25950  for (ii = this.NN + 1; ii > 1; --ii) {
25951    dataL ^= this.parray[ii];
25952    dataR = this._F(dataL) ^ dataR;
25953
25954    const tmp = dataL;
25955    dataL = dataR;
25956    dataR = tmp;
25957  }
25958
25959  dataL ^= this.parray[1];
25960  dataR ^= this.parray[0];
25961
25962  vals[0] = this._clean(dataR);
25963  vals[1] = this._clean(dataL);
25964};
25965
25966//*
25967//* This method takes a key array and initializes the
25968//* sboxes and parray for this encryption.
25969//*
25970Blowfish.prototype.init = function (key) {
25971  let ii;
25972  let jj = 0;
25973
25974  this.parray = [];
25975  for (ii = 0; ii < this.NN + 2; ++ii) {
25976    let data = 0x00000000;
25977    for (let kk = 0; kk < 4; ++kk) {
25978      data = data << 8 | key[jj] & 0x00FF;
25979      if (++jj >= key.length) {
25980        jj = 0;
25981      }
25982    }
25983    this.parray[ii] = this.PARRAY[ii] ^ data;
25984  }
25985
25986  this.sboxes = [];
25987  for (ii = 0; ii < 4; ++ii) {
25988    this.sboxes[ii] = [];
25989    for (jj = 0; jj < 256; ++jj) {
25990      this.sboxes[ii][jj] = this.SBOXES[ii][jj];
25991    }
25992  }
25993
25994  const vals = [0x00000000, 0x00000000];
25995
25996  for (ii = 0; ii < this.NN + 2; ii += 2) {
25997    this._encrypt_block(vals);
25998    this.parray[ii + 0] = vals[0];
25999    this.parray[ii + 1] = vals[1];
26000  }
26001
26002  for (ii = 0; ii < 4; ++ii) {
26003    for (jj = 0; jj < 256; jj += 2) {
26004      this._encrypt_block(vals);
26005      this.sboxes[ii][jj + 0] = vals[0];
26006      this.sboxes[ii][jj + 1] = vals[1];
26007    }
26008  }
26009};
26010
26011// added by Recurity Labs
26012function BF(key) {
26013  this.bf = new Blowfish();
26014  this.bf.init(key);
26015
26016  this.encrypt = function (block) {
26017    return this.bf.encrypt_block(block);
26018  };
26019}
26020
26021BF.keySize = BF.prototype.keySize = 16;
26022BF.blockSize = BF.prototype.blockSize = 16;
26023
26024exports.default = BF;
26025
26026},{}],85:[function(require,module,exports){
26027'use strict';
26028
26029Object.defineProperty(exports, "__esModule", {
26030  value: true
26031});
26032// Use of this source code is governed by a BSD-style
26033// license that can be found in the LICENSE file.
26034
26035// Copyright 2010 pjacobs@xeekr.com . All rights reserved.
26036
26037// Modified by Recurity Labs GmbH
26038
26039// fixed/modified by Herbert Hanewinkel, www.haneWIN.de
26040// check www.haneWIN.de for the latest version
26041
26042// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.
26043// CAST-128 is a common OpenPGP cipher.
26044
26045
26046// CAST5 constructor
26047
26048function OpenpgpSymencCast5() {
26049  this.BlockSize = 8;
26050  this.KeySize = 16;
26051
26052  this.setKey = function (key) {
26053    this.masking = new Array(16);
26054    this.rotate = new Array(16);
26055
26056    this.reset();
26057
26058    if (key.length === this.KeySize) {
26059      this.keySchedule(key);
26060    } else {
26061      throw new Error('CAST-128: keys must be 16 bytes');
26062    }
26063    return true;
26064  };
26065
26066  this.reset = function () {
26067    for (let i = 0; i < 16; i++) {
26068      this.masking[i] = 0;
26069      this.rotate[i] = 0;
26070    }
26071  };
26072
26073  this.getBlockSize = function () {
26074    return this.BlockSize;
26075  };
26076
26077  this.encrypt = function (src) {
26078    const dst = new Array(src.length);
26079
26080    for (let i = 0; i < src.length; i += 8) {
26081      let l = src[i] << 24 | src[i + 1] << 16 | src[i + 2] << 8 | src[i + 3];
26082      let r = src[i + 4] << 24 | src[i + 5] << 16 | src[i + 6] << 8 | src[i + 7];
26083      let t;
26084
26085      t = r;
26086      r = l ^ f1(r, this.masking[0], this.rotate[0]);
26087      l = t;
26088      t = r;
26089      r = l ^ f2(r, this.masking[1], this.rotate[1]);
26090      l = t;
26091      t = r;
26092      r = l ^ f3(r, this.masking[2], this.rotate[2]);
26093      l = t;
26094      t = r;
26095      r = l ^ f1(r, this.masking[3], this.rotate[3]);
26096      l = t;
26097
26098      t = r;
26099      r = l ^ f2(r, this.masking[4], this.rotate[4]);
26100      l = t;
26101      t = r;
26102      r = l ^ f3(r, this.masking[5], this.rotate[5]);
26103      l = t;
26104      t = r;
26105      r = l ^ f1(r, this.masking[6], this.rotate[6]);
26106      l = t;
26107      t = r;
26108      r = l ^ f2(r, this.masking[7], this.rotate[7]);
26109      l = t;
26110
26111      t = r;
26112      r = l ^ f3(r, this.masking[8], this.rotate[8]);
26113      l = t;
26114      t = r;
26115      r = l ^ f1(r, this.masking[9], this.rotate[9]);
26116      l = t;
26117      t = r;
26118      r = l ^ f2(r, this.masking[10], this.rotate[10]);
26119      l = t;
26120      t = r;
26121      r = l ^ f3(r, this.masking[11], this.rotate[11]);
26122      l = t;
26123
26124      t = r;
26125      r = l ^ f1(r, this.masking[12], this.rotate[12]);
26126      l = t;
26127      t = r;
26128      r = l ^ f2(r, this.masking[13], this.rotate[13]);
26129      l = t;
26130      t = r;
26131      r = l ^ f3(r, this.masking[14], this.rotate[14]);
26132      l = t;
26133      t = r;
26134      r = l ^ f1(r, this.masking[15], this.rotate[15]);
26135      l = t;
26136
26137      dst[i] = r >>> 24 & 255;
26138      dst[i + 1] = r >>> 16 & 255;
26139      dst[i + 2] = r >>> 8 & 255;
26140      dst[i + 3] = r & 255;
26141      dst[i + 4] = l >>> 24 & 255;
26142      dst[i + 5] = l >>> 16 & 255;
26143      dst[i + 6] = l >>> 8 & 255;
26144      dst[i + 7] = l & 255;
26145    }
26146
26147    return dst;
26148  };
26149
26150  this.decrypt = function (src) {
26151    const dst = new Array(src.length);
26152
26153    for (let i = 0; i < src.length; i += 8) {
26154      let l = src[i] << 24 | src[i + 1] << 16 | src[i + 2] << 8 | src[i + 3];
26155      let r = src[i + 4] << 24 | src[i + 5] << 16 | src[i + 6] << 8 | src[i + 7];
26156      let t;
26157
26158      t = r;
26159      r = l ^ f1(r, this.masking[15], this.rotate[15]);
26160      l = t;
26161      t = r;
26162      r = l ^ f3(r, this.masking[14], this.rotate[14]);
26163      l = t;
26164      t = r;
26165      r = l ^ f2(r, this.masking[13], this.rotate[13]);
26166      l = t;
26167      t = r;
26168      r = l ^ f1(r, this.masking[12], this.rotate[12]);
26169      l = t;
26170
26171      t = r;
26172      r = l ^ f3(r, this.masking[11], this.rotate[11]);
26173      l = t;
26174      t = r;
26175      r = l ^ f2(r, this.masking[10], this.rotate[10]);
26176      l = t;
26177      t = r;
26178      r = l ^ f1(r, this.masking[9], this.rotate[9]);
26179      l = t;
26180      t = r;
26181      r = l ^ f3(r, this.masking[8], this.rotate[8]);
26182      l = t;
26183
26184      t = r;
26185      r = l ^ f2(r, this.masking[7], this.rotate[7]);
26186      l = t;
26187      t = r;
26188      r = l ^ f1(r, this.masking[6], this.rotate[6]);
26189      l = t;
26190      t = r;
26191      r = l ^ f3(r, this.masking[5], this.rotate[5]);
26192      l = t;
26193      t = r;
26194      r = l ^ f2(r, this.masking[4], this.rotate[4]);
26195      l = t;
26196
26197      t = r;
26198      r = l ^ f1(r, this.masking[3], this.rotate[3]);
26199      l = t;
26200      t = r;
26201      r = l ^ f3(r, this.masking[2], this.rotate[2]);
26202      l = t;
26203      t = r;
26204      r = l ^ f2(r, this.masking[1], this.rotate[1]);
26205      l = t;
26206      t = r;
26207      r = l ^ f1(r, this.masking[0], this.rotate[0]);
26208      l = t;
26209
26210      dst[i] = r >>> 24 & 255;
26211      dst[i + 1] = r >>> 16 & 255;
26212      dst[i + 2] = r >>> 8 & 255;
26213      dst[i + 3] = r & 255;
26214      dst[i + 4] = l >>> 24 & 255;
26215      dst[i + 5] = l >> 16 & 255;
26216      dst[i + 6] = l >> 8 & 255;
26217      dst[i + 7] = l & 255;
26218    }
26219
26220    return dst;
26221  };
26222  const scheduleA = new Array(4);
26223
26224  scheduleA[0] = new Array(4);
26225  scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];
26226  scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
26227  scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
26228  scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
26229
26230  scheduleA[1] = new Array(4);
26231  scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
26232  scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
26233  scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
26234  scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
26235
26236  scheduleA[2] = new Array(4);
26237  scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];
26238  scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
26239  scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
26240  scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
26241
26242  scheduleA[3] = new Array(4);
26243  scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
26244  scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
26245  scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
26246  scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
26247
26248  const scheduleB = new Array(4);
26249
26250  scheduleB[0] = new Array(4);
26251  scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];
26252  scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];
26253  scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];
26254  scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];
26255
26256  scheduleB[1] = new Array(4);
26257  scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];
26258  scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];
26259  scheduleB[1][2] = [7, 6, 8, 9, 3];
26260  scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];
26261
26262  scheduleB[2] = new Array(4);
26263  scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];
26264  scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];
26265  scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];
26266  scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];
26267
26268  scheduleB[3] = new Array(4);
26269  scheduleB[3][0] = [8, 9, 7, 6, 3];
26270  scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];
26271  scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];
26272  scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];
26273
26274  // changed 'in' to 'inn' (in javascript 'in' is a reserved word)
26275  this.keySchedule = function (inn) {
26276    const t = new Array(8);
26277    const k = new Array(32);
26278
26279    let j;
26280
26281    for (let i = 0; i < 4; i++) {
26282      j = i * 4;
26283      t[i] = inn[j] << 24 | inn[j + 1] << 16 | inn[j + 2] << 8 | inn[j + 3];
26284    }
26285
26286    const x = [6, 7, 4, 5];
26287    let ki = 0;
26288    let w;
26289
26290    for (let half = 0; half < 2; half++) {
26291      for (let round = 0; round < 4; round++) {
26292        for (j = 0; j < 4; j++) {
26293          const a = scheduleA[round][j];
26294          w = t[a[1]];
26295
26296          w ^= sBox[4][t[a[2] >>> 2] >>> 24 - 8 * (a[2] & 3) & 0xff];
26297          w ^= sBox[5][t[a[3] >>> 2] >>> 24 - 8 * (a[3] & 3) & 0xff];
26298          w ^= sBox[6][t[a[4] >>> 2] >>> 24 - 8 * (a[4] & 3) & 0xff];
26299          w ^= sBox[7][t[a[5] >>> 2] >>> 24 - 8 * (a[5] & 3) & 0xff];
26300          w ^= sBox[x[j]][t[a[6] >>> 2] >>> 24 - 8 * (a[6] & 3) & 0xff];
26301          t[a[0]] = w;
26302        }
26303
26304        for (j = 0; j < 4; j++) {
26305          const b = scheduleB[round][j];
26306          w = sBox[4][t[b[0] >>> 2] >>> 24 - 8 * (b[0] & 3) & 0xff];
26307
26308          w ^= sBox[5][t[b[1] >>> 2] >>> 24 - 8 * (b[1] & 3) & 0xff];
26309          w ^= sBox[6][t[b[2] >>> 2] >>> 24 - 8 * (b[2] & 3) & 0xff];
26310          w ^= sBox[7][t[b[3] >>> 2] >>> 24 - 8 * (b[3] & 3) & 0xff];
26311          w ^= sBox[4 + j][t[b[4] >>> 2] >>> 24 - 8 * (b[4] & 3) & 0xff];
26312          k[ki] = w;
26313          ki++;
26314        }
26315      }
26316    }
26317
26318    for (let i = 0; i < 16; i++) {
26319      this.masking[i] = k[i];
26320      this.rotate[i] = k[16 + i] & 0x1f;
26321    }
26322  };
26323
26324  // These are the three 'f' functions. See RFC 2144, section 2.2.
26325
26326  function f1(d, m, r) {
26327    const t = m + d;
26328    const I = t << r | t >>> 32 - r;
26329    return (sBox[0][I >>> 24] ^ sBox[1][I >>> 16 & 255]) - sBox[2][I >>> 8 & 255] + sBox[3][I & 255];
26330  }
26331
26332  function f2(d, m, r) {
26333    const t = m ^ d;
26334    const I = t << r | t >>> 32 - r;
26335    return sBox[0][I >>> 24] - sBox[1][I >>> 16 & 255] + sBox[2][I >>> 8 & 255] ^ sBox[3][I & 255];
26336  }
26337
26338  function f3(d, m, r) {
26339    const t = m - d;
26340    const I = t << r | t >>> 32 - r;
26341    return (sBox[0][I >>> 24] + sBox[1][I >>> 16 & 255] ^ sBox[2][I >>> 8 & 255]) - sBox[3][I & 255];
26342  }
26343
26344  const sBox = new Array(8);
26345  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];
26346
26347  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];
26348
26349  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];
26350
26351  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];
26352
26353  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];
26354
26355  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];
26356
26357  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];
26358
26359  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];
26360}
26361
26362function Cast5(key) {
26363  this.cast5 = new OpenpgpSymencCast5();
26364  this.cast5.setKey(key);
26365
26366  this.encrypt = function (block) {
26367    return this.cast5.encrypt(block);
26368  };
26369}
26370
26371Cast5.blockSize = Cast5.prototype.blockSize = 8;
26372Cast5.keySize = Cast5.prototype.keySize = 16;
26373
26374exports.default = Cast5;
26375
26376},{}],86:[function(require,module,exports){
26377"use strict";
26378
26379Object.defineProperty(exports, "__esModule", {
26380  value: true
26381});
26382//Paul Tero, July 2001
26383//http://www.tero.co.uk/des/
26384//
26385//Optimised for performance with large blocks by Michael Hayworth, November 2001
26386//http://www.netdealing.com
26387//
26388// Modified by Recurity Labs GmbH
26389
26390//THIS SOFTWARE IS PROVIDED "AS IS" AND
26391//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26392//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26393//ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26394//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26395//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26396//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26397//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26398//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26399//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26400//SUCH DAMAGE.
26401
26402//des
26403//this takes the key, the message, and whether to encrypt or decrypt
26404
26405function des(keys, message, encrypt, mode, iv, padding) {
26406  //declaring this locally speeds things up a bit
26407  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];
26408  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];
26409  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];
26410  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];
26411  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];
26412  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];
26413  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];
26414  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];
26415
26416  //create the 16 or 48 subkeys we will need
26417  let m = 0;
26418  let i;
26419  let j;
26420  let temp;
26421  let right1;
26422  let right2;
26423  let left;
26424  let right;
26425  let looping;
26426  let cbcleft;
26427  let cbcleft2;
26428  let cbcright;
26429  let cbcright2;
26430  let endloop;
26431  let loopinc;
26432  let len = message.length;
26433
26434  //set up the loops for single and triple des
26435  const iterations = keys.length === 32 ? 3 : 9; //single or triple des
26436  if (iterations === 3) {
26437    looping = encrypt ? [0, 32, 2] : [30, -2, -2];
26438  } else {
26439    looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];
26440  }
26441
26442  //pad the message depending on the padding parameter
26443  //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt
26444  if (encrypt) {
26445    message = des_addPadding(message, padding);
26446    len = message.length;
26447  }
26448
26449  //store the result here
26450  let result = new Uint8Array(len);
26451  let k = 0;
26452
26453  if (mode === 1) {
26454    //CBC mode
26455    cbcleft = iv[m++] << 24 | iv[m++] << 16 | iv[m++] << 8 | iv[m++];
26456    cbcright = iv[m++] << 24 | iv[m++] << 16 | iv[m++] << 8 | iv[m++];
26457    m = 0;
26458  }
26459
26460  //loop through each 64 bit chunk of the message
26461  while (m < len) {
26462    left = message[m++] << 24 | message[m++] << 16 | message[m++] << 8 | message[m++];
26463    right = message[m++] << 24 | message[m++] << 16 | message[m++] << 8 | message[m++];
26464
26465    //for Cipher Block Chaining mode, xor the message with the previous result
26466    if (mode === 1) {
26467      if (encrypt) {
26468        left ^= cbcleft;
26469        right ^= cbcright;
26470      } else {
26471        cbcleft2 = cbcleft;
26472        cbcright2 = cbcright;
26473        cbcleft = left;
26474        cbcright = right;
26475      }
26476    }
26477
26478    //first each 64 but chunk of the message must be permuted according to IP
26479    temp = (left >>> 4 ^ right) & 0x0f0f0f0f;
26480    right ^= temp;
26481    left ^= temp << 4;
26482    temp = (left >>> 16 ^ right) & 0x0000ffff;
26483    right ^= temp;
26484    left ^= temp << 16;
26485    temp = (right >>> 2 ^ left) & 0x33333333;
26486    left ^= temp;
26487    right ^= temp << 2;
26488    temp = (right >>> 8 ^ left) & 0x00ff00ff;
26489    left ^= temp;
26490    right ^= temp << 8;
26491    temp = (left >>> 1 ^ right) & 0x55555555;
26492    right ^= temp;
26493    left ^= temp << 1;
26494
26495    left = left << 1 | left >>> 31;
26496    right = right << 1 | right >>> 31;
26497
26498    //do this either 1 or 3 times for each chunk of the message
26499    for (j = 0; j < iterations; j += 3) {
26500      endloop = looping[j + 1];
26501      loopinc = looping[j + 2];
26502      //now go through and perform the encryption or decryption
26503      for (i = looping[j]; i !== endloop; i += loopinc) {
26504        //for efficiency
26505        right1 = right ^ keys[i];
26506        right2 = (right >>> 4 | right << 28) ^ keys[i + 1];
26507        //the result is attained by passing these bytes through the S selection functions
26508        temp = left;
26509        left = right;
26510        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]);
26511      }
26512      temp = left;
26513      left = right;
26514      right = temp; //unreverse left and right
26515    } //for either 1 or 3 iterations
26516
26517    //move then each one bit to the right
26518    left = left >>> 1 | left << 31;
26519    right = right >>> 1 | right << 31;
26520
26521    //now perform IP-1, which is IP in the opposite direction
26522    temp = (left >>> 1 ^ right) & 0x55555555;
26523    right ^= temp;
26524    left ^= temp << 1;
26525    temp = (right >>> 8 ^ left) & 0x00ff00ff;
26526    left ^= temp;
26527    right ^= temp << 8;
26528    temp = (right >>> 2 ^ left) & 0x33333333;
26529    left ^= temp;
26530    right ^= temp << 2;
26531    temp = (left >>> 16 ^ right) & 0x0000ffff;
26532    right ^= temp;
26533    left ^= temp << 16;
26534    temp = (left >>> 4 ^ right) & 0x0f0f0f0f;
26535    right ^= temp;
26536    left ^= temp << 4;
26537
26538    //for Cipher Block Chaining mode, xor the message with the previous result
26539    if (mode === 1) {
26540      if (encrypt) {
26541        cbcleft = left;
26542        cbcright = right;
26543      } else {
26544        left ^= cbcleft2;
26545        right ^= cbcright2;
26546      }
26547    }
26548
26549    result[k++] = left >>> 24;
26550    result[k++] = left >>> 16 & 0xff;
26551    result[k++] = left >>> 8 & 0xff;
26552    result[k++] = left & 0xff;
26553    result[k++] = right >>> 24;
26554    result[k++] = right >>> 16 & 0xff;
26555    result[k++] = right >>> 8 & 0xff;
26556    result[k++] = right & 0xff;
26557  } //for every 8 characters, or 64 bits in the message
26558
26559  //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt
26560  if (!encrypt) {
26561    result = des_removePadding(result, padding);
26562  }
26563
26564  return result;
26565} //end of des
26566
26567
26568//des_createKeys
26569//this takes as input a 64 bit key (even though only 56 bits are used)
26570//as an array of 2 integers, and returns 16 48 bit keys
26571
26572function des_createKeys(key) {
26573  //declaring this locally speeds things up a bit
26574  const pc2bytes0 = [0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204];
26575  const pc2bytes1 = [0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100, 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101];
26576  const pc2bytes2 = [0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808];
26577  const pc2bytes3 = [0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000, 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000];
26578  const pc2bytes4 = [0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000, 0x41000, 0x1010, 0x41010];
26579  const pc2bytes5 = [0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420, 0x2000000, 0x2000400, 0x2000020, 0x2000420];
26580  const pc2bytes6 = [0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002];
26581  const pc2bytes7 = [0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000, 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800];
26582  const pc2bytes8 = [0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000, 0x2000002, 0x2040002, 0x2000002, 0x2040002];
26583  const pc2bytes9 = [0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408, 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408];
26584  const pc2bytes10 = [0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020, 0x102000, 0x102020, 0x102000, 0x102020];
26585  const pc2bytes11 = [0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000, 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200];
26586  const pc2bytes12 = [0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010, 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010];
26587  const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];
26588
26589  //how many iterations (1 for des, 3 for triple des)
26590  const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys
26591  //stores the return keys
26592  const keys = new Array(32 * iterations);
26593  //now define the left shifts which need to be done
26594  const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];
26595  //other variables
26596  let lefttemp;
26597  let righttemp;
26598  let m = 0;
26599  let n = 0;
26600  let temp;
26601
26602  for (let j = 0; j < iterations; j++) {
26603    //either 1 or 3 iterations
26604    let left = key[m++] << 24 | key[m++] << 16 | key[m++] << 8 | key[m++];
26605    let right = key[m++] << 24 | key[m++] << 16 | key[m++] << 8 | key[m++];
26606
26607    temp = (left >>> 4 ^ right) & 0x0f0f0f0f;
26608    right ^= temp;
26609    left ^= temp << 4;
26610    temp = (right >>> -16 ^ left) & 0x0000ffff;
26611    left ^= temp;
26612    right ^= temp << -16;
26613    temp = (left >>> 2 ^ right) & 0x33333333;
26614    right ^= temp;
26615    left ^= temp << 2;
26616    temp = (right >>> -16 ^ left) & 0x0000ffff;
26617    left ^= temp;
26618    right ^= temp << -16;
26619    temp = (left >>> 1 ^ right) & 0x55555555;
26620    right ^= temp;
26621    left ^= temp << 1;
26622    temp = (right >>> 8 ^ left) & 0x00ff00ff;
26623    left ^= temp;
26624    right ^= temp << 8;
26625    temp = (left >>> 1 ^ right) & 0x55555555;
26626    right ^= temp;
26627    left ^= temp << 1;
26628
26629    //the right side needs to be shifted and to get the last four bits of the left side
26630    temp = left << 8 | right >>> 20 & 0x000000f0;
26631    //left needs to be put upside down
26632    left = right << 24 | right << 8 & 0xff0000 | right >>> 8 & 0xff00 | right >>> 24 & 0xf0;
26633    right = temp;
26634
26635    //now go through and perform these shifts on the left and right keys
26636    for (let i = 0; i < shifts.length; i++) {
26637      //shift the keys either one or two bits to the left
26638      if (shifts[i]) {
26639        left = left << 2 | left >>> 26;
26640        right = right << 2 | right >>> 26;
26641      } else {
26642        left = left << 1 | left >>> 27;
26643        right = right << 1 | right >>> 27;
26644      }
26645      left &= -0xf;
26646      right &= -0xf;
26647
26648      //now apply PC-2, in such a way that E is easier when encrypting or decrypting
26649      //this conversion will look like PC-2 except only the last 6 bits of each byte are used
26650      //rather than 48 consecutive bits and the order of lines will be according to
26651      //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7
26652      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];
26653      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];
26654      temp = (righttemp >>> 16 ^ lefttemp) & 0x0000ffff;
26655      keys[n++] = lefttemp ^ temp;
26656      keys[n++] = righttemp ^ temp << 16;
26657    }
26658  } //for each iterations
26659  //return the keys we've created
26660  return keys;
26661} //end of des_createKeys
26662
26663
26664function des_addPadding(message, padding) {
26665  const padLength = 8 - message.length % 8;
26666
26667  let pad;
26668  if (padding === 2 && padLength < 8) {
26669    //pad the message with spaces
26670    pad = " ".charCodeAt(0);
26671  } else if (padding === 1) {
26672    //PKCS7 padding
26673    pad = padLength;
26674  } else if (!padding && padLength < 8) {
26675    //pad the message out with null bytes
26676    pad = 0;
26677  } else if (padLength === 8) {
26678    return message;
26679  } else {
26680    throw new Error('des: invalid padding');
26681  }
26682
26683  const paddedMessage = new Uint8Array(message.length + padLength);
26684  for (let i = 0; i < message.length; i++) {
26685    paddedMessage[i] = message[i];
26686  }
26687  for (let j = 0; j < padLength; j++) {
26688    paddedMessage[message.length + j] = pad;
26689  }
26690
26691  return paddedMessage;
26692}
26693
26694function des_removePadding(message, padding) {
26695  let padLength = null;
26696  let pad;
26697  if (padding === 2) {
26698    // space padded
26699    pad = " ".charCodeAt(0);
26700  } else if (padding === 1) {
26701    // PKCS7
26702    padLength = message[message.length - 1];
26703  } else if (!padding) {
26704    // null padding
26705    pad = 0;
26706  } else {
26707    throw new Error('des: invalid padding');
26708  }
26709
26710  if (!padLength) {
26711    padLength = 1;
26712    while (message[message.length - padLength] === pad) {
26713      padLength++;
26714    }
26715    padLength--;
26716  }
26717
26718  return message.subarray(0, message.length - padLength);
26719}
26720
26721// added by Recurity Labs
26722
26723function TripleDES(key) {
26724  this.key = [];
26725
26726  for (let i = 0; i < 3; i++) {
26727    this.key.push(new Uint8Array(key.subarray(i * 8, i * 8 + 8)));
26728  }
26729
26730  this.encrypt = function (block) {
26731    return des(des_createKeys(this.key[2]), des(des_createKeys(this.key[1]), des(des_createKeys(this.key[0]), block, true, 0, null, null), false, 0, null, null), true, 0, null, null);
26732  };
26733}
26734
26735TripleDES.keySize = TripleDES.prototype.keySize = 24;
26736TripleDES.blockSize = TripleDES.prototype.blockSize = 8;
26737
26738// This is "original" DES
26739
26740function DES(key) {
26741  this.key = key;
26742
26743  this.encrypt = function (block, padding) {
26744    const keys = des_createKeys(this.key);
26745    return des(keys, block, true, 0, null, padding);
26746  };
26747
26748  this.decrypt = function (block, padding) {
26749    const keys = des_createKeys(this.key);
26750    return des(keys, block, false, 0, null, padding);
26751  };
26752}
26753
26754exports.default = { DES, TripleDES };
26755
26756},{}],87:[function(require,module,exports){
26757'use strict';
26758
26759Object.defineProperty(exports, "__esModule", {
26760  value: true
26761});
26762
26763var _aes = require('./aes');
26764
26765var _aes2 = _interopRequireDefault(_aes);
26766
26767var _des = require('./des.js');
26768
26769var _des2 = _interopRequireDefault(_des);
26770
26771var _cast = require('./cast5');
26772
26773var _cast2 = _interopRequireDefault(_cast);
26774
26775var _twofish = require('./twofish');
26776
26777var _twofish2 = _interopRequireDefault(_twofish);
26778
26779var _blowfish = require('./blowfish');
26780
26781var _blowfish2 = _interopRequireDefault(_blowfish);
26782
26783function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
26784
26785exports.default = {
26786  /**
26787   * AES-128 encryption and decryption (ID 7)
26788   * @function
26789   * @param {String} key 128-bit key
26790   * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
26791   * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
26792   * @returns {Object}
26793   * @requires asmcrypto.js
26794   */
26795  aes128: (0, _aes2.default)(128),
26796  /**
26797   * AES-128 Block Cipher (ID 8)
26798   * @function
26799   * @param {String} key 192-bit key
26800   * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
26801   * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
26802   * @returns {Object}
26803   * @requires asmcrypto.js
26804   */
26805  aes192: (0, _aes2.default)(192),
26806  /**
26807   * AES-128 Block Cipher (ID 9)
26808   * @function
26809   * @param {String} key 256-bit key
26810   * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
26811   * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
26812   * @returns {Object}
26813   * @requires asmcrypto.js
26814   */
26815  aes256: (0, _aes2.default)(256),
26816  // Not in OpenPGP specifications
26817  des: _des2.default.DES,
26818  /**
26819   * Triple DES Block Cipher (ID 2)
26820   * @function
26821   * @param {String} key 192-bit key
26822   * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67}
26823   * @returns {Object}
26824   */
26825  tripledes: _des2.default.TripleDES,
26826  '3des': _des2.default.TripleDES,
26827  /**
26828   * CAST-128 Block Cipher (ID 3)
26829   * @function
26830   * @param {String} key 128-bit key
26831   * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm}
26832   * @returns {Object}
26833   */
26834  cast5: _cast2.default,
26835  /**
26836   * Twofish Block Cipher (ID 10)
26837   * @function
26838   * @param {String} key 256-bit key
26839   * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH}
26840   * @returns {Object}
26841   */
26842  twofish: _twofish2.default,
26843  /**
26844   * Blowfish Block Cipher (ID 4)
26845   * @function
26846   * @param {String} key 128-bit key
26847   * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH}
26848   * @returns {Object}
26849   */
26850  blowfish: _blowfish2.default,
26851  /**
26852   * Not implemented
26853   * @function
26854   * @throws {Error}
26855   */
26856  idea: function idea() {
26857    throw new Error('IDEA symmetric-key algorithm not implemented');
26858  }
26859}; /**
26860    * @fileoverview Symmetric cryptography functions
26861    * @requires crypto/cipher/aes
26862    * @requires crypto/cipher/des
26863    * @requires crypto/cipher/cast5
26864    * @requires crypto/cipher/twofish
26865    * @requires crypto/cipher/blowfish
26866    * @module crypto/cipher
26867    */
26868
26869},{"./aes":83,"./blowfish":84,"./cast5":85,"./des.js":86,"./twofish":88}],88:[function(require,module,exports){
26870"use strict";
26871
26872Object.defineProperty(exports, "__esModule", {
26873  value: true
26874});
26875/* eslint-disable no-mixed-operators, no-fallthrough */
26876
26877/* Modified by Recurity Labs GmbH
26878 *
26879 * Cipher.js
26880 * A block-cipher algorithm implementation on JavaScript
26881 * See Cipher.readme.txt for further information.
26882 *
26883 * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]
26884 * This script file is distributed under the LGPL
26885 *
26886 * ACKNOWLEDGMENT
26887 *
26888 *     The main subroutines are written by Michiel van Everdingen.
26889 *
26890 *     Michiel van Everdingen
26891 *     http://home.versatel.nl/MAvanEverdingen/index.html
26892 *
26893 *     All rights for these routines are reserved to Michiel van Everdingen.
26894 *
26895 */
26896
26897////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
26898//Math
26899////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
26900
26901const MAXINT = 0xFFFFFFFF;
26902
26903function rotw(w, n) {
26904  return (w << n | w >>> 32 - n) & MAXINT;
26905}
26906
26907function getW(a, i) {
26908  return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;
26909}
26910
26911function setW(a, i, w) {
26912  a.splice(i, 4, w & 0xFF, w >>> 8 & 0xFF, w >>> 16 & 0xFF, w >>> 24 & 0xFF);
26913}
26914
26915function getB(x, n) {
26916  return x >>> n * 8 & 0xFF;
26917}
26918
26919// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
26920// Twofish
26921// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
26922
26923function createTwofish() {
26924  //
26925  let keyBytes = null;
26926  let dataBytes = null;
26927  let dataOffset = -1;
26928  // var dataLength = -1;
26929  // var idx2 = -1;
26930  //
26931
26932  let tfsKey = [];
26933  let tfsM = [[], [], [], []];
26934
26935  function tfsInit(key) {
26936    keyBytes = key;
26937    let i;
26938    let a;
26939    let b;
26940    let c;
26941    let d;
26942    const meKey = [];
26943    const moKey = [];
26944    const inKey = [];
26945    let kLen;
26946    const sKey = [];
26947    let f01;
26948    let f5b;
26949    let fef;
26950
26951    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]];
26952    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]];
26953    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]];
26954    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]];
26955    const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];
26956    const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];
26957    const q = [[], []];
26958    const m = [[], [], [], []];
26959
26960    function ffm5b(x) {
26961      return x ^ x >> 2 ^ [0, 90, 180, 238][x & 3];
26962    }
26963
26964    function ffmEf(x) {
26965      return x ^ x >> 1 ^ x >> 2 ^ [0, 238, 180, 90][x & 3];
26966    }
26967
26968    function mdsRem(p, q) {
26969      let i;
26970      let t;
26971      let u;
26972      for (i = 0; i < 8; i++) {
26973        t = q >>> 24;
26974        q = q << 8 & MAXINT | p >>> 24;
26975        p = p << 8 & MAXINT;
26976        u = t << 1;
26977        if (t & 128) {
26978          u ^= 333;
26979        }
26980        q ^= t ^ u << 16;
26981        u ^= t >>> 1;
26982        if (t & 1) {
26983          u ^= 166;
26984        }
26985        q ^= u << 24 | u << 8;
26986      }
26987      return q;
26988    }
26989
26990    function qp(n, x) {
26991      const a = x >> 4;
26992      const b = x & 15;
26993      const c = q0[n][a ^ b];
26994      const d = q1[n][ror4[b] ^ ashx[a]];
26995      return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];
26996    }
26997
26998    function hFun(x, key) {
26999      let a = getB(x, 0);
27000      let b = getB(x, 1);
27001      let c = getB(x, 2);
27002      let d = getB(x, 3);
27003      switch (kLen) {
27004        case 4:
27005          a = q[1][a] ^ getB(key[3], 0);
27006          b = q[0][b] ^ getB(key[3], 1);
27007          c = q[0][c] ^ getB(key[3], 2);
27008          d = q[1][d] ^ getB(key[3], 3);
27009        case 3:
27010          a = q[1][a] ^ getB(key[2], 0);
27011          b = q[1][b] ^ getB(key[2], 1);
27012          c = q[0][c] ^ getB(key[2], 2);
27013          d = q[0][d] ^ getB(key[2], 3);
27014        case 2:
27015          a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);
27016          b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);
27017          c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);
27018          d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);
27019      }
27020      return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];
27021    }
27022
27023    keyBytes = keyBytes.slice(0, 32);
27024    i = keyBytes.length;
27025    while (i !== 16 && i !== 24 && i !== 32) {
27026      keyBytes[i++] = 0;
27027    }
27028
27029    for (i = 0; i < keyBytes.length; i += 4) {
27030      inKey[i >> 2] = getW(keyBytes, i);
27031    }
27032    for (i = 0; i < 256; i++) {
27033      q[0][i] = qp(0, i);
27034      q[1][i] = qp(1, i);
27035    }
27036    for (i = 0; i < 256; i++) {
27037      f01 = q[1][i];
27038      f5b = ffm5b(f01);
27039      fef = ffmEf(f01);
27040      m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);
27041      m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);
27042      f01 = q[0][i];
27043      f5b = ffm5b(f01);
27044      fef = ffmEf(f01);
27045      m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);
27046      m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);
27047    }
27048
27049    kLen = inKey.length / 2;
27050    for (i = 0; i < kLen; i++) {
27051      a = inKey[i + i];
27052      meKey[i] = a;
27053      b = inKey[i + i + 1];
27054      moKey[i] = b;
27055      sKey[kLen - i - 1] = mdsRem(a, b);
27056    }
27057    for (i = 0; i < 40; i += 2) {
27058      a = 0x1010101 * i;
27059      b = a + 0x1010101;
27060      a = hFun(a, meKey);
27061      b = rotw(hFun(b, moKey), 8);
27062      tfsKey[i] = a + b & MAXINT;
27063      tfsKey[i + 1] = rotw(a + 2 * b, 9);
27064    }
27065    for (i = 0; i < 256; i++) {
27066      a = b = c = d = i;
27067      switch (kLen) {
27068        case 4:
27069          a = q[1][a] ^ getB(sKey[3], 0);
27070          b = q[0][b] ^ getB(sKey[3], 1);
27071          c = q[0][c] ^ getB(sKey[3], 2);
27072          d = q[1][d] ^ getB(sKey[3], 3);
27073        case 3:
27074          a = q[1][a] ^ getB(sKey[2], 0);
27075          b = q[1][b] ^ getB(sKey[2], 1);
27076          c = q[0][c] ^ getB(sKey[2], 2);
27077          d = q[0][d] ^ getB(sKey[2], 3);
27078        case 2:
27079          tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];
27080          tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];
27081          tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];
27082          tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];
27083      }
27084    }
27085  }
27086
27087  function tfsG0(x) {
27088    return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];
27089  }
27090
27091  function tfsG1(x) {
27092    return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];
27093  }
27094
27095  function tfsFrnd(r, blk) {
27096    let a = tfsG0(blk[0]);
27097    let b = tfsG1(blk[1]);
27098    blk[2] = rotw(blk[2] ^ a + b + tfsKey[4 * r + 8] & MAXINT, 31);
27099    blk[3] = rotw(blk[3], 1) ^ a + 2 * b + tfsKey[4 * r + 9] & MAXINT;
27100    a = tfsG0(blk[2]);
27101    b = tfsG1(blk[3]);
27102    blk[0] = rotw(blk[0] ^ a + b + tfsKey[4 * r + 10] & MAXINT, 31);
27103    blk[1] = rotw(blk[1], 1) ^ a + 2 * b + tfsKey[4 * r + 11] & MAXINT;
27104  }
27105
27106  function tfsIrnd(i, blk) {
27107    let a = tfsG0(blk[0]);
27108    let b = tfsG1(blk[1]);
27109    blk[2] = rotw(blk[2], 1) ^ a + b + tfsKey[4 * i + 10] & MAXINT;
27110    blk[3] = rotw(blk[3] ^ a + 2 * b + tfsKey[4 * i + 11] & MAXINT, 31);
27111    a = tfsG0(blk[2]);
27112    b = tfsG1(blk[3]);
27113    blk[0] = rotw(blk[0], 1) ^ a + b + tfsKey[4 * i + 8] & MAXINT;
27114    blk[1] = rotw(blk[1] ^ a + 2 * b + tfsKey[4 * i + 9] & MAXINT, 31);
27115  }
27116
27117  function tfsClose() {
27118    tfsKey = [];
27119    tfsM = [[], [], [], []];
27120  }
27121
27122  function tfsEncrypt(data, offset) {
27123    dataBytes = data;
27124    dataOffset = offset;
27125    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]];
27126    for (let j = 0; j < 8; j++) {
27127      tfsFrnd(j, blk);
27128    }
27129    setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);
27130    setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);
27131    setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);
27132    setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);
27133    dataOffset += 16;
27134    return dataBytes;
27135  }
27136
27137  function tfsDecrypt(data, offset) {
27138    dataBytes = data;
27139    dataOffset = offset;
27140    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]];
27141    for (let j = 7; j >= 0; j--) {
27142      tfsIrnd(j, blk);
27143    }
27144    setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);
27145    setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);
27146    setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);
27147    setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);
27148    dataOffset += 16;
27149  }
27150
27151  // added by Recurity Labs
27152
27153  function tfsFinal() {
27154    return dataBytes;
27155  }
27156
27157  return {
27158    name: "twofish",
27159    blocksize: 128 / 8,
27160    open: tfsInit,
27161    close: tfsClose,
27162    encrypt: tfsEncrypt,
27163    decrypt: tfsDecrypt,
27164    // added by Recurity Labs
27165    finalize: tfsFinal
27166  };
27167}
27168
27169// added by Recurity Labs
27170
27171function TF(key) {
27172  this.tf = createTwofish();
27173  this.tf.open(Array.from(key), 0);
27174
27175  this.encrypt = function (block) {
27176    return this.tf.encrypt(Array.from(block), 0);
27177  };
27178}
27179
27180TF.keySize = TF.prototype.keySize = 32;
27181TF.blockSize = TF.prototype.blockSize = 16;
27182
27183exports.default = TF;
27184
27185},{}],89:[function(require,module,exports){
27186'use strict';
27187
27188Object.defineProperty(exports, "__esModule", {
27189  value: true
27190});
27191
27192var _cbc = require('asmcrypto.js/dist_es5/aes/cbc');
27193
27194var _util = require('../util');
27195
27196var _util2 = _interopRequireDefault(_util);
27197
27198function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
27199
27200/**
27201 * @fileoverview This module implements AES-CMAC on top of
27202 * native AES-CBC using either the WebCrypto API or Node.js' crypto API.
27203 * @requires asmcrypto.js
27204 * @requires util
27205 * @module crypto/cmac
27206 */
27207
27208const webCrypto = _util2.default.getWebCrypto();
27209const nodeCrypto = _util2.default.getNodeCrypto();
27210const Buffer = _util2.default.getNodeBuffer();
27211
27212/**
27213 * This implementation of CMAC is based on the description of OMAC in
27214 * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that
27215 * document:
27216 *
27217 * We have made a small modification to the OMAC algorithm as it was
27218 * originally presented, changing one of its two constants.
27219 * Specifically, the constant 4 at line 85 was the constant 1/2 (the
27220 * multiplicative inverse of 2) in the original definition of OMAC [14].
27221 * The OMAC authors indicate that they will promulgate this modification
27222 * [15], which slightly simplifies implementations.
27223 */
27224
27225const blockLength = 16;
27226
27227/**
27228 * xor `padding` into the end of `data`. This function implements "the
27229 * operation xor→ [which] xors the shorter string into the end of longer
27230 * one". Since data is always as least as long as padding, we can
27231 * simplify the implementation.
27232 * @param {Uint8Array} data
27233 * @param {Uint8Array} padding
27234 */
27235function rightXorMut(data, padding) {
27236  const offset = data.length - blockLength;
27237  for (let i = 0; i < blockLength; i++) {
27238    data[i + offset] ^= padding[i];
27239  }
27240  return data;
27241}
27242
27243function pad(data, padding, padding2) {
27244  // if |M| in {n, 2n, 3n, ...}
27245  if (data.length && data.length % blockLength === 0) {
27246    // then return M xor→ B,
27247    return rightXorMut(data, padding);
27248  }
27249  // else return (M || 10^(n−1−(|M| mod n))) xor→ P
27250  const padded = new Uint8Array(data.length + (blockLength - data.length % blockLength));
27251  padded.set(data);
27252  padded[data.length] = 0b10000000;
27253  return rightXorMut(padded, padding2);
27254}
27255
27256const zeroBlock = new Uint8Array(blockLength);
27257
27258exports.default = async function CMAC(key) {
27259  const cbc = await CBC(key);
27260
27261  // L ← E_K(0^n); B ← 2L; P ← 4L
27262  const padding = _util2.default.double((await cbc(zeroBlock)));
27263  const padding2 = _util2.default.double(padding);
27264
27265  return async function (data) {
27266    // return CBC_K(pad(M; B, P))
27267    return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);
27268  };
27269};
27270
27271async function CBC(key) {
27272  if (_util2.default.getWebCrypto() && key.length !== 24) {
27273    // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
27274    key = await webCrypto.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);
27275    return async function (pt) {
27276      const ct = await webCrypto.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);
27277      return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);
27278    };
27279  }
27280  if (_util2.default.getNodeCrypto()) {
27281    // Node crypto library
27282    key = new Buffer(key);
27283    return async function (pt) {
27284      pt = new Buffer(pt);
27285      const en = new nodeCrypto.createCipheriv('aes-' + key.length * 8 + '-cbc', key, zeroBlock);
27286      const ct = en.update(pt);
27287      return new Uint8Array(ct);
27288    };
27289  }
27290  // asm.js fallback
27291  return async function (pt) {
27292    return _cbc.AES_CBC.encrypt(pt, key, false, zeroBlock);
27293  };
27294}
27295
27296},{"../util":153,"asmcrypto.js/dist_es5/aes/cbc":5}],90:[function(require,module,exports){
27297'use strict';
27298
27299Object.defineProperty(exports, "__esModule", {
27300  value: true
27301});
27302
27303var _bn = require('bn.js');
27304
27305var _bn2 = _interopRequireDefault(_bn);
27306
27307var _public_key = require('./public_key');
27308
27309var _public_key2 = _interopRequireDefault(_public_key);
27310
27311var _cipher = require('./cipher');
27312
27313var _cipher2 = _interopRequireDefault(_cipher);
27314
27315var _random = require('./random');
27316
27317var _random2 = _interopRequireDefault(_random);
27318
27319var _ecdh_symkey = require('../type/ecdh_symkey');
27320
27321var _ecdh_symkey2 = _interopRequireDefault(_ecdh_symkey);
27322
27323var _kdf_params = require('../type/kdf_params');
27324
27325var _kdf_params2 = _interopRequireDefault(_kdf_params);
27326
27327var _mpi = require('../type/mpi');
27328
27329var _mpi2 = _interopRequireDefault(_mpi);
27330
27331var _oid = require('../type/oid');
27332
27333var _oid2 = _interopRequireDefault(_oid);
27334
27335var _enums = require('../enums');
27336
27337var _enums2 = _interopRequireDefault(_enums);
27338
27339var _util = require('../util');
27340
27341var _util2 = _interopRequireDefault(_util);
27342
27343function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
27344
27345// GPG4Browsers - An OpenPGP implementation in javascript
27346// Copyright (C) 2011 Recurity Labs GmbH
27347//
27348// This library is free software; you can redistribute it and/or
27349// modify it under the terms of the GNU Lesser General Public
27350// License as published by the Free Software Foundation; either
27351// version 3.0 of the License, or (at your option) any later version.
27352//
27353// This library is distributed in the hope that it will be useful,
27354// but WITHOUT ANY WARRANTY; without even the implied warranty of
27355// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
27356// Lesser General Public License for more details.
27357//
27358// You should have received a copy of the GNU Lesser General Public
27359// License along with this library; if not, write to the Free Software
27360// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
27361
27362// The GPG4Browsers crypto interface
27363
27364/**
27365 * @fileoverview Provides functions for asymmetric encryption and decryption as
27366 * well as key generation and parameter handling for all public-key cryptosystems.
27367 * @requires bn.js
27368 * @requires crypto/public_key
27369 * @requires crypto/cipher
27370 * @requires crypto/random
27371 * @requires type/ecdh_symkey
27372 * @requires type/kdf_params
27373 * @requires type/mpi
27374 * @requires type/oid
27375 * @requires enums
27376 * @requires util
27377 * @module crypto/crypto
27378 */
27379
27380function constructParams(types, data) {
27381  return types.map(function (type, i) {
27382    if (data && data[i]) {
27383      return new type(data[i]);
27384    }
27385    return new type();
27386  });
27387}
27388
27389exports.default = {
27390  /**
27391   * Encrypts data using specified algorithm and public key parameters.
27392   * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.
27393   * @param {module:enums.publicKey}        algo        Public key algorithm
27394   * @param {Array<module:type/mpi|
27395                   module:type/oid|
27396                   module:type/kdf_params>} pub_params  Algorithm-specific public key parameters
27397   * @param {module:type/mpi}               data        Data to be encrypted as MPI
27398   * @param {String}                        fingerprint Recipient fingerprint
27399   * @returns {Array<module:type/mpi|
27400   *                 module:type/ecdh_symkey>}          encrypted session key parameters
27401   * @async
27402   */
27403  publicKeyEncrypt: async function publicKeyEncrypt(algo, pub_params, data, fingerprint) {
27404    const types = this.getEncSessionKeyParamTypes(algo);
27405    switch (algo) {
27406      case _enums2.default.publicKey.rsa_encrypt:
27407      case _enums2.default.publicKey.rsa_encrypt_sign:
27408        {
27409          const m = data.toBN();
27410          const n = pub_params[0].toBN();
27411          const e = pub_params[1].toBN();
27412          const res = await _public_key2.default.rsa.encrypt(m, n, e);
27413          return constructParams(types, [res]);
27414        }
27415      case _enums2.default.publicKey.elgamal:
27416        {
27417          const m = data.toBN();
27418          const p = pub_params[0].toBN();
27419          const g = pub_params[1].toBN();
27420          const y = pub_params[2].toBN();
27421          const res = await _public_key2.default.elgamal.encrypt(m, p, g, y);
27422          return constructParams(types, [res.c1, res.c2]);
27423        }
27424      case _enums2.default.publicKey.ecdh:
27425        {
27426          const oid = pub_params[0];
27427          const Q = pub_params[1].toUint8Array();
27428          const kdf_params = pub_params[2];
27429
27430          var _ref = await _public_key2.default.elliptic.ecdh.encrypt(oid, kdf_params.cipher, kdf_params.hash, data, Q, fingerprint);
27431
27432          const V = _ref.publicKey,
27433                C = _ref.wrappedKey;
27434
27435          return constructParams(types, [new _bn2.default(V), C]);
27436        }
27437      default:
27438        return [];
27439    }
27440  },
27441
27442  /**
27443   * Decrypts data using specified algorithm and private key parameters.
27444   * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.
27445   * @param {module:enums.publicKey}        algo        Public key algorithm
27446   * @param {Array<module:type/mpi|
27447                   module:type/oid|
27448                   module:type/kdf_params>} key_params  Algorithm-specific public, private key parameters
27449   * @param {Array<module:type/mpi|
27450                   module:type/ecdh_symkey>}
27451                                            data_params encrypted session key parameters
27452   * @param {String}                        fingerprint Recipient fingerprint
27453   * @returns {BN}                          A BN containing the decrypted data
27454   * @async
27455   */
27456  publicKeyDecrypt: async function publicKeyDecrypt(algo, key_params, data_params, fingerprint) {
27457    switch (algo) {
27458      case _enums2.default.publicKey.rsa_encrypt_sign:
27459      case _enums2.default.publicKey.rsa_encrypt:
27460        {
27461          const c = data_params[0].toBN();
27462          const n = key_params[0].toBN(); // n = pq
27463          const e = key_params[1].toBN();
27464          const d = key_params[2].toBN(); // de = 1 mod (p-1)(q-1)
27465          const p = key_params[3].toBN();
27466          const q = key_params[4].toBN();
27467          const u = key_params[5].toBN(); // q^-1 mod p
27468          return _public_key2.default.rsa.decrypt(c, n, e, d, p, q, u);
27469        }
27470      case _enums2.default.publicKey.elgamal:
27471        {
27472          const c1 = data_params[0].toBN();
27473          const c2 = data_params[1].toBN();
27474          const p = key_params[0].toBN();
27475          const x = key_params[3].toBN();
27476          return _public_key2.default.elgamal.decrypt(c1, c2, p, x);
27477        }
27478      case _enums2.default.publicKey.ecdh:
27479        {
27480          const oid = key_params[0];
27481          const kdf_params = key_params[2];
27482          const V = data_params[0].toUint8Array();
27483          const C = data_params[1].data;
27484          const d = key_params[3].toUint8Array();
27485          return _public_key2.default.elliptic.ecdh.decrypt(oid, kdf_params.cipher, kdf_params.hash, V, C, d, fingerprint);
27486        }
27487      default:
27488        throw new Error('Invalid public key encryption algorithm.');
27489    }
27490  },
27491
27492  /** Returns the types comprising the private key of an algorithm
27493   * @param {String} algo The public key algorithm
27494   * @returns {Array<String>} The array of types
27495   */
27496  getPrivKeyParamTypes: function getPrivKeyParamTypes(algo) {
27497    switch (algo) {
27498      //   Algorithm-Specific Fields for RSA secret keys:
27499      //       - multiprecision integer (MPI) of RSA secret exponent d.
27500      //       - MPI of RSA secret prime value p.
27501      //       - MPI of RSA secret prime value q (p < q).
27502      //       - MPI of u, the multiplicative inverse of p, mod q.
27503      case _enums2.default.publicKey.rsa_encrypt:
27504      case _enums2.default.publicKey.rsa_encrypt_sign:
27505      case _enums2.default.publicKey.rsa_sign:
27506        return [_mpi2.default, _mpi2.default, _mpi2.default, _mpi2.default];
27507      //   Algorithm-Specific Fields for Elgamal secret keys:
27508      //        - MPI of Elgamal secret exponent x.
27509      case _enums2.default.publicKey.elgamal:
27510        return [_mpi2.default];
27511      //   Algorithm-Specific Fields for DSA secret keys:
27512      //      - MPI of DSA secret exponent x.
27513      case _enums2.default.publicKey.dsa:
27514        return [_mpi2.default];
27515      //   Algorithm-Specific Fields for ECDSA or ECDH secret keys:
27516      //       - MPI of an integer representing the secret key.
27517      case _enums2.default.publicKey.ecdh:
27518      case _enums2.default.publicKey.ecdsa:
27519      case _enums2.default.publicKey.eddsa:
27520        return [_mpi2.default];
27521      default:
27522        throw new Error('Invalid public key encryption algorithm.');
27523    }
27524  },
27525
27526  /** Returns the types comprising the public key of an algorithm
27527   * @param {String} algo The public key algorithm
27528   * @returns {Array<String>} The array of types
27529   */
27530  getPubKeyParamTypes: function getPubKeyParamTypes(algo) {
27531    switch (algo) {
27532      //   Algorithm-Specific Fields for RSA public keys:
27533      //       - a multiprecision integer (MPI) of RSA public modulus n;
27534      //       - an MPI of RSA public encryption exponent e.
27535      case _enums2.default.publicKey.rsa_encrypt:
27536      case _enums2.default.publicKey.rsa_encrypt_sign:
27537      case _enums2.default.publicKey.rsa_sign:
27538        return [_mpi2.default, _mpi2.default];
27539      //   Algorithm-Specific Fields for Elgamal public keys:
27540      //       - MPI of Elgamal prime p;
27541      //       - MPI of Elgamal group generator g;
27542      //       - MPI of Elgamal public key value y (= g**x mod p where x  is secret).
27543      case _enums2.default.publicKey.elgamal:
27544        return [_mpi2.default, _mpi2.default, _mpi2.default];
27545      //   Algorithm-Specific Fields for DSA public keys:
27546      //       - MPI of DSA prime p;
27547      //       - MPI of DSA group order q (q is a prime divisor of p-1);
27548      //       - MPI of DSA group generator g;
27549      //       - MPI of DSA public-key value y (= g**x mod p where x  is secret).
27550      case _enums2.default.publicKey.dsa:
27551        return [_mpi2.default, _mpi2.default, _mpi2.default, _mpi2.default];
27552      //   Algorithm-Specific Fields for ECDSA/EdDSA public keys:
27553      //       - OID of curve;
27554      //       - MPI of EC point representing public key.
27555      case _enums2.default.publicKey.ecdsa:
27556      case _enums2.default.publicKey.eddsa:
27557        return [_oid2.default, _mpi2.default];
27558      //   Algorithm-Specific Fields for ECDH public keys:
27559      //       - OID of curve;
27560      //       - MPI of EC point representing public key.
27561      //       - KDF: variable-length field containing KDF parameters.
27562      case _enums2.default.publicKey.ecdh:
27563        return [_oid2.default, _mpi2.default, _kdf_params2.default];
27564      default:
27565        throw new Error('Invalid public key encryption algorithm.');
27566    }
27567  },
27568
27569  /** Returns the types comprising the encrypted session key of an algorithm
27570   * @param {String} algo The public key algorithm
27571   * @returns {Array<String>} The array of types
27572   */
27573  getEncSessionKeyParamTypes: function getEncSessionKeyParamTypes(algo) {
27574    switch (algo) {
27575      //   Algorithm-Specific Fields for RSA encrypted session keys:
27576      //       - MPI of RSA encrypted value m**e mod n.
27577      case _enums2.default.publicKey.rsa_encrypt:
27578      case _enums2.default.publicKey.rsa_encrypt_sign:
27579        return [_mpi2.default];
27580
27581      //   Algorithm-Specific Fields for Elgamal encrypted session keys:
27582      //       - MPI of Elgamal value g**k mod p
27583      //       - MPI of Elgamal value m * y**k mod p
27584      case _enums2.default.publicKey.elgamal:
27585        return [_mpi2.default, _mpi2.default];
27586      //   Algorithm-Specific Fields for ECDH encrypted session keys:
27587      //       - MPI containing the ephemeral key used to establish the shared secret
27588      //       - ECDH Symmetric Key
27589      case _enums2.default.publicKey.ecdh:
27590        return [_mpi2.default, _ecdh_symkey2.default];
27591      default:
27592        throw new Error('Invalid public key encryption algorithm.');
27593    }
27594  },
27595
27596  /** Generate algorithm-specific key parameters
27597   * @param {String}          algo The public key algorithm
27598   * @param {Integer}         bits Bit length for RSA keys
27599   * @param {module:type/oid} oid  Object identifier for ECC keys
27600   * @returns {Array}              The array of parameters
27601   * @async
27602   */
27603  generateParams: function generateParams(algo, bits, oid) {
27604    const types = [].concat(this.getPubKeyParamTypes(algo), this.getPrivKeyParamTypes(algo));
27605    switch (algo) {
27606      case _enums2.default.publicKey.rsa_encrypt:
27607      case _enums2.default.publicKey.rsa_encrypt_sign:
27608      case _enums2.default.publicKey.rsa_sign:
27609        {
27610          return _public_key2.default.rsa.generate(bits, "10001").then(function (keyObject) {
27611            return constructParams(types, [keyObject.n, keyObject.e, keyObject.d, keyObject.p, keyObject.q, keyObject.u]);
27612          });
27613        }
27614      case _enums2.default.publicKey.dsa:
27615      case _enums2.default.publicKey.elgamal:
27616        throw new Error('Unsupported algorithm for key generation.');
27617      case _enums2.default.publicKey.ecdsa:
27618      case _enums2.default.publicKey.eddsa:
27619        return _public_key2.default.elliptic.generate(oid).then(function (keyObject) {
27620          return constructParams(types, [keyObject.oid, keyObject.Q, keyObject.d]);
27621        });
27622      case _enums2.default.publicKey.ecdh:
27623        return _public_key2.default.elliptic.generate(oid).then(function (keyObject) {
27624          return constructParams(types, [keyObject.oid, keyObject.Q, [keyObject.hash, keyObject.cipher], keyObject.d]);
27625        });
27626      default:
27627        throw new Error('Invalid public key algorithm.');
27628    }
27629  },
27630
27631  /**
27632   * Generates a random byte prefix for the specified algorithm
27633   * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
27634   * @param {module:enums.symmetric} algo Symmetric encryption algorithm
27635   * @returns {Uint8Array}                Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.
27636   * @async
27637   */
27638  getPrefixRandom: async function getPrefixRandom(algo) {
27639    const prefixrandom = await _random2.default.getRandomBytes(_cipher2.default[algo].blockSize);
27640    const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);
27641    return _util2.default.concat([prefixrandom, repeat]);
27642  },
27643
27644  /**
27645   * Generating a session key for the specified symmetric algorithm
27646   * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
27647   * @param {module:enums.symmetric} algo Symmetric encryption algorithm
27648   * @returns {Uint8Array}                Random bytes as a string to be used as a key
27649   * @async
27650   */
27651  generateSessionKey: function generateSessionKey(algo) {
27652    return _random2.default.getRandomBytes(_cipher2.default[algo].keySize);
27653  },
27654
27655  constructParams: constructParams
27656};
27657
27658},{"../enums":114,"../type/ecdh_symkey":147,"../type/kdf_params":148,"../type/mpi":150,"../type/oid":151,"../util":153,"./cipher":87,"./public_key":107,"./random":110,"bn.js":17}],91:[function(require,module,exports){
27659'use strict';
27660
27661Object.defineProperty(exports, "__esModule", {
27662  value: true
27663});
27664
27665var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); // OpenPGP.js - An OpenPGP implementation in javascript
27666// Copyright (C) 2018 ProtonTech AG
27667//
27668// This library is free software; you can redistribute it and/or
27669// modify it under the terms of the GNU Lesser General Public
27670// License as published by the Free Software Foundation; either
27671// version 3.0 of the License, or (at your option) any later version.
27672//
27673// This library is distributed in the hope that it will be useful,
27674// but WITHOUT ANY WARRANTY; without even the implied warranty of
27675// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
27676// Lesser General Public License for more details.
27677//
27678// You should have received a copy of the GNU Lesser General Public
27679// License along with this library; if not, write to the Free Software
27680// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
27681
27682/**
27683 * @fileoverview This module implements AES-EAX en/decryption on top of
27684 * native AES-CTR using either the WebCrypto API or Node.js' crypto API.
27685 * @requires asmcrypto.js
27686 * @requires crypto/cmac
27687 * @requires util
27688 * @module crypto/eax
27689 */
27690
27691var _ctr = require('asmcrypto.js/dist_es5/aes/ctr');
27692
27693var _cmac = require('./cmac');
27694
27695var _cmac2 = _interopRequireDefault(_cmac);
27696
27697var _util = require('../util');
27698
27699var _util2 = _interopRequireDefault(_util);
27700
27701function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
27702
27703const webCrypto = _util2.default.getWebCrypto();
27704const nodeCrypto = _util2.default.getNodeCrypto();
27705const Buffer = _util2.default.getNodeBuffer();
27706
27707const blockLength = 16;
27708const ivLength = blockLength;
27709const tagLength = blockLength;
27710
27711const zero = new Uint8Array(blockLength);
27712const one = new Uint8Array(blockLength);one[blockLength - 1] = 1;
27713const two = new Uint8Array(blockLength);two[blockLength - 1] = 2;
27714
27715async function OMAC(key) {
27716  const cmac = await (0, _cmac2.default)(key);
27717  return function (t, message) {
27718    return cmac(_util2.default.concatUint8Array([t, message]));
27719  };
27720}
27721
27722async function CTR(key) {
27723  if (_util2.default.getWebCrypto() && key.length !== 24 && // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
27724  navigator.userAgent.indexOf('Edge') === -1) {
27725    key = await webCrypto.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);
27726    return async function (pt, iv) {
27727      const ct = await webCrypto.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength * 8 }, key, pt);
27728      return new Uint8Array(ct);
27729    };
27730  }
27731  if (_util2.default.getNodeCrypto()) {
27732    // Node crypto library
27733    key = new Buffer(key);
27734    return async function (pt, iv) {
27735      pt = new Buffer(pt);
27736      iv = new Buffer(iv);
27737      const en = new nodeCrypto.createCipheriv('aes-' + key.length * 8 + '-ctr', key, iv);
27738      const ct = Buffer.concat([en.update(pt), en.final()]);
27739      return new Uint8Array(ct);
27740    };
27741  }
27742  // asm.js fallback
27743  return async function (pt, iv) {
27744    return _ctr.AES_CTR.encrypt(pt, key, iv);
27745  };
27746}
27747
27748/**
27749 * Class to en/decrypt using EAX mode.
27750 * @param  {String}     cipher      The symmetric cipher algorithm to use e.g. 'aes128'
27751 * @param  {Uint8Array} key         The encryption key
27752 */
27753async function EAX(cipher, key) {
27754  if (cipher.substr(0, 3) !== 'aes') {
27755    throw new Error('EAX mode supports only AES cipher');
27756  }
27757
27758  var _ref = await Promise.all([OMAC(key), CTR(key)]),
27759      _ref2 = _slicedToArray(_ref, 2);
27760
27761  const omac = _ref2[0],
27762        ctr = _ref2[1];
27763
27764
27765  return {
27766    /**
27767     * Encrypt plaintext input.
27768     * @param  {Uint8Array} plaintext   The cleartext input to be encrypted
27769     * @param  {Uint8Array} nonce       The nonce (16 bytes)
27770     * @param  {Uint8Array} adata       Associated data to sign
27771     * @returns {Promise<Uint8Array>}    The ciphertext output
27772     */
27773    encrypt: async function encrypt(plaintext, nonce, adata) {
27774      var _ref3 = await Promise.all([omac(zero, nonce), omac(one, adata)]),
27775          _ref4 = _slicedToArray(_ref3, 2);
27776
27777      const omacNonce = _ref4[0],
27778            omacAdata = _ref4[1];
27779
27780      const ciphered = await ctr(plaintext, omacNonce);
27781      const omacCiphered = await omac(two, ciphered);
27782      const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
27783      for (let i = 0; i < tagLength; i++) {
27784        tag[i] ^= omacAdata[i] ^ omacNonce[i];
27785      }
27786      return _util2.default.concatUint8Array([ciphered, tag]);
27787    },
27788
27789    /**
27790     * Decrypt ciphertext input.
27791     * @param  {Uint8Array} ciphertext   The ciphertext input to be decrypted
27792     * @param  {Uint8Array} nonce        The nonce (16 bytes)
27793     * @param  {Uint8Array} adata        Associated data to verify
27794     * @returns {Promise<Uint8Array>}     The plaintext output
27795     */
27796    decrypt: async function decrypt(ciphertext, nonce, adata) {
27797      if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');
27798      const ciphered = ciphertext.subarray(0, -tagLength);
27799      const ctTag = ciphertext.subarray(-tagLength);
27800
27801      var _ref5 = await Promise.all([omac(zero, nonce), omac(one, adata), omac(two, ciphered)]),
27802          _ref6 = _slicedToArray(_ref5, 3);
27803
27804      const omacNonce = _ref6[0],
27805            omacAdata = _ref6[1],
27806            omacCiphered = _ref6[2];
27807
27808      const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
27809      for (let i = 0; i < tagLength; i++) {
27810        tag[i] ^= omacAdata[i] ^ omacNonce[i];
27811      }
27812      if (!_util2.default.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');
27813      const plaintext = await ctr(ciphered, omacNonce);
27814      return plaintext;
27815    }
27816  };
27817}
27818
27819/**
27820 * 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}.
27821 * @param  {Uint8Array} iv           The initialization vector (16 bytes)
27822 * @param  {Uint8Array} chunkIndex   The chunk index (8 bytes)
27823 */
27824EAX.getNonce = function (iv, chunkIndex) {
27825  const nonce = iv.slice();
27826  for (let i = 0; i < chunkIndex.length; i++) {
27827    nonce[8 + i] ^= chunkIndex[i];
27828  }
27829  return nonce;
27830};
27831
27832EAX.blockLength = blockLength;
27833EAX.ivLength = ivLength;
27834EAX.tagLength = tagLength;
27835
27836exports.default = EAX;
27837
27838},{"../util":153,"./cmac":89,"asmcrypto.js/dist_es5/aes/ctr":7}],92:[function(require,module,exports){
27839'use strict';
27840
27841Object.defineProperty(exports, "__esModule", {
27842  value: true
27843});
27844
27845var _gcm = require('asmcrypto.js/dist_es5/aes/gcm');
27846
27847var _util = require('../util');
27848
27849var _util2 = _interopRequireDefault(_util);
27850
27851function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
27852
27853// OpenPGP.js - An OpenPGP implementation in javascript
27854// Copyright (C) 2016 Tankred Hase
27855//
27856// This library is free software; you can redistribute it and/or
27857// modify it under the terms of the GNU Lesser General Public
27858// License as published by the Free Software Foundation; either
27859// version 3.0 of the License, or (at your option) any later version.
27860//
27861// This library is distributed in the hope that it will be useful,
27862// but WITHOUT ANY WARRANTY; without even the implied warranty of
27863// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
27864// Lesser General Public License for more details.
27865//
27866// You should have received a copy of the GNU Lesser General Public
27867// License along with this library; if not, write to the Free Software
27868// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
27869
27870/**
27871 * @fileoverview This module wraps native AES-GCM en/decryption for both
27872 * the WebCrypto api as well as node.js' crypto api.
27873 * @requires asmcrypto.js
27874 * @requires util
27875 * @module crypto/gcm
27876 */
27877
27878const webCrypto = _util2.default.getWebCrypto(); // no GCM support in IE11, Safari 9
27879const nodeCrypto = _util2.default.getNodeCrypto();
27880const Buffer = _util2.default.getNodeBuffer();
27881
27882const blockLength = 16;
27883const ivLength = 12; // size of the IV in bytes
27884const tagLength = 16; // size of the tag in bytes
27885const ALGO = 'AES-GCM';
27886
27887/**
27888 * Class to en/decrypt using GCM mode.
27889 * @param  {String}     cipher      The symmetric cipher algorithm to use e.g. 'aes128'
27890 * @param  {Uint8Array} key         The encryption key
27891 */
27892async function GCM(cipher, key) {
27893  if (cipher.substr(0, 3) !== 'aes') {
27894    throw new Error('GCM mode supports only AES cipher');
27895  }
27896
27897  if (_util2.default.getWebCrypto() && key.length !== 24) {
27898    // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
27899    const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);
27900
27901    return {
27902      encrypt: async function encrypt(pt, iv, adata = new Uint8Array()) {
27903        if (!pt.length ||
27904        // iOS does not support GCM-en/decrypting empty messages
27905        // Also, synchronous en/decryption might be faster in this case.
27906        !adata.length && navigator.userAgent.indexOf('Edge') !== -1
27907        // Edge does not support GCM-en/decrypting without ADATA
27908        ) {
27909            return _gcm.AES_GCM.encrypt(pt, key, iv, adata);
27910          }
27911        const ct = await webCrypto.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);
27912        return new Uint8Array(ct);
27913      },
27914
27915      decrypt: async function decrypt(ct, iv, adata = new Uint8Array()) {
27916        if (ct.length === tagLength ||
27917        // iOS does not support GCM-en/decrypting empty messages
27918        // Also, synchronous en/decryption might be faster in this case.
27919        !adata.length && navigator.userAgent.indexOf('Edge') !== -1
27920        // Edge does not support GCM-en/decrypting without ADATA
27921        ) {
27922            return _gcm.AES_GCM.decrypt(ct, key, iv, adata);
27923          }
27924        const pt = await webCrypto.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);
27925        return new Uint8Array(pt);
27926      }
27927    };
27928  }
27929
27930  if (_util2.default.getNodeCrypto()) {
27931    // Node crypto library
27932    key = new Buffer(key);
27933
27934    return {
27935      encrypt: async function encrypt(pt, iv, adata = new Uint8Array()) {
27936        pt = new Buffer(pt);
27937        iv = new Buffer(iv);
27938        adata = new Buffer(adata);
27939        const en = new nodeCrypto.createCipheriv('aes-' + key.length * 8 + '-gcm', key, iv);
27940        en.setAAD(adata);
27941        const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext
27942        return new Uint8Array(ct);
27943      },
27944
27945      decrypt: async function decrypt(ct, iv, adata = new Uint8Array()) {
27946        ct = new Buffer(ct);
27947        iv = new Buffer(iv);
27948        adata = new Buffer(adata);
27949        const de = new nodeCrypto.createDecipheriv('aes-' + key.length * 8 + '-gcm', key, iv);
27950        de.setAAD(adata);
27951        de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext
27952        const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]);
27953        return new Uint8Array(pt);
27954      }
27955    };
27956  }
27957
27958  return {
27959    encrypt: async function encrypt(pt, iv, adata) {
27960      return _gcm.AES_GCM.encrypt(pt, key, iv, adata);
27961    },
27962
27963    decrypt: async function decrypt(ct, iv, adata) {
27964      return _gcm.AES_GCM.decrypt(ct, key, iv, adata);
27965    }
27966  };
27967}
27968
27969/**
27970 * Get GCM nonce. Note: this operation is not defined by the standard.
27971 * A future version of the standard may define GCM mode differently,
27972 * hopefully under a different ID (we use Private/Experimental algorithm
27973 * ID 100) so that we can maintain backwards compatibility.
27974 * @param  {Uint8Array} iv           The initialization vector (12 bytes)
27975 * @param  {Uint8Array} chunkIndex   The chunk index (8 bytes)
27976 */
27977GCM.getNonce = function (iv, chunkIndex) {
27978  const nonce = iv.slice();
27979  for (let i = 0; i < chunkIndex.length; i++) {
27980    nonce[4 + i] ^= chunkIndex[i];
27981  }
27982  return nonce;
27983};
27984
27985GCM.blockLength = blockLength;
27986GCM.ivLength = ivLength;
27987GCM.tagLength = tagLength;
27988
27989exports.default = GCM;
27990
27991},{"../util":153,"asmcrypto.js/dist_es5/aes/gcm":9}],93:[function(require,module,exports){
27992'use strict';
27993
27994Object.defineProperty(exports, "__esModule", {
27995  value: true
27996});
27997
27998var _sha = require('asmcrypto.js/dist_es5/hash/sha1/sha1');
27999
28000var _sha2 = require('asmcrypto.js/dist_es5/hash/sha256/sha256');
28001
28002var _ = require('hash.js/lib/hash/sha/224');
28003
28004var _2 = _interopRequireDefault(_);
28005
28006var _3 = require('hash.js/lib/hash/sha/384');
28007
28008var _4 = _interopRequireDefault(_3);
28009
28010var _5 = require('hash.js/lib/hash/sha/512');
28011
28012var _6 = _interopRequireDefault(_5);
28013
28014var _ripemd = require('hash.js/lib/hash/ripemd');
28015
28016var _webStreamTools = require('web-stream-tools');
28017
28018var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
28019
28020var _md = require('./md5');
28021
28022var _md2 = _interopRequireDefault(_md);
28023
28024var _config = require('../../config');
28025
28026var _config2 = _interopRequireDefault(_config);
28027
28028var _util = require('../../util');
28029
28030var _util2 = _interopRequireDefault(_util);
28031
28032function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
28033
28034/**
28035 * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.
28036 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
28037 * @see {@link https://github.com/indutny/hash.js|hash.js}
28038 * @requires asmcrypto.js
28039 * @requires hash.js
28040 * @requires web-stream-tools
28041 * @requires crypto/hash/md5
28042 * @requires config
28043 * @requires util
28044 * @module crypto/hash
28045 */
28046
28047const webCrypto = _util2.default.getWebCrypto();
28048const nodeCrypto = _util2.default.getNodeCrypto();
28049const Buffer = _util2.default.getNodeBuffer();
28050
28051function node_hash(type) {
28052  return async function (data) {
28053    const shasum = nodeCrypto.createHash(type);
28054    return _webStreamTools2.default.transform(data, value => {
28055      shasum.update(new Buffer(value));
28056    }, () => new Uint8Array(shasum.digest()));
28057  };
28058}
28059
28060function hashjs_hash(hash, webCryptoHash) {
28061  return async function (data) {
28062    if (!_util2.default.isStream(data) && webCrypto && webCryptoHash && data.length >= _config2.default.min_bytes_for_web_crypto) {
28063      return new Uint8Array((await webCrypto.digest(webCryptoHash, data)));
28064    }
28065    const hashInstance = hash();
28066    return _webStreamTools2.default.transform(data, value => {
28067      hashInstance.update(value);
28068    }, () => new Uint8Array(hashInstance.digest()));
28069  };
28070}
28071
28072function asmcrypto_hash(hash, webCryptoHash) {
28073  return async function (data) {
28074    if (_util2.default.isStream(data)) {
28075      const hashInstance = new hash();
28076      return _webStreamTools2.default.transform(data, value => {
28077        hashInstance.process(value);
28078      }, () => hashInstance.finish().result);
28079    } else if (webCrypto && webCryptoHash && data.length >= _config2.default.min_bytes_for_web_crypto) {
28080      return new Uint8Array((await webCrypto.digest(webCryptoHash, data)));
28081    } else {
28082      return hash.bytes(data);
28083    }
28084  };
28085}
28086
28087let hash_fns;
28088if (nodeCrypto) {
28089  // Use Node native crypto for all hash functions
28090  hash_fns = {
28091    md5: node_hash('md5'),
28092    sha1: node_hash('sha1'),
28093    sha224: node_hash('sha224'),
28094    sha256: node_hash('sha256'),
28095    sha384: node_hash('sha384'),
28096    sha512: node_hash('sha512'),
28097    ripemd: node_hash('ripemd160')
28098  };
28099} else {
28100  // Use JS fallbacks
28101  hash_fns = {
28102    md5: _md2.default,
28103    sha1: asmcrypto_hash(_sha.Sha1, navigator.userAgent.indexOf('Edge') === -1 && 'SHA-1'),
28104    sha224: hashjs_hash(_2.default),
28105    sha256: asmcrypto_hash(_sha2.Sha256, 'SHA-256'),
28106    sha384: hashjs_hash(_4.default, 'SHA-384'),
28107    sha512: hashjs_hash(_6.default, 'SHA-512'), // asmcrypto sha512 is huge.
28108    ripemd: hashjs_hash(_ripemd.ripemd160)
28109  };
28110}
28111
28112exports.default = {
28113
28114  /** @see module:md5 */
28115  md5: hash_fns.md5,
28116  /** @see asmCrypto */
28117  sha1: hash_fns.sha1,
28118  /** @see hash.js */
28119  sha224: hash_fns.sha224,
28120  /** @see asmCrypto */
28121  sha256: hash_fns.sha256,
28122  /** @see hash.js */
28123  sha384: hash_fns.sha384,
28124  /** @see asmCrypto */
28125  sha512: hash_fns.sha512,
28126  /** @see hash.js */
28127  ripemd: hash_fns.ripemd,
28128
28129  /**
28130   * Create a hash on the specified data using the specified algorithm
28131   * @param {module:enums.hash} algo Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
28132   * @param {Uint8Array} data Data to be hashed
28133   * @returns {Promise<Uint8Array>} hash value
28134   */
28135  digest: function digest(algo, data) {
28136    switch (algo) {
28137      case 1:
28138        // - MD5 [HAC]
28139        return this.md5(data);
28140      case 2:
28141        // - SHA-1 [FIPS180]
28142        return this.sha1(data);
28143      case 3:
28144        // - RIPE-MD/160 [HAC]
28145        return this.ripemd(data);
28146      case 8:
28147        // - SHA256 [FIPS180]
28148        return this.sha256(data);
28149      case 9:
28150        // - SHA384 [FIPS180]
28151        return this.sha384(data);
28152      case 10:
28153        // - SHA512 [FIPS180]
28154        return this.sha512(data);
28155      case 11:
28156        // - SHA224 [FIPS180]
28157        return this.sha224(data);
28158      default:
28159        throw new Error('Invalid hash function.');
28160    }
28161  },
28162
28163  /**
28164   * Returns the hash size in bytes of the specified hash algorithm type
28165   * @param {module:enums.hash} algo Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
28166   * @returns {Integer} Size in bytes of the resulting hash
28167   */
28168  getHashByteLength: function getHashByteLength(algo) {
28169    switch (algo) {
28170      case 1:
28171        // - MD5 [HAC]
28172        return 16;
28173      case 2: // - SHA-1 [FIPS180]
28174      case 3:
28175        // - RIPE-MD/160 [HAC]
28176        return 20;
28177      case 8:
28178        // - SHA256 [FIPS180]
28179        return 32;
28180      case 9:
28181        // - SHA384 [FIPS180]
28182        return 48;
28183      case 10:
28184        // - SHA512 [FIPS180]
28185        return 64;
28186      case 11:
28187        // - SHA224 [FIPS180]
28188        return 28;
28189      default:
28190        throw new Error('Invalid hash algorithm.');
28191    }
28192  }
28193};
28194
28195},{"../../config":80,"../../util":153,"./md5":94,"asmcrypto.js/dist_es5/hash/sha1/sha1":12,"asmcrypto.js/dist_es5/hash/sha256/sha256":14,"hash.js/lib/hash/ripemd":38,"hash.js/lib/hash/sha/224":41,"hash.js/lib/hash/sha/384":43,"hash.js/lib/hash/sha/512":44,"web-stream-tools":76}],94:[function(require,module,exports){
28196'use strict';
28197
28198Object.defineProperty(exports, "__esModule", {
28199  value: true
28200});
28201
28202var _util = require('../../util');
28203
28204var _util2 = _interopRequireDefault(_util);
28205
28206function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
28207
28208// MD5 Digest
28209async function md5(entree) {
28210  const digest = md51(_util2.default.Uint8Array_to_str(entree));
28211  return _util2.default.hex_to_Uint8Array(hex(digest));
28212} /**
28213   * A fast MD5 JavaScript implementation
28214   * Copyright (c) 2012 Joseph Myers
28215   * http://www.myersdaily.org/joseph/javascript/md5-text.html
28216   *
28217   * Permission to use, copy, modify, and distribute this software
28218   * and its documentation for any purposes and without
28219   * fee is hereby granted provided that this copyright notice
28220   * appears in all copies.
28221   *
28222   * Of course, this soft is provided "as is" without express or implied
28223   * warranty of any kind.
28224   */
28225
28226/**
28227 * @requires util
28228 */
28229
28230function md5cycle(x, k) {
28231  let a = x[0];
28232  let b = x[1];
28233  let c = x[2];
28234  let d = x[3];
28235
28236  a = ff(a, b, c, d, k[0], 7, -680876936);
28237  d = ff(d, a, b, c, k[1], 12, -389564586);
28238  c = ff(c, d, a, b, k[2], 17, 606105819);
28239  b = ff(b, c, d, a, k[3], 22, -1044525330);
28240  a = ff(a, b, c, d, k[4], 7, -176418897);
28241  d = ff(d, a, b, c, k[5], 12, 1200080426);
28242  c = ff(c, d, a, b, k[6], 17, -1473231341);
28243  b = ff(b, c, d, a, k[7], 22, -45705983);
28244  a = ff(a, b, c, d, k[8], 7, 1770035416);
28245  d = ff(d, a, b, c, k[9], 12, -1958414417);
28246  c = ff(c, d, a, b, k[10], 17, -42063);
28247  b = ff(b, c, d, a, k[11], 22, -1990404162);
28248  a = ff(a, b, c, d, k[12], 7, 1804603682);
28249  d = ff(d, a, b, c, k[13], 12, -40341101);
28250  c = ff(c, d, a, b, k[14], 17, -1502002290);
28251  b = ff(b, c, d, a, k[15], 22, 1236535329);
28252
28253  a = gg(a, b, c, d, k[1], 5, -165796510);
28254  d = gg(d, a, b, c, k[6], 9, -1069501632);
28255  c = gg(c, d, a, b, k[11], 14, 643717713);
28256  b = gg(b, c, d, a, k[0], 20, -373897302);
28257  a = gg(a, b, c, d, k[5], 5, -701558691);
28258  d = gg(d, a, b, c, k[10], 9, 38016083);
28259  c = gg(c, d, a, b, k[15], 14, -660478335);
28260  b = gg(b, c, d, a, k[4], 20, -405537848);
28261  a = gg(a, b, c, d, k[9], 5, 568446438);
28262  d = gg(d, a, b, c, k[14], 9, -1019803690);
28263  c = gg(c, d, a, b, k[3], 14, -187363961);
28264  b = gg(b, c, d, a, k[8], 20, 1163531501);
28265  a = gg(a, b, c, d, k[13], 5, -1444681467);
28266  d = gg(d, a, b, c, k[2], 9, -51403784);
28267  c = gg(c, d, a, b, k[7], 14, 1735328473);
28268  b = gg(b, c, d, a, k[12], 20, -1926607734);
28269
28270  a = hh(a, b, c, d, k[5], 4, -378558);
28271  d = hh(d, a, b, c, k[8], 11, -2022574463);
28272  c = hh(c, d, a, b, k[11], 16, 1839030562);
28273  b = hh(b, c, d, a, k[14], 23, -35309556);
28274  a = hh(a, b, c, d, k[1], 4, -1530992060);
28275  d = hh(d, a, b, c, k[4], 11, 1272893353);
28276  c = hh(c, d, a, b, k[7], 16, -155497632);
28277  b = hh(b, c, d, a, k[10], 23, -1094730640);
28278  a = hh(a, b, c, d, k[13], 4, 681279174);
28279  d = hh(d, a, b, c, k[0], 11, -358537222);
28280  c = hh(c, d, a, b, k[3], 16, -722521979);
28281  b = hh(b, c, d, a, k[6], 23, 76029189);
28282  a = hh(a, b, c, d, k[9], 4, -640364487);
28283  d = hh(d, a, b, c, k[12], 11, -421815835);
28284  c = hh(c, d, a, b, k[15], 16, 530742520);
28285  b = hh(b, c, d, a, k[2], 23, -995338651);
28286
28287  a = ii(a, b, c, d, k[0], 6, -198630844);
28288  d = ii(d, a, b, c, k[7], 10, 1126891415);
28289  c = ii(c, d, a, b, k[14], 15, -1416354905);
28290  b = ii(b, c, d, a, k[5], 21, -57434055);
28291  a = ii(a, b, c, d, k[12], 6, 1700485571);
28292  d = ii(d, a, b, c, k[3], 10, -1894986606);
28293  c = ii(c, d, a, b, k[10], 15, -1051523);
28294  b = ii(b, c, d, a, k[1], 21, -2054922799);
28295  a = ii(a, b, c, d, k[8], 6, 1873313359);
28296  d = ii(d, a, b, c, k[15], 10, -30611744);
28297  c = ii(c, d, a, b, k[6], 15, -1560198380);
28298  b = ii(b, c, d, a, k[13], 21, 1309151649);
28299  a = ii(a, b, c, d, k[4], 6, -145523070);
28300  d = ii(d, a, b, c, k[11], 10, -1120210379);
28301  c = ii(c, d, a, b, k[2], 15, 718787259);
28302  b = ii(b, c, d, a, k[9], 21, -343485551);
28303
28304  x[0] = add32(a, x[0]);
28305  x[1] = add32(b, x[1]);
28306  x[2] = add32(c, x[2]);
28307  x[3] = add32(d, x[3]);
28308}
28309
28310function cmn(q, a, b, x, s, t) {
28311  a = add32(add32(a, q), add32(x, t));
28312  return add32(a << s | a >>> 32 - s, b);
28313}
28314
28315function ff(a, b, c, d, x, s, t) {
28316  return cmn(b & c | ~b & d, a, b, x, s, t);
28317}
28318
28319function gg(a, b, c, d, x, s, t) {
28320  return cmn(b & d | c & ~d, a, b, x, s, t);
28321}
28322
28323function hh(a, b, c, d, x, s, t) {
28324  return cmn(b ^ c ^ d, a, b, x, s, t);
28325}
28326
28327function ii(a, b, c, d, x, s, t) {
28328  return cmn(c ^ (b | ~d), a, b, x, s, t);
28329}
28330
28331function md51(s) {
28332  const n = s.length;
28333  const state = [1732584193, -271733879, -1732584194, 271733878];
28334  let i;
28335  for (i = 64; i <= s.length; i += 64) {
28336    md5cycle(state, md5blk(s.substring(i - 64, i)));
28337  }
28338  s = s.substring(i - 64);
28339  const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
28340  for (i = 0; i < s.length; i++) {
28341    tail[i >> 2] |= s.charCodeAt(i) << (i % 4 << 3);
28342  }
28343  tail[i >> 2] |= 0x80 << (i % 4 << 3);
28344  if (i > 55) {
28345    md5cycle(state, tail);
28346    for (i = 0; i < 16; i++) {
28347      tail[i] = 0;
28348    }
28349  }
28350  tail[14] = n * 8;
28351  md5cycle(state, tail);
28352  return state;
28353}
28354
28355/* there needs to be support for Unicode here,
28356 * unless we pretend that we can redefine the MD-5
28357 * algorithm for multi-byte characters (perhaps
28358 * by adding every four 16-bit characters and
28359 * shortening the sum to 32 bits). Otherwise
28360 * I suggest performing MD-5 as if every character
28361 * was two bytes--e.g., 0040 0025 = @%--but then
28362 * how will an ordinary MD-5 sum be matched?
28363 * There is no way to standardize text to something
28364 * like UTF-8 before transformation; speed cost is
28365 * utterly prohibitive. The JavaScript standard
28366 * itself needs to look at this: it should start
28367 * providing access to strings as preformed UTF-8
28368 * 8-bit unsigned value arrays.
28369 */
28370function md5blk(s) {
28371  /* I figured global was faster.   */
28372  const md5blks = [];
28373  let i; /* Andy King said do it this way. */
28374  for (i = 0; i < 64; i += 4) {
28375    md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
28376  }
28377  return md5blks;
28378}
28379
28380const hex_chr = '0123456789abcdef'.split('');
28381
28382function rhex(n) {
28383  let s = '';
28384  let j = 0;
28385  for (; j < 4; j++) {
28386    s += hex_chr[n >> j * 8 + 4 & 0x0F] + hex_chr[n >> j * 8 & 0x0F];
28387  }
28388  return s;
28389}
28390
28391function hex(x) {
28392  for (let i = 0; i < x.length; i++) {
28393    x[i] = rhex(x[i]);
28394  }
28395  return x.join('');
28396}
28397
28398/* this function is much faster,
28399so if possible we use it. Some IEs
28400are the only ones I know of that
28401need the idiotic second function,
28402generated by an if clause.  */
28403
28404function add32(a, b) {
28405  return a + b & 0xFFFFFFFF;
28406}
28407
28408exports.default = md5;
28409
28410},{"../../util":153}],95:[function(require,module,exports){
28411'use strict';
28412
28413Object.defineProperty(exports, "__esModule", {
28414  value: true
28415});
28416
28417var _cipher = require('./cipher');
28418
28419var _cipher2 = _interopRequireDefault(_cipher);
28420
28421var _hash = require('./hash');
28422
28423var _hash2 = _interopRequireDefault(_hash);
28424
28425var _cfb = require('./cfb');
28426
28427var _cfb2 = _interopRequireDefault(_cfb);
28428
28429var _gcm = require('./gcm');
28430
28431var _gcm2 = _interopRequireDefault(_gcm);
28432
28433var _eax = require('./eax');
28434
28435var _eax2 = _interopRequireDefault(_eax);
28436
28437var _ocb = require('./ocb');
28438
28439var _ocb2 = _interopRequireDefault(_ocb);
28440
28441var _public_key = require('./public_key');
28442
28443var _public_key2 = _interopRequireDefault(_public_key);
28444
28445var _signature = require('./signature');
28446
28447var _signature2 = _interopRequireDefault(_signature);
28448
28449var _random = require('./random');
28450
28451var _random2 = _interopRequireDefault(_random);
28452
28453var _pkcs = require('./pkcs1');
28454
28455var _pkcs2 = _interopRequireDefault(_pkcs);
28456
28457var _pkcs3 = require('./pkcs5');
28458
28459var _pkcs4 = _interopRequireDefault(_pkcs3);
28460
28461var _crypto = require('./crypto');
28462
28463var _crypto2 = _interopRequireDefault(_crypto);
28464
28465var _aes_kw = require('./aes_kw');
28466
28467var _aes_kw2 = _interopRequireDefault(_aes_kw);
28468
28469function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
28470
28471// TODO move cfb and gcm to cipher
28472const mod = {
28473  /** @see module:crypto/cipher */
28474  cipher: _cipher2.default,
28475  /** @see module:crypto/hash */
28476  hash: _hash2.default,
28477  /** @see module:crypto/cfb */
28478  cfb: _cfb2.default,
28479  /** @see module:crypto/gcm */
28480  gcm: _gcm2.default,
28481  experimental_gcm: _gcm2.default,
28482  /** @see module:crypto/eax */
28483  eax: _eax2.default,
28484  /** @see module:crypto/ocb */
28485  ocb: _ocb2.default,
28486  /** @see module:crypto/public_key */
28487  publicKey: _public_key2.default,
28488  /** @see module:crypto/signature */
28489  signature: _signature2.default,
28490  /** @see module:crypto/random */
28491  random: _random2.default,
28492  /** @see module:crypto/pkcs1 */
28493  pkcs1: _pkcs2.default,
28494  /** @see module:crypto/pkcs5 */
28495  pkcs5: _pkcs4.default,
28496  /** @see module:crypto/aes_kw */
28497  aes_kw: _aes_kw2.default
28498}; /**
28499    * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js
28500    * @see module:crypto/crypto
28501    * @see module:crypto/signature
28502    * @see module:crypto/public_key
28503    * @see module:crypto/cipher
28504    * @see module:crypto/random
28505    * @see module:crypto/hash
28506    * @module crypto
28507    */
28508
28509Object.assign(mod, _crypto2.default);
28510
28511exports.default = mod;
28512
28513},{"./aes_kw":81,"./cfb":82,"./cipher":87,"./crypto":90,"./eax":91,"./gcm":92,"./hash":93,"./ocb":96,"./pkcs1":97,"./pkcs5":98,"./public_key":107,"./random":110,"./signature":111}],96:[function(require,module,exports){
28514'use strict';
28515
28516Object.defineProperty(exports, "__esModule", {
28517  value: true
28518});
28519
28520var _cipher = require('./cipher');
28521
28522var _cipher2 = _interopRequireDefault(_cipher);
28523
28524var _util = require('../util');
28525
28526var _util2 = _interopRequireDefault(_util);
28527
28528function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
28529
28530// OpenPGP.js - An OpenPGP implementation in javascript
28531// Copyright (C) 2018 ProtonTech AG
28532//
28533// This library is free software; you can redistribute it and/or
28534// modify it under the terms of the GNU Lesser General Public
28535// License as published by the Free Software Foundation; either
28536// version 3.0 of the License, or (at your option) any later version.
28537//
28538// This library is distributed in the hope that it will be useful,
28539// but WITHOUT ANY WARRANTY; without even the implied warranty of
28540// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
28541// Lesser General Public License for more details.
28542//
28543// You should have received a copy of the GNU Lesser General Public
28544// License along with this library; if not, write to the Free Software
28545// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
28546
28547/**
28548 * @fileoverview This module implements AES-OCB en/decryption.
28549 * @requires crypto/cipher
28550 * @requires util
28551 * @module crypto/ocb
28552 */
28553
28554const blockLength = 16;
28555const ivLength = 15;
28556
28557// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:
28558// While OCB [RFC7253] allows the authentication tag length to be of any
28559// number up to 128 bits long, this document requires a fixed
28560// authentication tag length of 128 bits (16 octets) for simplicity.
28561const tagLength = 16;
28562
28563function ntz(n) {
28564  let ntz = 0;
28565  for (let i = 1; (n & i) === 0; i <<= 1) {
28566    ntz++;
28567  }
28568  return ntz;
28569}
28570
28571function xorMut(S, T) {
28572  for (let i = 0; i < S.length; i++) {
28573    S[i] ^= T[i];
28574  }
28575  return S;
28576}
28577
28578function xor(S, T) {
28579  return xorMut(S.slice(), T);
28580}
28581
28582const zeroBlock = new Uint8Array(blockLength);
28583const one = new Uint8Array([1]);
28584
28585/**
28586 * Class to en/decrypt using OCB mode.
28587 * @param  {String}     cipher      The symmetric cipher algorithm to use e.g. 'aes128'
28588 * @param  {Uint8Array} key         The encryption key
28589 */
28590async function OCB(cipher, key) {
28591
28592  let maxNtz = 0;
28593  let encipher;
28594  let decipher;
28595  let mask;
28596
28597  constructKeyVariables(cipher, key);
28598
28599  function constructKeyVariables(cipher, key) {
28600    const aes = new _cipher2.default[cipher](key);
28601    encipher = aes.encrypt.bind(aes);
28602    decipher = aes.decrypt.bind(aes);
28603
28604    const mask_x = encipher(zeroBlock);
28605    const mask_$ = _util2.default.double(mask_x);
28606    mask = [];
28607    mask[0] = _util2.default.double(mask_$);
28608
28609    mask.x = mask_x;
28610    mask.$ = mask_$;
28611  }
28612
28613  function extendKeyVariables(text, adata) {
28614    const newMaxNtz = _util2.default.nbits(Math.max(text.length, adata.length) / blockLength | 0) - 1;
28615    for (let i = maxNtz + 1; i <= newMaxNtz; i++) {
28616      mask[i] = _util2.default.double(mask[i - 1]);
28617    }
28618    maxNtz = newMaxNtz;
28619  }
28620
28621  function hash(adata) {
28622    if (!adata.length) {
28623      // Fast path
28624      return zeroBlock;
28625    }
28626
28627    //
28628    // Consider A as a sequence of 128-bit blocks
28629    //
28630    const m = adata.length / blockLength | 0;
28631
28632    const offset = new Uint8Array(blockLength);
28633    const sum = new Uint8Array(blockLength);
28634    for (let i = 0; i < m; i++) {
28635      xorMut(offset, mask[ntz(i + 1)]);
28636      xorMut(sum, encipher(xor(offset, adata)));
28637      adata = adata.subarray(blockLength);
28638    }
28639
28640    //
28641    // Process any final partial block; compute final hash value
28642    //
28643    if (adata.length) {
28644      xorMut(offset, mask.x);
28645
28646      const cipherInput = new Uint8Array(blockLength);
28647      cipherInput.set(adata, 0);
28648      cipherInput[adata.length] = 0b10000000;
28649      xorMut(cipherInput, offset);
28650
28651      xorMut(sum, encipher(cipherInput));
28652    }
28653
28654    return sum;
28655  }
28656
28657  /**
28658   * Encrypt/decrypt data.
28659   * @param  {encipher|decipher} fn   Encryption/decryption block cipher function
28660   * @param  {Uint8Array} text        The cleartext or ciphertext (without tag) input
28661   * @param  {Uint8Array} nonce       The nonce (15 bytes)
28662   * @param  {Uint8Array} adata       Associated data to sign
28663   * @returns {Promise<Uint8Array>}    The ciphertext or plaintext output, with tag appended in both cases
28664   */
28665  function crypt(fn, text, nonce, adata) {
28666    //
28667    // Consider P as a sequence of 128-bit blocks
28668    //
28669    const m = text.length / blockLength | 0;
28670
28671    //
28672    // Key-dependent variables
28673    //
28674    extendKeyVariables(text, adata);
28675
28676    //
28677    // Nonce-dependent and per-encryption variables
28678    //
28679    //    Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N
28680    // Note: We assume here that tagLength mod 16 == 0.
28681    const paddedNonce = _util2.default.concatUint8Array([zeroBlock.subarray(0, ivLength - nonce.length), one, nonce]);
28682    //    bottom = str2num(Nonce[123..128])
28683    const bottom = paddedNonce[blockLength - 1] & 0b111111;
28684    //    Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))
28685    paddedNonce[blockLength - 1] &= 0b11000000;
28686    const kTop = encipher(paddedNonce);
28687    //    Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])
28688    const stretched = _util2.default.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);
28689    //    Offset_0 = Stretch[1+bottom..128+bottom]
28690    const offset = _util2.default.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);
28691    //    Checksum_0 = zeros(128)
28692    const checksum = new Uint8Array(blockLength);
28693
28694    const ct = new Uint8Array(text.length + tagLength);
28695
28696    //
28697    // Process any whole blocks
28698    //
28699    let i;
28700    let pos = 0;
28701    for (i = 0; i < m; i++) {
28702      // Offset_i = Offset_{i-1} xor L_{ntz(i)}
28703      xorMut(offset, mask[ntz(i + 1)]);
28704      // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)
28705      // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)
28706      ct.set(xorMut(fn(xor(offset, text)), offset), pos);
28707      // Checksum_i = Checksum_{i-1} xor P_i
28708      xorMut(checksum, fn === encipher ? text : ct.subarray(pos));
28709
28710      text = text.subarray(blockLength);
28711      pos += blockLength;
28712    }
28713
28714    //
28715    // Process any final partial block and compute raw tag
28716    //
28717    if (text.length) {
28718      // Offset_* = Offset_m xor L_*
28719      xorMut(offset, mask.x);
28720      // Pad = ENCIPHER(K, Offset_*)
28721      const padding = encipher(offset);
28722      // C_* = P_* xor Pad[1..bitlen(P_*)]
28723      ct.set(xor(text, padding), pos);
28724
28725      // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))
28726      const xorInput = new Uint8Array(blockLength);
28727      xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength), 0);
28728      xorInput[text.length] = 0b10000000;
28729      xorMut(checksum, xorInput);
28730      pos += text.length;
28731    }
28732    // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)
28733    const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata));
28734
28735    //
28736    // Assemble ciphertext
28737    //
28738    // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]
28739    ct.set(tag, pos);
28740    return ct;
28741  }
28742
28743  return {
28744    /**
28745     * Encrypt plaintext input.
28746     * @param  {Uint8Array} plaintext   The cleartext input to be encrypted
28747     * @param  {Uint8Array} nonce       The nonce (15 bytes)
28748     * @param  {Uint8Array} adata       Associated data to sign
28749     * @returns {Promise<Uint8Array>}    The ciphertext output
28750     */
28751    encrypt: async function encrypt(plaintext, nonce, adata) {
28752      return crypt(encipher, plaintext, nonce, adata);
28753    },
28754
28755    /**
28756     * Decrypt ciphertext input.
28757     * @param  {Uint8Array} ciphertext  The ciphertext input to be decrypted
28758     * @param  {Uint8Array} nonce       The nonce (15 bytes)
28759     * @param  {Uint8Array} adata       Associated data to sign
28760     * @returns {Promise<Uint8Array>}    The ciphertext output
28761     */
28762    decrypt: async function decrypt(ciphertext, nonce, adata) {
28763      if (ciphertext.length < tagLength) throw new Error('Invalid OCB ciphertext');
28764
28765      const tag = ciphertext.subarray(-tagLength);
28766      ciphertext = ciphertext.subarray(0, -tagLength);
28767
28768      const crypted = crypt(decipher, ciphertext, nonce, adata);
28769      // if (Tag[1..TAGLEN] == T)
28770      if (_util2.default.equalsUint8Array(tag, crypted.subarray(-tagLength))) {
28771        return crypted.subarray(0, -tagLength);
28772      }
28773      throw new Error('Authentication tag mismatch');
28774    }
28775  };
28776}
28777
28778/**
28779 * 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}.
28780 * @param  {Uint8Array} iv           The initialization vector (15 bytes)
28781 * @param  {Uint8Array} chunkIndex   The chunk index (8 bytes)
28782 */
28783OCB.getNonce = function (iv, chunkIndex) {
28784  const nonce = iv.slice();
28785  for (let i = 0; i < chunkIndex.length; i++) {
28786    nonce[7 + i] ^= chunkIndex[i];
28787  }
28788  return nonce;
28789};
28790
28791OCB.blockLength = blockLength;
28792OCB.ivLength = ivLength;
28793OCB.tagLength = tagLength;
28794
28795exports.default = OCB;
28796
28797},{"../util":153,"./cipher":87}],97:[function(require,module,exports){
28798'use strict';
28799
28800Object.defineProperty(exports, "__esModule", {
28801  value: true
28802});
28803
28804var _random = require('./random');
28805
28806var _random2 = _interopRequireDefault(_random);
28807
28808var _hash = require('./hash');
28809
28810var _hash2 = _interopRequireDefault(_hash);
28811
28812var _util = require('../util');
28813
28814var _util2 = _interopRequireDefault(_util);
28815
28816function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
28817
28818/** @namespace */
28819const eme = {};
28820/** @namespace */
28821// GPG4Browsers - An OpenPGP implementation in javascript
28822// Copyright (C) 2011 Recurity Labs GmbH
28823//
28824// This library is free software; you can redistribute it and/or
28825// modify it under the terms of the GNU Lesser General Public
28826// License as published by the Free Software Foundation; either
28827// version 3.0 of the License, or (at your option) any later version.
28828//
28829// This library is distributed in the hope that it will be useful,
28830// but WITHOUT ANY WARRANTY; without even the implied warranty of
28831// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
28832// Lesser General Public License for more details.
28833//
28834// You should have received a copy of the GNU Lesser General Public
28835// License along with this library; if not, write to the Free Software
28836// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
28837
28838/**
28839 * @fileoverview Provides EME-PKCS1-v1_5 encoding and decoding and EMSA-PKCS1-v1_5 encoding function
28840 * @see module:crypto/public_key/rsa
28841 * @see module:crypto/public_key/elliptic/ecdh
28842 * @see module:packet.PublicKeyEncryptedSessionKey
28843 * @requires crypto/random
28844 * @requires crypto/hash
28845 * @requires util
28846 * @module crypto/pkcs1
28847 */
28848
28849const emsa = {};
28850
28851/**
28852 * ASN1 object identifiers for hashes
28853 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}
28854 */
28855const hash_headers = [];
28856hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10];
28857hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];
28858hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];
28859hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20];
28860hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30];
28861hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40];
28862hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1C];
28863
28864/**
28865 * Create padding with secure random data
28866 * @private
28867 * @param  {Integer} length Length of the padding in bytes
28868 * @returns {String}        Padding as string
28869 * @async
28870 */
28871async function getPkcs1Padding(length) {
28872  let result = '';
28873  while (result.length < length) {
28874    const randomBytes = await _random2.default.getRandomBytes(length - result.length);
28875    for (let i = 0; i < randomBytes.length; i++) {
28876      if (randomBytes[i] !== 0) {
28877        result += String.fromCharCode(randomBytes[i]);
28878      }
28879    }
28880  }
28881  return result;
28882}
28883
28884/**
28885 * Create a EME-PKCS1-v1_5 padded message
28886 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}
28887 * @param {String} M message to be encoded
28888 * @param {Integer} k the length in octets of the key modulus
28889 * @returns {Promise<String>} EME-PKCS1 padded message
28890 * @async
28891 */
28892eme.encode = async function (M, k) {
28893  const mLen = M.length;
28894  // length checking
28895  if (mLen > k - 11) {
28896    throw new Error('Message too long');
28897  }
28898  // Generate an octet string PS of length k - mLen - 3 consisting of
28899  // pseudo-randomly generated nonzero octets
28900  const PS = await getPkcs1Padding(k - mLen - 3);
28901  // Concatenate PS, the message M, and other padding to form an
28902  // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.
28903  return String.fromCharCode(0) + String.fromCharCode(2) + PS + String.fromCharCode(0) + M;
28904};
28905
28906/**
28907 * Decode a EME-PKCS1-v1_5 padded message
28908 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}
28909 * @param {String} EM encoded message, an octet string
28910 * @returns {String} message, an octet string
28911 */
28912eme.decode = function (EM) {
28913  // leading zeros truncated by bn.js
28914  if (EM.charCodeAt(0) !== 0) {
28915    EM = String.fromCharCode(0) + EM;
28916  }
28917  const firstOct = EM.charCodeAt(0);
28918  const secondOct = EM.charCodeAt(1);
28919  let i = 2;
28920  while (EM.charCodeAt(i) !== 0 && i < EM.length) {
28921    i++;
28922  }
28923  const psLen = i - 2;
28924  const separator = EM.charCodeAt(i++);
28925  if (firstOct === 0 && secondOct === 2 && psLen >= 8 && separator === 0) {
28926    return EM.substr(i);
28927  }
28928  throw new Error('Decryption error');
28929};
28930
28931/**
28932 * Create a EMSA-PKCS1-v1_5 padded message
28933 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}
28934 * @param {Integer} algo Hash algorithm type used
28935 * @param {Uint8Array} hashed message to be encoded
28936 * @param {Integer} emLen intended length in octets of the encoded message
28937 * @returns {String} encoded message
28938 */
28939emsa.encode = async function (algo, hashed, emLen) {
28940  let i;
28941  const H = _util2.default.Uint8Array_to_str(hashed);
28942  if (H.length !== _hash2.default.getHashByteLength(algo)) {
28943    throw new Error('Invalid hash length');
28944  }
28945  // produce an ASN.1 DER value for the hash function used.
28946  // Let T be the full hash prefix
28947  let T = '';
28948  for (i = 0; i < hash_headers[algo].length; i++) {
28949    T += String.fromCharCode(hash_headers[algo][i]);
28950  }
28951  // add hash value to prefix
28952  T += H;
28953  // and let tLen be the length in octets of T
28954  const tLen = T.length;
28955  if (emLen < tLen + 11) {
28956    throw new Error('Intended encoded message length too short');
28957  }
28958  // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF
28959  // The length of PS will be at least 8 octets
28960  let PS = '';
28961  for (i = 0; i < emLen - tLen - 3; i++) {
28962    PS += String.fromCharCode(0xff);
28963  }
28964  // Concatenate PS, the hash prefix T, and other padding to form the
28965  // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || T.
28966  const EM = String.fromCharCode(0x00) + String.fromCharCode(0x01) + PS + String.fromCharCode(0x00) + T;
28967  return _util2.default.str_to_hex(EM);
28968};
28969
28970exports.default = { eme, emsa };
28971
28972},{"../util":153,"./hash":93,"./random":110}],98:[function(require,module,exports){
28973'use strict';
28974
28975Object.defineProperty(exports, "__esModule", {
28976  value: true
28977});
28978// OpenPGP.js - An OpenPGP implementation in javascript
28979// Copyright (C) 2015-2016 Decentral
28980//
28981// This library is free software; you can redistribute it and/or
28982// modify it under the terms of the GNU Lesser General Public
28983// License as published by the Free Software Foundation; either
28984// version 3.0 of the License, or (at your option) any later version.
28985//
28986// This library is distributed in the hope that it will be useful,
28987// but WITHOUT ANY WARRANTY; without even the implied warranty of
28988// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
28989// Lesser General Public License for more details.
28990//
28991// You should have received a copy of the GNU Lesser General Public
28992// License along with this library; if not, write to the Free Software
28993// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
28994
28995/**
28996 * @fileoverview Functions to add and remove PKCS5 padding
28997 * @see module:packet.PublicKeyEncryptedSessionKey
28998 * @module crypto/pkcs5
28999 */
29000
29001/**
29002 * Add pkcs5 padding to a text.
29003 * @param  {String}  msg  Text to add padding
29004 * @returns {String}       Text with padding added
29005 */
29006function encode(msg) {
29007  const c = 8 - msg.length % 8;
29008  const padding = String.fromCharCode(c).repeat(c);
29009  return msg + padding;
29010}
29011
29012/**
29013 * Remove pkcs5 padding from a string.
29014 * @param  {String}  msg  Text to remove padding from
29015 * @returns {String}       Text with padding removed
29016 */
29017function decode(msg) {
29018  const len = msg.length;
29019  if (len > 0) {
29020    const c = msg.charCodeAt(len - 1);
29021    if (c >= 1 && c <= 8) {
29022      const provided = msg.substr(len - c);
29023      const computed = String.fromCharCode(c).repeat(c);
29024      if (provided === computed) {
29025        return msg.substr(0, len - c);
29026      }
29027    }
29028  }
29029  throw new Error('Invalid padding');
29030}
29031
29032exports.default = { encode, decode };
29033
29034},{}],99:[function(require,module,exports){
29035'use strict';
29036
29037Object.defineProperty(exports, "__esModule", {
29038  value: true
29039});
29040
29041var _bn = require('bn.js');
29042
29043var _bn2 = _interopRequireDefault(_bn);
29044
29045var _random = require('../random');
29046
29047var _random2 = _interopRequireDefault(_random);
29048
29049var _util = require('../../util');
29050
29051var _util2 = _interopRequireDefault(_util);
29052
29053function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29054
29055const one = new _bn2.default(1); // GPG4Browsers - An OpenPGP implementation in javascript
29056// Copyright (C) 2011 Recurity Labs GmbH
29057//
29058// This library is free software; you can redistribute it and/or
29059// modify it under the terms of the GNU Lesser General Public
29060// License as published by the Free Software Foundation; either
29061// version 3.0 of the License, or (at your option) any later version.
29062//
29063// This library is distributed in the hope that it will be useful,
29064// but WITHOUT ANY WARRANTY; without even the implied warranty of
29065// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
29066// Lesser General Public License for more details.
29067//
29068// You should have received a copy of the GNU Lesser General Public
29069// License along with this library; if not, write to the Free Software
29070// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
29071
29072/**
29073 * @fileoverview A Digital signature algorithm implementation
29074 * @requires bn.js
29075 * @requires crypto/random
29076 * @requires util
29077 * @module crypto/public_key/dsa
29078 */
29079
29080const zero = new _bn2.default(0);
29081
29082/*
29083  TODO regarding the hash function, read:
29084   https://tools.ietf.org/html/rfc4880#section-13.6
29085   https://tools.ietf.org/html/rfc4880#section-14
29086*/
29087
29088exports.default = {
29089  /**
29090   * DSA Sign function
29091   * @param {Integer} hash_algo
29092   * @param {Uint8Array} hashed
29093   * @param {BN} g
29094   * @param {BN} p
29095   * @param {BN} q
29096   * @param {BN} x
29097   * @returns {{ r: BN, s: BN }}
29098   * @async
29099   */
29100  sign: async function sign(hash_algo, hashed, g, p, q, x) {
29101    let k;
29102    let r;
29103    let s;
29104    let t;
29105    const redp = new _bn2.default.red(p);
29106    const redq = new _bn2.default.red(q);
29107    const gred = g.toRed(redp);
29108    const xred = x.toRed(redq);
29109    // If the output size of the chosen hash is larger than the number of
29110    // bits of q, the hash result is truncated to fit by taking the number
29111    // of leftmost bits equal to the number of bits of q.  This (possibly
29112    // truncated) hash function result is treated as a number and used
29113    // directly in the DSA signature algorithm.
29114    const h = new _bn2.default(_util2.default.getLeftNBits(hashed, q.bitLength())).toRed(redq);
29115    // FIPS-186-4, section 4.6:
29116    // The values of r and s shall be checked to determine if r = 0 or s = 0.
29117    // If either r = 0 or s = 0, a new value of k shall be generated, and the
29118    // signature shall be recalculated. It is extremely unlikely that r = 0
29119    // or s = 0 if signatures are generated properly.
29120    while (true) {
29121      // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
29122      k = await _random2.default.getRandomBN(one, q); // returns in [1, q-1]
29123      r = gred.redPow(k).fromRed().toRed(redq); // (g**k mod p) mod q
29124      if (zero.cmp(r) === 0) {
29125        continue;
29126      }
29127      t = h.redAdd(xred.redMul(r)); // H(m) + x*r mod q
29128      s = k.toRed(redq).redInvm().redMul(t); // k**-1 * (H(m) + x*r) mod q
29129      if (zero.cmp(s) === 0) {
29130        continue;
29131      }
29132      break;
29133    }
29134    return { r: r.toArrayLike(Uint8Array),
29135      s: s.toArrayLike(Uint8Array) };
29136  },
29137
29138  /**
29139   * DSA Verify function
29140   * @param {Integer} hash_algo
29141   * @param {BN} r
29142   * @param {BN} s
29143   * @param {Uint8Array} hashed
29144   * @param {BN} g
29145   * @param {BN} p
29146   * @param {BN} q
29147   * @param {BN} y
29148   * @returns BN
29149   * @async
29150   */
29151  verify: async function verify(hash_algo, r, s, hashed, g, p, q, y) {
29152    if (zero.ucmp(r) >= 0 || r.ucmp(q) >= 0 || zero.ucmp(s) >= 0 || s.ucmp(q) >= 0) {
29153      _util2.default.print_debug("invalid DSA Signature");
29154      return null;
29155    }
29156    const redp = new _bn2.default.red(p);
29157    const redq = new _bn2.default.red(q);
29158    const h = new _bn2.default(_util2.default.getLeftNBits(hashed, q.bitLength()));
29159    const w = s.toRed(redq).redInvm(); // s**-1 mod q
29160    if (zero.cmp(w) === 0) {
29161      _util2.default.print_debug("invalid DSA Signature");
29162      return null;
29163    }
29164    const u1 = h.toRed(redq).redMul(w); // H(m) * w mod q
29165    const u2 = r.toRed(redq).redMul(w); // r * w mod q
29166    const t1 = g.toRed(redp).redPow(u1.fromRed()); // g**u1 mod p
29167    const t2 = y.toRed(redp).redPow(u2.fromRed()); // y**u2 mod p
29168    const v = t1.redMul(t2).fromRed().mod(q); // (g**u1 * y**u2 mod p) mod q
29169    return v.cmp(r) === 0;
29170  }
29171};
29172
29173},{"../../util":153,"../random":110,"bn.js":17}],100:[function(require,module,exports){
29174'use strict';
29175
29176Object.defineProperty(exports, "__esModule", {
29177  value: true
29178});
29179
29180var _bn = require('bn.js');
29181
29182var _bn2 = _interopRequireDefault(_bn);
29183
29184var _random = require('../random');
29185
29186var _random2 = _interopRequireDefault(_random);
29187
29188function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29189
29190// GPG4Browsers - An OpenPGP implementation in javascript
29191// Copyright (C) 2011 Recurity Labs GmbH
29192//
29193// This library is free software; you can redistribute it and/or
29194// modify it under the terms of the GNU Lesser General Public
29195// License as published by the Free Software Foundation; either
29196// version 3.0 of the License, or (at your option) any later version.
29197//
29198// This library is distributed in the hope that it will be useful,
29199// but WITHOUT ANY WARRANTY; without even the implied warranty of
29200// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
29201// Lesser General Public License for more details.
29202//
29203// You should have received a copy of the GNU Lesser General Public
29204// License along with this library; if not, write to the Free Software
29205// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
29206
29207/**
29208 * @fileoverview ElGamal implementation
29209 * @requires bn.js
29210 * @requires crypto/random
29211 * @module crypto/public_key/elgamal
29212 */
29213
29214const zero = new _bn2.default(0);
29215
29216exports.default = {
29217  /**
29218   * ElGamal Encryption function
29219   * @param {BN} m
29220   * @param {BN} p
29221   * @param {BN} g
29222   * @param {BN} y
29223   * @returns {{ c1: BN, c2: BN }}
29224   * @async
29225   */
29226  encrypt: async function encrypt(m, p, g, y) {
29227    const redp = new _bn2.default.red(p);
29228    const mred = m.toRed(redp);
29229    const gred = g.toRed(redp);
29230    const yred = y.toRed(redp);
29231    // See Section 11.5 here: https://crypto.stanford.edu/~dabo/cryptobook/BonehShoup_0_4.pdf
29232    const k = await _random2.default.getRandomBN(zero, p); // returns in [0, p-1]
29233    return {
29234      c1: gred.redPow(k).fromRed(),
29235      c2: yred.redPow(k).redMul(mred).fromRed()
29236    };
29237  },
29238
29239  /**
29240   * ElGamal Encryption function
29241   * @param {BN} c1
29242   * @param {BN} c2
29243   * @param {BN} p
29244   * @param {BN} x
29245   * @returns BN
29246   * @async
29247   */
29248  decrypt: async function decrypt(c1, c2, p, x) {
29249    const redp = new _bn2.default.red(p);
29250    const c1red = c1.toRed(redp);
29251    const c2red = c2.toRed(redp);
29252    return c1red.redPow(x).redInvm().redMul(c2red).fromRed();
29253  }
29254};
29255
29256},{"../random":110,"bn.js":17}],101:[function(require,module,exports){
29257'use strict';
29258
29259Object.defineProperty(exports, "__esModule", {
29260  value: true
29261});
29262exports.getPreferredHashAlgo = exports.generate = exports.nodeCurves = exports.webCurves = exports.curves = undefined;
29263
29264var _bn = require('bn.js');
29265
29266var _bn2 = _interopRequireDefault(_bn);
29267
29268var _elliptic = require('elliptic');
29269
29270var _key = require('./key');
29271
29272var _key2 = _interopRequireDefault(_key);
29273
29274var _random = require('../../random');
29275
29276var _random2 = _interopRequireDefault(_random);
29277
29278var _enums = require('../../../enums');
29279
29280var _enums2 = _interopRequireDefault(_enums);
29281
29282var _util = require('../../../util');
29283
29284var _util2 = _interopRequireDefault(_util);
29285
29286var _oid = require('../../../type/oid');
29287
29288var _oid2 = _interopRequireDefault(_oid);
29289
29290function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29291
29292const webCrypto = _util2.default.getWebCrypto(); // OpenPGP.js - An OpenPGP implementation in javascript
29293// Copyright (C) 2015-2016 Decentral
29294//
29295// This library is free software; you can redistribute it and/or
29296// modify it under the terms of the GNU Lesser General Public
29297// License as published by the Free Software Foundation; either
29298// version 3.0 of the License, or (at your option) any later version.
29299//
29300// This library is distributed in the hope that it will be useful,
29301// but WITHOUT ANY WARRANTY; without even the implied warranty of
29302// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
29303// Lesser General Public License for more details.
29304//
29305// You should have received a copy of the GNU Lesser General Public
29306// License along with this library; if not, write to the Free Software
29307// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
29308
29309/**
29310 * @fileoverview Wrapper of an instance of an Elliptic Curve
29311 * @requires bn.js
29312 * @requires elliptic
29313 * @requires crypto/public_key/elliptic/key
29314 * @requires crypto/random
29315 * @requires enums
29316 * @requires util
29317 * @requires type/oid
29318 * @module crypto/public_key/elliptic/curve
29319 */
29320
29321const nodeCrypto = _util2.default.getNodeCrypto();
29322
29323const webCurves = {
29324  'p256': 'P-256',
29325  'p384': 'P-384',
29326  'p521': 'P-521'
29327};
29328const knownCurves = nodeCrypto ? nodeCrypto.getCurves() : [];
29329const nodeCurves = nodeCrypto ? {
29330  secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,
29331  p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,
29332  p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,
29333  p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,
29334  ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined,
29335  curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined,
29336  brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,
29337  brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,
29338  brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined
29339} : {};
29340
29341const curves = {
29342  p256: {
29343    oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],
29344    keyType: _enums2.default.publicKey.ecdsa,
29345    hash: _enums2.default.hash.sha256,
29346    cipher: _enums2.default.symmetric.aes128,
29347    node: nodeCurves.p256,
29348    web: webCurves.p256,
29349    payloadSize: 32
29350  },
29351  p384: {
29352    oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],
29353    keyType: _enums2.default.publicKey.ecdsa,
29354    hash: _enums2.default.hash.sha384,
29355    cipher: _enums2.default.symmetric.aes192,
29356    node: nodeCurves.p384,
29357    web: webCurves.p384,
29358    payloadSize: 48
29359  },
29360  p521: {
29361    oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],
29362    keyType: _enums2.default.publicKey.ecdsa,
29363    hash: _enums2.default.hash.sha512,
29364    cipher: _enums2.default.symmetric.aes256,
29365    node: nodeCurves.p521,
29366    web: webCurves.p521,
29367    payloadSize: 66
29368  },
29369  secp256k1: {
29370    oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],
29371    keyType: _enums2.default.publicKey.ecdsa,
29372    hash: _enums2.default.hash.sha256,
29373    cipher: _enums2.default.symmetric.aes128,
29374    node: nodeCurves.secp256k1
29375  },
29376  ed25519: {
29377    oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],
29378    keyType: _enums2.default.publicKey.eddsa,
29379    hash: _enums2.default.hash.sha512,
29380    node: false // nodeCurves.ed25519 TODO
29381  },
29382  curve25519: {
29383    oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],
29384    keyType: _enums2.default.publicKey.ecdsa,
29385    hash: _enums2.default.hash.sha256,
29386    cipher: _enums2.default.symmetric.aes128,
29387    node: false // nodeCurves.curve25519 TODO
29388  },
29389  brainpoolP256r1: {
29390    oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],
29391    keyType: _enums2.default.publicKey.ecdsa,
29392    hash: _enums2.default.hash.sha256,
29393    cipher: _enums2.default.symmetric.aes128,
29394    node: nodeCurves.brainpoolP256r1
29395  },
29396  brainpoolP384r1: {
29397    oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],
29398    keyType: _enums2.default.publicKey.ecdsa,
29399    hash: _enums2.default.hash.sha384,
29400    cipher: _enums2.default.symmetric.aes192,
29401    node: nodeCurves.brainpoolP384r1
29402  },
29403  brainpoolP512r1: {
29404    oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],
29405    keyType: _enums2.default.publicKey.ecdsa,
29406    hash: _enums2.default.hash.sha512,
29407    cipher: _enums2.default.symmetric.aes256,
29408    node: nodeCurves.brainpoolP512r1
29409  }
29410};
29411
29412/**
29413 * @constructor
29414 */
29415function Curve(oid_or_name, params) {
29416  try {
29417    if (_util2.default.isArray(oid_or_name) || _util2.default.isUint8Array(oid_or_name)) {
29418      // by oid byte array
29419      oid_or_name = new _oid2.default(oid_or_name);
29420    }
29421    if (oid_or_name instanceof _oid2.default) {
29422      // by curve OID
29423      oid_or_name = oid_or_name.getName();
29424    }
29425    // by curve name or oid string
29426    this.name = _enums2.default.write(_enums2.default.curve, oid_or_name);
29427  } catch (err) {
29428    throw new Error('Not valid curve');
29429  }
29430  params = params || curves[this.name];
29431
29432  this.keyType = params.keyType;
29433  switch (this.keyType) {
29434    case _enums2.default.publicKey.ecdsa:
29435      this.curve = new _elliptic.ec(this.name);
29436      break;
29437    case _enums2.default.publicKey.eddsa:
29438      this.curve = new _elliptic.eddsa(this.name);
29439      break;
29440    default:
29441      throw new Error('Unknown elliptic key type;');
29442  }
29443
29444  this.oid = params.oid;
29445  this.hash = params.hash;
29446  this.cipher = params.cipher;
29447  this.node = params.node && curves[this.name];
29448  this.web = params.web && curves[this.name];
29449  this.payloadSize = params.payloadSize;
29450}
29451
29452Curve.prototype.keyFromPrivate = function (priv) {
29453  // Not for ed25519
29454  return new _key2.default(this, { priv: priv });
29455};
29456
29457Curve.prototype.keyFromPublic = function (pub) {
29458  const keyPair = new _key2.default(this, { pub: pub });
29459  if (this.keyType === _enums2.default.publicKey.ecdsa && keyPair.keyPair.validate().result !== true) {
29460    throw new Error('Invalid elliptic public key');
29461  }
29462  return keyPair;
29463};
29464
29465Curve.prototype.genKeyPair = async function () {
29466  let keyPair;
29467  if (this.web && _util2.default.getWebCrypto()) {
29468    // If browser doesn't support a curve, we'll catch it
29469    try {
29470      keyPair = await webGenKeyPair(this.name);
29471    } catch (err) {
29472      _util2.default.print_debug("Browser did not support signing: " + err.message);
29473    }
29474  } else if (this.node && _util2.default.getNodeCrypto()) {
29475    keyPair = await nodeGenKeyPair(this.name);
29476  }
29477
29478  if (!keyPair || !keyPair.priv) {
29479    // elliptic fallback
29480    const r = await this.curve.genKeyPair({
29481      entropy: _util2.default.Uint8Array_to_str((await _random2.default.getRandomBytes(32)))
29482    });
29483    const compact = this.curve.curve.type === 'edwards' || this.curve.curve.type === 'mont';
29484    if (this.keyType === _enums2.default.publicKey.eddsa) {
29485      keyPair = { secret: r.getSecret() };
29486    } else {
29487      keyPair = { pub: r.getPublic('array', compact), priv: r.getPrivate().toArray() };
29488    }
29489  }
29490  return new _key2.default(this, keyPair);
29491};
29492
29493async function generate(curve) {
29494  curve = new Curve(curve);
29495  const keyPair = await curve.genKeyPair();
29496  return {
29497    oid: curve.oid,
29498    Q: new _bn2.default(keyPair.getPublic()),
29499    d: new _bn2.default(keyPair.getPrivate()),
29500    hash: curve.hash,
29501    cipher: curve.cipher
29502  };
29503}
29504
29505function getPreferredHashAlgo(oid) {
29506  return curves[_enums2.default.write(_enums2.default.curve, oid.toHex())].hash;
29507}
29508
29509exports.default = Curve;
29510exports.curves = curves;
29511exports.webCurves = webCurves;
29512exports.nodeCurves = nodeCurves;
29513exports.generate = generate;
29514exports.getPreferredHashAlgo = getPreferredHashAlgo;
29515
29516//////////////////////////
29517//                      //
29518//   Helper functions   //
29519//                      //
29520//////////////////////////
29521
29522
29523async function webGenKeyPair(name) {
29524  // Note: keys generated with ECDSA and ECDH are structurally equivalent
29525  const webCryptoKey = await webCrypto.generateKey({ name: "ECDSA", namedCurve: webCurves[name] }, true, ["sign", "verify"]);
29526
29527  const privateKey = await webCrypto.exportKey("jwk", webCryptoKey.privateKey);
29528  const publicKey = await webCrypto.exportKey("jwk", webCryptoKey.publicKey);
29529
29530  return {
29531    pub: {
29532      x: _util2.default.b64_to_Uint8Array(publicKey.x, true),
29533      y: _util2.default.b64_to_Uint8Array(publicKey.y, true)
29534    },
29535    priv: _util2.default.b64_to_Uint8Array(privateKey.d, true)
29536  };
29537}
29538
29539async function nodeGenKeyPair(name) {
29540  // Note: ECDSA and ECDH key generation is structurally equivalent
29541  const ecdh = nodeCrypto.createECDH(nodeCurves[name]);
29542  await ecdh.generateKeys();
29543
29544  return {
29545    pub: ecdh.getPublicKey().toJSON().data,
29546    priv: ecdh.getPrivateKey().toJSON().data
29547  };
29548}
29549
29550},{"../../../enums":114,"../../../type/oid":151,"../../../util":153,"../../random":110,"./key":106,"bn.js":17,"elliptic":19}],102:[function(require,module,exports){
29551'use strict';
29552
29553Object.defineProperty(exports, "__esModule", {
29554  value: true
29555});
29556
29557var _bn = require('bn.js');
29558
29559var _bn2 = _interopRequireDefault(_bn);
29560
29561var _naclFastLight = require('tweetnacl/nacl-fast-light.js');
29562
29563var _naclFastLight2 = _interopRequireDefault(_naclFastLight);
29564
29565var _curves = require('./curves');
29566
29567var _curves2 = _interopRequireDefault(_curves);
29568
29569var _aes_kw = require('../../aes_kw');
29570
29571var _aes_kw2 = _interopRequireDefault(_aes_kw);
29572
29573var _cipher = require('../../cipher');
29574
29575var _cipher2 = _interopRequireDefault(_cipher);
29576
29577var _hash = require('../../hash');
29578
29579var _hash2 = _interopRequireDefault(_hash);
29580
29581var _kdf_params = require('../../../type/kdf_params');
29582
29583var _kdf_params2 = _interopRequireDefault(_kdf_params);
29584
29585var _enums = require('../../../enums');
29586
29587var _enums2 = _interopRequireDefault(_enums);
29588
29589var _util = require('../../../util');
29590
29591var _util2 = _interopRequireDefault(_util);
29592
29593function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29594
29595// Build Param for ECDH algorithm (RFC 6637)
29596function buildEcdhParam(public_algo, oid, cipher_algo, hash_algo, fingerprint) {
29597  const kdf_params = new _kdf_params2.default([hash_algo, cipher_algo]);
29598  return _util2.default.concatUint8Array([oid.write(), new Uint8Array([public_algo]), kdf_params.write(), _util2.default.str_to_Uint8Array("Anonymous Sender    "), fingerprint.subarray(0, 20)]);
29599}
29600
29601// Key Derivation Function (RFC 6637)
29602// OpenPGP.js - An OpenPGP implementation in javascript
29603// Copyright (C) 2015-2016 Decentral
29604//
29605// This library is free software; you can redistribute it and/or
29606// modify it under the terms of the GNU Lesser General Public
29607// License as published by the Free Software Foundation; either
29608// version 3.0 of the License, or (at your option) any later version.
29609//
29610// This library is distributed in the hope that it will be useful,
29611// but WITHOUT ANY WARRANTY; without even the implied warranty of
29612// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
29613// Lesser General Public License for more details.
29614//
29615// You should have received a copy of the GNU Lesser General Public
29616// License along with this library; if not, write to the Free Software
29617// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
29618
29619/**
29620 * @fileoverview Key encryption and decryption for RFC 6637 ECDH
29621 * @requires bn.js
29622 * @requires tweetnacl
29623 * @requires crypto/public_key/elliptic/curve
29624 * @requires crypto/aes_kw
29625 * @requires crypto/cipher
29626 * @requires crypto/hash
29627 * @requires type/kdf_params
29628 * @requires enums
29629 * @requires util
29630 * @module crypto/public_key/elliptic/ecdh
29631 */
29632
29633async function kdf(hash_algo, X, length, param, stripLeading = false, stripTrailing = false) {
29634  // Note: X is little endian for Curve25519, big-endian for all others.
29635  // This is not ideal, but the RFC's are unclear
29636  // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
29637  let i;
29638  if (stripLeading) {
29639    // Work around old go crypto bug
29640    for (i = 0; i < X.length && X[i] === 0; i++);
29641    X = X.subarray(i);
29642  }
29643  if (stripTrailing) {
29644    // Work around old OpenPGP.js bug
29645    for (i = X.length - 1; i >= 0 && X[i] === 0; i--);
29646    X = X.subarray(0, i + 1);
29647  }
29648  const digest = await _hash2.default.digest(hash_algo, _util2.default.concatUint8Array([new Uint8Array([0, 0, 0, 1]), X, param]));
29649  return digest.subarray(0, length);
29650}
29651
29652/**
29653 * Generate ECDHE ephemeral key and secret from public key
29654 *
29655 * @param  {Curve}                  curve        Elliptic curve object
29656 * @param  {Uint8Array}             Q                   Recipient public key
29657 * @returns {Promise<{V: Uint8Array, S: BN}>}   Returns public part of ephemeral key and generated ephemeral secret
29658 * @async
29659 */
29660async function genPublicEphemeralKey(curve, Q) {
29661  if (curve.name === 'curve25519') {
29662    var _nacl$box$keyPair = _naclFastLight2.default.box.keyPair();
29663
29664    const d = _nacl$box$keyPair.secretKey;
29665
29666    var _ref = await genPrivateEphemeralKey(curve, Q, d);
29667
29668    const secretKey = _ref.secretKey,
29669          sharedKey = _ref.sharedKey;
29670
29671    var _nacl$box$keyPair$fro = _naclFastLight2.default.box.keyPair.fromSecretKey(secretKey);
29672
29673    let publicKey = _nacl$box$keyPair$fro.publicKey;
29674
29675    publicKey = _util2.default.concatUint8Array([new Uint8Array([0x40]), publicKey]);
29676    return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
29677  }
29678  const v = await curve.genKeyPair();
29679  Q = curve.keyFromPublic(Q);
29680  const publicKey = new Uint8Array(v.getPublic());
29681  const S = v.derive(Q);
29682  const len = curve.curve.curve.p.byteLength();
29683  const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
29684  return { publicKey, sharedKey };
29685}
29686
29687/**
29688 * Encrypt and wrap a session key
29689 *
29690 * @param  {module:type/oid}        oid          Elliptic curve object identifier
29691 * @param  {module:enums.symmetric} cipher_algo  Symmetric cipher to use
29692 * @param  {module:enums.hash}      hash_algo    Hash algorithm to use
29693 * @param  {module:type/mpi}        m            Value derived from session key (RFC 6637)
29694 * @param  {Uint8Array}             Q            Recipient public key
29695 * @param  {String}                 fingerprint  Recipient fingerprint
29696 * @returns {Promise<{V: BN, C: BN}>}            Returns public part of ephemeral key and encoded session key
29697 * @async
29698 */
29699async function encrypt(oid, cipher_algo, hash_algo, m, Q, fingerprint) {
29700  const curve = new _curves2.default(oid);
29701
29702  var _ref2 = await genPublicEphemeralKey(curve, Q);
29703
29704  const publicKey = _ref2.publicKey,
29705        sharedKey = _ref2.sharedKey;
29706
29707  const param = buildEcdhParam(_enums2.default.publicKey.ecdh, oid, cipher_algo, hash_algo, fingerprint);
29708  cipher_algo = _enums2.default.read(_enums2.default.symmetric, cipher_algo);
29709  const Z = await kdf(hash_algo, sharedKey, _cipher2.default[cipher_algo].keySize, param);
29710  const wrappedKey = _aes_kw2.default.wrap(Z, m.toString());
29711  return { publicKey, wrappedKey };
29712}
29713
29714/**
29715 * Generate ECDHE secret from private key and public part of ephemeral key
29716 *
29717 * @param  {Curve}                  curve        Elliptic curve object
29718 * @param  {Uint8Array}             V            Public part of ephemeral key
29719 * @param  {Uint8Array}             d            Recipient private key
29720 * @returns {Promise<BN>}                        Generated ephemeral secret
29721 * @async
29722 */
29723async function genPrivateEphemeralKey(curve, V, d) {
29724  if (curve.name === 'curve25519') {
29725    const one = new _bn2.default(1);
29726    const mask = one.ushln(255 - 3).sub(one).ushln(3);
29727    let secretKey = new _bn2.default(d);
29728    secretKey = secretKey.or(one.ushln(255 - 1));
29729    secretKey = secretKey.and(mask);
29730    secretKey = secretKey.toArrayLike(Uint8Array, 'le', 32);
29731    const sharedKey = _naclFastLight2.default.scalarMult(secretKey, V.subarray(1));
29732    return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
29733  }
29734  V = curve.keyFromPublic(V);
29735  d = curve.keyFromPrivate(d);
29736  const secretKey = new Uint8Array(d.getPrivate());
29737  const S = d.derive(V);
29738  const len = curve.curve.curve.p.byteLength();
29739  const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
29740  return { secretKey, sharedKey };
29741}
29742
29743/**
29744 * Decrypt and unwrap the value derived from session key
29745 *
29746 * @param  {module:type/oid}        oid          Elliptic curve object identifier
29747 * @param  {module:enums.symmetric} cipher_algo  Symmetric cipher to use
29748 * @param  {module:enums.hash}      hash_algo    Hash algorithm to use
29749 * @param  {Uint8Array}             V            Public part of ephemeral key
29750 * @param  {Uint8Array}             C            Encrypted and wrapped value derived from session key
29751 * @param  {Uint8Array}             d            Recipient private key
29752 * @param  {String}                 fingerprint  Recipient fingerprint
29753 * @returns {Promise<BN>}                        Value derived from session
29754 * @async
29755 */
29756async function decrypt(oid, cipher_algo, hash_algo, V, C, d, fingerprint) {
29757  const curve = new _curves2.default(oid);
29758
29759  var _ref3 = await genPrivateEphemeralKey(curve, V, d);
29760
29761  const sharedKey = _ref3.sharedKey;
29762
29763  const param = buildEcdhParam(_enums2.default.publicKey.ecdh, oid, cipher_algo, hash_algo, fingerprint);
29764  cipher_algo = _enums2.default.read(_enums2.default.symmetric, cipher_algo);
29765  let err;
29766  for (let i = 0; i < 3; i++) {
29767    try {
29768      // Work around old go crypto bug and old OpenPGP.js bug, respectively.
29769      const Z = await kdf(hash_algo, sharedKey, _cipher2.default[cipher_algo].keySize, param, i === 1, i === 2);
29770      return new _bn2.default(_aes_kw2.default.unwrap(Z, C));
29771    } catch (e) {
29772      err = e;
29773    }
29774  }
29775  throw err;
29776}
29777
29778exports.default = { encrypt, decrypt, genPublicEphemeralKey, genPrivateEphemeralKey, buildEcdhParam, kdf };
29779
29780},{"../../../enums":114,"../../../type/kdf_params":148,"../../../util":153,"../../aes_kw":81,"../../cipher":87,"../../hash":93,"./curves":101,"bn.js":17,"tweetnacl/nacl-fast-light.js":73}],103:[function(require,module,exports){
29781'use strict';
29782
29783Object.defineProperty(exports, "__esModule", {
29784  value: true
29785});
29786
29787var _curves = require('./curves');
29788
29789var _curves2 = _interopRequireDefault(_curves);
29790
29791function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29792
29793/**
29794 * Sign a message using the provided key
29795 * @param  {module:type/oid}   oid       Elliptic curve object identifier
29796 * @param  {module:enums.hash} hash_algo Hash algorithm used to sign
29797 * @param  {Uint8Array}        m         Message to sign
29798 * @param  {Uint8Array}        d         Private key used to sign the message
29799 * @param  {Uint8Array}        hashed    The hashed message
29800 * @returns {{r: Uint8Array,
29801 *            s: Uint8Array}}            Signature of the message
29802 * @async
29803 */
29804async function sign(oid, hash_algo, m, d, hashed) {
29805  const curve = new _curves2.default(oid);
29806  const key = curve.keyFromPrivate(d);
29807  const signature = await key.sign(m, hash_algo, hashed);
29808  return { r: signature.r.toArrayLike(Uint8Array),
29809    s: signature.s.toArrayLike(Uint8Array) };
29810}
29811
29812/**
29813 * Verifies if a signature is valid for a message
29814 * @param  {module:type/oid}   oid       Elliptic curve object identifier
29815 * @param  {module:enums.hash} hash_algo Hash algorithm used in the signature
29816 * @param  {{r: Uint8Array,
29817             s: Uint8Array}}   signature Signature to verify
29818 * @param  {Uint8Array}        m         Message to verify
29819 * @param  {Uint8Array}        Q         Public key used to verify the message
29820 * @param  {Uint8Array}        hashed    The hashed message
29821 * @returns {Boolean}
29822 * @async
29823 */
29824// OpenPGP.js - An OpenPGP implementation in javascript
29825// Copyright (C) 2015-2016 Decentral
29826//
29827// This library is free software; you can redistribute it and/or
29828// modify it under the terms of the GNU Lesser General Public
29829// License as published by the Free Software Foundation; either
29830// version 3.0 of the License, or (at your option) any later version.
29831//
29832// This library is distributed in the hope that it will be useful,
29833// but WITHOUT ANY WARRANTY; without even the implied warranty of
29834// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
29835// Lesser General Public License for more details.
29836//
29837// You should have received a copy of the GNU Lesser General Public
29838// License along with this library; if not, write to the Free Software
29839// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
29840
29841/**
29842 * @fileoverview Implementation of ECDSA following RFC6637 for Openpgpjs
29843 * @requires crypto/public_key/elliptic/curve
29844 * @module crypto/public_key/elliptic/ecdsa
29845 */
29846
29847async function verify(oid, hash_algo, signature, m, Q, hashed) {
29848  const curve = new _curves2.default(oid);
29849  const key = curve.keyFromPublic(Q);
29850  return key.verify(m, signature, hash_algo, hashed);
29851}
29852
29853exports.default = { sign, verify };
29854
29855},{"./curves":101}],104:[function(require,module,exports){
29856'use strict';
29857
29858Object.defineProperty(exports, "__esModule", {
29859  value: true
29860});
29861
29862var _ = require('hash.js/lib/hash/sha/512');
29863
29864var _2 = _interopRequireDefault(_);
29865
29866var _naclFastLight = require('tweetnacl/nacl-fast-light.js');
29867
29868var _naclFastLight2 = _interopRequireDefault(_naclFastLight);
29869
29870var _util = require('../../../util');
29871
29872var _util2 = _interopRequireDefault(_util);
29873
29874function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29875
29876_naclFastLight2.default.hash = bytes => new Uint8Array((0, _2.default)().update(bytes).digest());
29877
29878/**
29879 * Sign a message using the provided key
29880 * @param  {module:type/oid}   oid       Elliptic curve object identifier
29881 * @param  {module:enums.hash} hash_algo Hash algorithm used to sign
29882 * @param  {Uint8Array}        m         Message to sign
29883 * @param  {Uint8Array}        d         Private key used to sign
29884 * @param  {Uint8Array}        hashed    The hashed message
29885 * @returns {{R: Uint8Array,
29886 *            S: Uint8Array}}            Signature of the message
29887 * @async
29888 */
29889// OpenPGP.js - An OpenPGP implementation in javascript
29890// Copyright (C) 2018 Proton Technologies AG
29891//
29892// This library is free software; you can redistribute it and/or
29893// modify it under the terms of the GNU Lesser General Public
29894// License as published by the Free Software Foundation; either
29895// version 3.0 of the License, or (at your option) any later version.
29896//
29897// This library is distributed in the hope that it will be useful,
29898// but WITHOUT ANY WARRANTY; without even the implied warranty of
29899// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
29900// Lesser General Public License for more details.
29901//
29902// You should have received a copy of the GNU Lesser General Public
29903// License along with this library; if not, write to the Free Software
29904// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
29905
29906/**
29907 * @fileoverview Implementation of EdDSA following RFC4880bis-03 for OpenPGP
29908 * @requires hash.js
29909 * @requires tweetnacl
29910 * @requires crypto/public_key/elliptic/curve
29911 * @requires util
29912 * @module crypto/public_key/elliptic/eddsa
29913 */
29914
29915async function sign(oid, hash_algo, m, d, hashed) {
29916  var _nacl$sign$keyPair$fr = _naclFastLight2.default.sign.keyPair.fromSeed(d);
29917
29918  const secretKey = _nacl$sign$keyPair$fr.secretKey;
29919
29920  const signature = _naclFastLight2.default.sign.detached(hashed, secretKey);
29921  // EdDSA signature params are returned in little-endian format
29922  return {
29923    R: signature.subarray(0, 32),
29924    S: signature.subarray(32)
29925  };
29926}
29927
29928/**
29929 * Verifies if a signature is valid for a message
29930 * @param  {module:type/oid}   oid       Elliptic curve object identifier
29931 * @param  {module:enums.hash} hash_algo Hash algorithm used in the signature
29932 * @param  {{R: Uint8Array,
29933             S: Uint8Array}}   signature Signature to verify the message
29934 * @param  {Uint8Array}        m         Message to verify
29935 * @param  {Uint8Array}        publicKey Public key used to verify the message
29936 * @param  {Uint8Array}        hashed    The hashed message
29937 * @returns {Boolean}
29938 * @async
29939 */
29940async function verify(oid, hash_algo, { R, S }, m, publicKey, hashed) {
29941  const signature = _util2.default.concatUint8Array([R, S]);
29942  return _naclFastLight2.default.sign.detached.verify(hashed, signature, publicKey.subarray(1));
29943}
29944
29945exports.default = { sign, verify };
29946
29947},{"../../../util":153,"hash.js/lib/hash/sha/512":44,"tweetnacl/nacl-fast-light.js":73}],105:[function(require,module,exports){
29948'use strict';
29949
29950Object.defineProperty(exports, "__esModule", {
29951  value: true
29952});
29953
29954var _curves = require('./curves');
29955
29956var _curves2 = _interopRequireDefault(_curves);
29957
29958var _ecdsa = require('./ecdsa');
29959
29960var _ecdsa2 = _interopRequireDefault(_ecdsa);
29961
29962var _eddsa = require('./eddsa');
29963
29964var _eddsa2 = _interopRequireDefault(_eddsa);
29965
29966var _ecdh = require('./ecdh');
29967
29968var _ecdh2 = _interopRequireDefault(_ecdh);
29969
29970function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29971
29972// OpenPGP.js - An OpenPGP implementation in javascript
29973// Copyright (C) 2015-2016 Decentral
29974//
29975// This library is free software; you can redistribute it and/or
29976// modify it under the terms of the GNU Lesser General Public
29977// License as published by the Free Software Foundation; either
29978// version 3.0 of the License, or (at your option) any later version.
29979//
29980// This library is distributed in the hope that it will be useful,
29981// but WITHOUT ANY WARRANTY; without even the implied warranty of
29982// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
29983// Lesser General Public License for more details.
29984//
29985// You should have received a copy of the GNU Lesser General Public
29986// License along with this library; if not, write to the Free Software
29987// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
29988
29989/**
29990 * @fileoverview Functions to access Elliptic Curve Cryptography
29991 * @see module:crypto/public_key/elliptic/curve
29992 * @see module:crypto/public_key/elliptic/ecdh
29993 * @see module:crypto/public_key/elliptic/ecdsa
29994 * @see module:crypto/public_key/elliptic/eddsa
29995 * @module crypto/public_key/elliptic
29996 */
29997
29998exports.default = {
29999  Curve: _curves2.default, ecdh: _ecdh2.default, ecdsa: _ecdsa2.default, eddsa: _eddsa2.default, generate: _curves.generate, getPreferredHashAlgo: _curves.getPreferredHashAlgo
30000};
30001
30002},{"./curves":101,"./ecdh":102,"./ecdsa":103,"./eddsa":104}],106:[function(require,module,exports){
30003'use strict';
30004
30005Object.defineProperty(exports, "__esModule", {
30006  value: true
30007});
30008
30009var _bn = require('bn.js');
30010
30011var _bn2 = _interopRequireDefault(_bn);
30012
30013var _webStreamTools = require('web-stream-tools');
30014
30015var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
30016
30017var _curves = require('./curves');
30018
30019var _util = require('../../../util');
30020
30021var _util2 = _interopRequireDefault(_util);
30022
30023var _enums = require('../../../enums');
30024
30025var _enums2 = _interopRequireDefault(_enums);
30026
30027function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30028
30029const webCrypto = _util2.default.getWebCrypto(); // OpenPGP.js - An OpenPGP implementation in javascript
30030// Copyright (C) 2015-2016 Decentral
30031//
30032// This library is free software; you can redistribute it and/or
30033// modify it under the terms of the GNU Lesser General Public
30034// License as published by the Free Software Foundation; either
30035// version 3.0 of the License, or (at your option) any later version.
30036//
30037// This library is distributed in the hope that it will be useful,
30038// but WITHOUT ANY WARRANTY; without even the implied warranty of
30039// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
30040// Lesser General Public License for more details.
30041//
30042// You should have received a copy of the GNU Lesser General Public
30043// License along with this library; if not, write to the Free Software
30044// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
30045
30046/**
30047 * @fileoverview Wrapper for a KeyPair of an Elliptic Curve
30048 * @requires bn.js
30049 * @requires web-stream-tools
30050 * @requires crypto/public_key/elliptic/curves
30051 * @requires util
30052 * @requires enums
30053 * @requires asn1.js
30054 * @module crypto/public_key/elliptic/key
30055 */
30056
30057const nodeCrypto = _util2.default.getNodeCrypto();
30058
30059/**
30060 * @constructor
30061 */
30062function KeyPair(curve, options) {
30063  this.curve = curve;
30064  this.keyType = curve.curve.type === 'edwards' ? _enums2.default.publicKey.eddsa : _enums2.default.publicKey.ecdsa;
30065  this.keyPair = this.curve.curve.keyPair(options);
30066}
30067
30068KeyPair.prototype.sign = async function (message, hash_algo, hashed) {
30069  if (message && !message.locked) {
30070    message = await _webStreamTools2.default.readToEnd(message);
30071    if (this.curve.web && _util2.default.getWebCrypto()) {
30072      // If browser doesn't support a curve, we'll catch it
30073      try {
30074        // need to await to make sure browser succeeds
30075        const signature = await webSign(this.curve, hash_algo, message, this.keyPair);
30076        return signature;
30077      } catch (err) {
30078        _util2.default.print_debug("Browser did not support signing: " + err.message);
30079      }
30080    } else if (this.curve.node && _util2.default.getNodeCrypto()) {
30081      return nodeSign(this.curve, hash_algo, message, this.keyPair);
30082    }
30083  }
30084  const digest = typeof hash_algo === 'undefined' ? message : hashed;
30085  return this.keyPair.sign(digest);
30086};
30087
30088KeyPair.prototype.verify = async function (message, signature, hash_algo, hashed) {
30089  if (message && !message.locked) {
30090    message = await _webStreamTools2.default.readToEnd(message);
30091    if (this.curve.web && _util2.default.getWebCrypto()) {
30092      // If browser doesn't support a curve, we'll catch it
30093      try {
30094        // need to await to make sure browser succeeds
30095        const result = await webVerify(this.curve, hash_algo, signature, message, this.keyPair.getPublic());
30096        return result;
30097      } catch (err) {
30098        _util2.default.print_debug("Browser did not support signing: " + err.message);
30099      }
30100    } else if (this.curve.node && _util2.default.getNodeCrypto()) {
30101      return nodeVerify(this.curve, hash_algo, signature, message, this.keyPair.getPublic());
30102    }
30103  }
30104  const digest = typeof hash_algo === 'undefined' ? message : hashed;
30105  return this.keyPair.verify(digest, signature);
30106};
30107
30108KeyPair.prototype.derive = function (pub) {
30109  if (this.keyType === _enums2.default.publicKey.eddsa) {
30110    throw new Error('Key can only be used for EdDSA');
30111  }
30112  return this.keyPair.derive(pub.keyPair.getPublic());
30113};
30114
30115KeyPair.prototype.getPublic = function () {
30116  const compact = this.curve.curve.curve.type === 'edwards' || this.curve.curve.curve.type === 'mont';
30117  return this.keyPair.getPublic('array', compact);
30118};
30119
30120KeyPair.prototype.getPrivate = function () {
30121  if (this.curve.keyType === _enums2.default.publicKey.eddsa) {
30122    return this.keyPair.getSecret();
30123  }
30124  return this.keyPair.getPrivate().toArray();
30125};
30126
30127exports.default = KeyPair;
30128
30129//////////////////////////
30130//                      //
30131//   Helper functions   //
30132//                      //
30133//////////////////////////
30134
30135
30136async function webSign(curve, hash_algo, message, keyPair) {
30137  const len = curve.payloadSize;
30138  const key = await webCrypto.importKey("jwk", {
30139    "kty": "EC",
30140    "crv": _curves.webCurves[curve.name],
30141    "x": _util2.default.Uint8Array_to_b64(new Uint8Array(keyPair.getPublic().getX().toArray('be', len)), true),
30142    "y": _util2.default.Uint8Array_to_b64(new Uint8Array(keyPair.getPublic().getY().toArray('be', len)), true),
30143    "d": _util2.default.Uint8Array_to_b64(new Uint8Array(keyPair.getPrivate().toArray('be', len)), true),
30144    "use": "sig",
30145    "kid": "ECDSA Private Key"
30146  }, {
30147    "name": "ECDSA",
30148    "namedCurve": _curves.webCurves[curve.name],
30149    "hash": { name: _enums2.default.read(_enums2.default.webHash, curve.hash) }
30150  }, false, ["sign"]);
30151
30152  const signature = new Uint8Array((await webCrypto.sign({
30153    "name": 'ECDSA',
30154    "namedCurve": _curves.webCurves[curve.name],
30155    "hash": { name: _enums2.default.read(_enums2.default.webHash, hash_algo) }
30156  }, key, message)));
30157
30158  return {
30159    r: new _bn2.default(signature.slice(0, len)),
30160    s: new _bn2.default(signature.slice(len, len << 1))
30161  };
30162}
30163
30164async function webVerify(curve, hash_algo, { r, s }, message, publicKey) {
30165  const len = curve.payloadSize;
30166  const key = await webCrypto.importKey("jwk", {
30167    "kty": "EC",
30168    "crv": _curves.webCurves[curve.name],
30169    "x": _util2.default.Uint8Array_to_b64(new Uint8Array(publicKey.getX().toArray('be', len)), true),
30170    "y": _util2.default.Uint8Array_to_b64(new Uint8Array(publicKey.getY().toArray('be', len)), true),
30171    "use": "sig",
30172    "kid": "ECDSA Public Key"
30173  }, {
30174    "name": "ECDSA",
30175    "namedCurve": _curves.webCurves[curve.name],
30176    "hash": { name: _enums2.default.read(_enums2.default.webHash, curve.hash) }
30177  }, false, ["verify"]);
30178
30179  const signature = _util2.default.concatUint8Array([new Uint8Array(len - r.length), r, new Uint8Array(len - s.length), s]).buffer;
30180
30181  return webCrypto.verify({
30182    "name": 'ECDSA',
30183    "namedCurve": _curves.webCurves[curve.name],
30184    "hash": { name: _enums2.default.read(_enums2.default.webHash, hash_algo) }
30185  }, key, signature, message);
30186}
30187
30188async function nodeSign(curve, hash_algo, message, keyPair) {
30189  const sign = nodeCrypto.createSign(_enums2.default.read(_enums2.default.hash, hash_algo));
30190  sign.write(message);
30191  sign.end();
30192
30193  const key = ECPrivateKey.encode({
30194    version: 1,
30195    parameters: curve.oid,
30196    privateKey: keyPair.getPrivate().toArray(),
30197    publicKey: { unused: 0, data: keyPair.getPublic().encode() }
30198  }, 'pem', {
30199    label: 'EC PRIVATE KEY'
30200  });
30201
30202  return ECDSASignature.decode(sign.sign(key), 'der');
30203}
30204
30205async function nodeVerify(curve, hash_algo, { r, s }, message, publicKey) {
30206  const verify = nodeCrypto.createVerify(_enums2.default.read(_enums2.default.hash, hash_algo));
30207  verify.write(message);
30208  verify.end();
30209
30210  const key = SubjectPublicKeyInfo.encode({
30211    algorithm: {
30212      algorithm: [1, 2, 840, 10045, 2, 1],
30213      parameters: curve.oid
30214    },
30215    subjectPublicKey: { unused: 0, data: publicKey.encode() }
30216  }, 'pem', {
30217    label: 'PUBLIC KEY'
30218  });
30219
30220  const signature = ECDSASignature.encode({
30221    r: new _bn2.default(r), s: new _bn2.default(s)
30222  }, 'der');
30223
30224  try {
30225    return verify.verify(key, signature);
30226  } catch (err) {
30227    return false;
30228  }
30229}
30230
30231// Originally written by Owen Smith https://github.com/omsmith
30232// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/
30233
30234/* eslint-disable no-invalid-this */
30235
30236const asn1 = nodeCrypto ? require('asn1.js') : undefined;
30237
30238const ECDSASignature = nodeCrypto ? asn1.define('ECDSASignature', function () {
30239  this.seq().obj(this.key('r').int(), this.key('s').int());
30240}) : undefined;
30241
30242const ECPrivateKey = nodeCrypto ? asn1.define('ECPrivateKey', function () {
30243  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());
30244}) : undefined;
30245
30246const AlgorithmIdentifier = nodeCrypto ? asn1.define('AlgorithmIdentifier', function () {
30247  this.seq().obj(this.key('algorithm').objid(), this.key('parameters').optional().any());
30248}) : undefined;
30249
30250const SubjectPublicKeyInfo = nodeCrypto ? asn1.define('SubjectPublicKeyInfo', function () {
30251  this.seq().obj(this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPublicKey').bitstr());
30252}) : undefined;
30253
30254},{"../../../enums":114,"../../../util":153,"./curves":101,"asn1.js":"asn1.js","bn.js":17,"web-stream-tools":76}],107:[function(require,module,exports){
30255'use strict';
30256
30257Object.defineProperty(exports, "__esModule", {
30258  value: true
30259});
30260
30261var _naclFastLight = require('tweetnacl/nacl-fast-light.js');
30262
30263var _naclFastLight2 = _interopRequireDefault(_naclFastLight);
30264
30265var _rsa = require('./rsa');
30266
30267var _rsa2 = _interopRequireDefault(_rsa);
30268
30269var _elgamal = require('./elgamal');
30270
30271var _elgamal2 = _interopRequireDefault(_elgamal);
30272
30273var _elliptic = require('./elliptic');
30274
30275var _elliptic2 = _interopRequireDefault(_elliptic);
30276
30277var _dsa = require('./dsa');
30278
30279var _dsa2 = _interopRequireDefault(_dsa);
30280
30281function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30282
30283exports.default = {
30284  /** @see module:crypto/public_key/rsa */
30285  rsa: _rsa2.default,
30286  /** @see module:crypto/public_key/elgamal */
30287  elgamal: _elgamal2.default,
30288  /** @see module:crypto/public_key/elliptic */
30289  elliptic: _elliptic2.default,
30290  /** @see module:crypto/public_key/dsa */
30291  dsa: _dsa2.default,
30292  /** @see tweetnacl */
30293  nacl: _naclFastLight2.default
30294}; /**
30295    * @fileoverview Asymmetric cryptography functions
30296    * @requires tweetnacl
30297    * @requires crypto/public_key/dsa
30298    * @requires crypto/public_key/elgamal
30299    * @requires crypto/public_key/elliptic
30300    * @requires crypto/public_key/rsa
30301    * @module crypto/public_key
30302    */
30303
30304},{"./dsa":99,"./elgamal":100,"./elliptic":105,"./rsa":109,"tweetnacl/nacl-fast-light.js":73}],108:[function(require,module,exports){
30305'use strict';
30306
30307Object.defineProperty(exports, "__esModule", {
30308  value: true
30309});
30310
30311var _bn = require('bn.js');
30312
30313var _bn2 = _interopRequireDefault(_bn);
30314
30315var _random = require('../random');
30316
30317var _random2 = _interopRequireDefault(_random);
30318
30319function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30320
30321// OpenPGP.js - An OpenPGP implementation in javascript
30322// Copyright (C) 2018 Proton Technologies AG
30323//
30324// This library is free software; you can redistribute it and/or
30325// modify it under the terms of the GNU Lesser General Public
30326// License as published by the Free Software Foundation; either
30327// version 3.0 of the License, or (at your option) any later version.
30328//
30329// This library is distributed in the hope that it will be useful,
30330// but WITHOUT ANY WARRANTY; without even the implied warranty of
30331// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
30332// Lesser General Public License for more details.
30333//
30334// You should have received a copy of the GNU Lesser General Public
30335// License along with this library; if not, write to the Free Software
30336// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
30337
30338/**
30339 * @fileoverview Algorithms for probabilistic random prime generation
30340 * @requires bn.js
30341 * @requires crypto/random
30342 * @module crypto/public_key/prime
30343 */
30344
30345exports.default = {
30346  randomProbablePrime, isProbablePrime, fermat, millerRabin, divisionTest
30347};
30348
30349/**
30350 * Probabilistic random number generator
30351 * @param {Integer} bits Bit length of the prime
30352 * @param {BN}      e    Optional RSA exponent to check against the prime
30353 * @param {Integer} k    Optional number of iterations of Miller-Rabin test
30354 * @returns BN
30355 * @async
30356 */
30357
30358async function randomProbablePrime(bits, e, k) {
30359  const min = new _bn2.default(1).shln(bits - 1);
30360  const thirty = new _bn2.default(30);
30361  /*
30362   * We can avoid any multiples of 3 and 5 by looking at n mod 30
30363   * 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
30364   * the next possible prime is mod 30:
30365   *            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
30366   */
30367  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];
30368
30369  let n = await _random2.default.getRandomBN(min, min.shln(1));
30370  let i = n.mod(thirty).toNumber();
30371
30372  do {
30373    n.iaddn(adds[i]);
30374    i = (i + adds[i]) % adds.length;
30375    // If reached the maximum, go back to the minimum.
30376    if (n.bitLength() > bits) {
30377      n = n.mod(min.shln(1)).iadd(min);
30378      i = n.mod(thirty).toNumber();
30379    }
30380  } while (!(await isProbablePrime(n, e, k)));
30381  return n;
30382}
30383
30384/**
30385 * Probabilistic primality testing
30386 * @param {BN}      n Number to test
30387 * @param {BN}      e Optional RSA exponent to check against the prime
30388 * @param {Integer} k Optional number of iterations of Miller-Rabin test
30389 * @returns {boolean}
30390 * @async
30391 */
30392async function isProbablePrime(n, e, k) {
30393  if (e && !n.subn(1).gcd(e).eqn(1)) {
30394    return false;
30395  }
30396  if (!divisionTest(n)) {
30397    return false;
30398  }
30399  if (!fermat(n)) {
30400    return false;
30401  }
30402  if (!(await millerRabin(n, k))) {
30403    return false;
30404  }
30405  // TODO implement the Lucas test
30406  // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
30407  return true;
30408}
30409
30410/**
30411 * Tests whether n is probably prime or not using Fermat's test with b = 2.
30412 * Fails if b^(n-1) mod n === 1.
30413 * @param {BN}      n Number to test
30414 * @param {Integer} b Optional Fermat test base
30415 * @returns {boolean}
30416 */
30417function fermat(n, b) {
30418  b = b || new _bn2.default(2);
30419  return b.toRed(_bn2.default.mont(n)).redPow(n.subn(1)).fromRed().cmpn(1) === 0;
30420}
30421
30422function divisionTest(n) {
30423  return small_primes.every(m => {
30424    return n.modn(m) !== 0;
30425  });
30426}
30427
30428// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c
30429const small_primes = [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];
30430
30431// Miller-Rabin - Miller Rabin algorithm for primality test
30432// Copyright Fedor Indutny, 2014.
30433//
30434// This software is licensed under the MIT License.
30435//
30436// Permission is hereby granted, free of charge, to any person obtaining a
30437// copy of this software and associated documentation files (the
30438// "Software"), to deal in the Software without restriction, including
30439// without limitation the rights to use, copy, modify, merge, publish,
30440// distribute, sublicense, and/or sell copies of the Software, and to permit
30441// persons to whom the Software is furnished to do so, subject to the
30442// following conditions:
30443//
30444// The above copyright notice and this permission notice shall be included
30445// in all copies or substantial portions of the Software.
30446//
30447// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
30448// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
30449// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
30450// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
30451// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
30452// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
30453// USE OR OTHER DEALINGS IN THE SOFTWARE.
30454
30455// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin
30456
30457// Sample syntax for Fixed-Base Miller-Rabin:
30458// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))
30459
30460/**
30461 * Tests whether n is probably prime or not using the Miller-Rabin test.
30462 * See HAC Remark 4.28.
30463 * @param {BN}       n    Number to test
30464 * @param {Integer}  k    Optional number of iterations of Miller-Rabin test
30465 * @param {Function} rand Optional function to generate potential witnesses
30466 * @returns {boolean}
30467 * @async
30468 */
30469async function millerRabin(n, k, rand) {
30470  const len = n.bitLength();
30471  const red = _bn2.default.mont(n);
30472  const rone = new _bn2.default(1).toRed(red);
30473
30474  if (!k) {
30475    k = Math.max(1, len / 48 | 0);
30476  }
30477
30478  const n1 = n.subn(1);
30479  const rn1 = n1.toRed(red);
30480
30481  // Find d and s, (n - 1) = (2 ^ s) * d;
30482  let s = 0;
30483  while (!n1.testn(s)) {
30484    s++;
30485  }
30486  const d = n.shrn(s);
30487
30488  for (; k > 0; k--) {
30489    const a = rand ? rand() : await _random2.default.getRandomBN(new _bn2.default(2), n1);
30490
30491    let x = a.toRed(red).redPow(d);
30492    if (x.eq(rone) || x.eq(rn1)) {
30493      continue;
30494    }
30495
30496    let i;
30497    for (i = 1; i < s; i++) {
30498      x = x.redSqr();
30499
30500      if (x.eq(rone)) {
30501        return false;
30502      }
30503      if (x.eq(rn1)) {
30504        break;
30505      }
30506    }
30507
30508    if (i === s) {
30509      return false;
30510    }
30511  }
30512
30513  return true;
30514}
30515
30516},{"../random":110,"bn.js":17}],109:[function(require,module,exports){
30517'use strict';
30518
30519Object.defineProperty(exports, "__esModule", {
30520  value: true
30521});
30522
30523var _bn = require('bn.js');
30524
30525var _bn2 = _interopRequireDefault(_bn);
30526
30527var _prime = require('./prime');
30528
30529var _prime2 = _interopRequireDefault(_prime);
30530
30531var _random = require('../random');
30532
30533var _random2 = _interopRequireDefault(_random);
30534
30535var _config = require('../../config');
30536
30537var _config2 = _interopRequireDefault(_config);
30538
30539var _util = require('../../util');
30540
30541var _util2 = _interopRequireDefault(_util);
30542
30543function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30544
30545// Helper for IE11 KeyOperation objects
30546function promisifyIE11Op(keyObj, err) {
30547  if (typeof keyObj.then !== 'function') {
30548    // IE11 KeyOperation
30549    return new Promise(function (resolve, reject) {
30550      keyObj.onerror = function () {
30551        reject(new Error(err));
30552      };
30553      keyObj.oncomplete = function (e) {
30554        resolve(e.target.result);
30555      };
30556    });
30557  }
30558  return keyObj;
30559} // GPG4Browsers - An OpenPGP implementation in javascript
30560// Copyright (C) 2011 Recurity Labs GmbH
30561//
30562// This library is free software; you can redistribute it and/or
30563// modify it under the terms of the GNU Lesser General Public
30564// License as published by the Free Software Foundation; either
30565// version 3.0 of the License, or (at your option) any later version.
30566//
30567// This library is distributed in the hope that it will be useful,
30568// but WITHOUT ANY WARRANTY; without even the implied warranty of
30569// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
30570// Lesser General Public License for more details.
30571//
30572// You should have received a copy of the GNU Lesser General Public
30573// License along with this library; if not, write to the Free Software
30574// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
30575
30576/**
30577 * @fileoverview RSA implementation
30578 * @requires bn.js
30579 * @requires crypto/public_key/prime
30580 * @requires crypto/random
30581 * @requires config
30582 * @requires util
30583 * @module crypto/public_key/rsa
30584 */
30585
30586exports.default = {
30587  /** Create signature
30588   * @param {BN} m message
30589   * @param {BN} n RSA public modulus
30590   * @param {BN} e RSA public exponent
30591   * @param {BN} d RSA private exponent
30592   * @returns {BN} RSA Signature
30593   * @async
30594   */
30595  sign: async function sign(m, n, e, d) {
30596    if (n.cmp(m) <= 0) {
30597      throw new Error('Message size cannot exceed modulus size');
30598    }
30599    const nred = new _bn2.default.red(n);
30600    return m.toRed(nred).redPow(d).toArrayLike(Uint8Array, 'be', n.byteLength());
30601  },
30602
30603  /**
30604   * Verify signature
30605   * @param {BN} s signature
30606   * @param {BN} n RSA public modulus
30607   * @param {BN} e RSA public exponent
30608   * @returns {BN}
30609   * @async
30610   */
30611  verify: async function verify(s, n, e) {
30612    if (n.cmp(s) <= 0) {
30613      throw new Error('Signature size cannot exceed modulus size');
30614    }
30615    const nred = new _bn2.default.red(n);
30616    return s.toRed(nred).redPow(e).toArrayLike(Uint8Array, 'be', n.byteLength());
30617  },
30618
30619  /**
30620   * Encrypt message
30621   * @param {BN} m message
30622   * @param {BN} n RSA public modulus
30623   * @param {BN} e RSA public exponent
30624   * @returns {BN} RSA Ciphertext
30625   * @async
30626   */
30627  encrypt: async function encrypt(m, n, e) {
30628    if (n.cmp(m) <= 0) {
30629      throw new Error('Message size cannot exceed modulus size');
30630    }
30631    const nred = new _bn2.default.red(n);
30632    return m.toRed(nred).redPow(e).toArrayLike(Uint8Array, 'be', n.byteLength());
30633  },
30634
30635  /**
30636   * Decrypt RSA message
30637   * @param {BN} m message
30638   * @param {BN} n RSA public modulus
30639   * @param {BN} e RSA public exponent
30640   * @param {BN} d RSA private exponent
30641   * @param {BN} p RSA private prime p
30642   * @param {BN} q RSA private prime q
30643   * @param {BN} u RSA private inverse of prime q
30644   * @returns {BN} RSA Plaintext
30645   * @async
30646   */
30647  decrypt: async function decrypt(m, n, e, d, p, q, u) {
30648    if (n.cmp(m) <= 0) {
30649      throw new Error('Data too large.');
30650    }
30651    const dq = d.mod(q.subn(1)); // d mod (q-1)
30652    const dp = d.mod(p.subn(1)); // d mod (p-1)
30653    const pred = new _bn2.default.red(p);
30654    const qred = new _bn2.default.red(q);
30655    const nred = new _bn2.default.red(n);
30656
30657    let blinder;
30658    let unblinder;
30659    if (_config2.default.rsa_blinding) {
30660      unblinder = (await _random2.default.getRandomBN(new _bn2.default(2), n)).toRed(nred);
30661      blinder = unblinder.redInvm().redPow(e);
30662      m = m.toRed(nred).redMul(blinder).fromRed();
30663    }
30664
30665    const mp = m.toRed(pred).redPow(dp);
30666    const mq = m.toRed(qred).redPow(dq);
30667    const t = mq.redSub(mp.fromRed().toRed(qred));
30668    const h = u.toRed(qred).redMul(t).fromRed();
30669
30670    let result = h.mul(p).add(mp).toRed(nred);
30671
30672    if (_config2.default.rsa_blinding) {
30673      result = result.redMul(unblinder);
30674    }
30675
30676    return result.toArrayLike(Uint8Array, 'be', n.byteLength());
30677  },
30678
30679  /**
30680   * Generate a new random private key B bits long with public exponent E.
30681   *
30682   * When possible, webCrypto is used. Otherwise, primes are generated using
30683   * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.
30684   * @see module:crypto/public_key/prime
30685   * @param {Integer} B RSA bit length
30686   * @param {String}  E RSA public exponent in hex string
30687   * @returns {{n: BN, e: BN, d: BN,
30688   *            p: BN, q: BN, u: BN}} RSA public modulus, RSA public exponent, RSA private exponent,
30689   *                                  RSA private prime p, RSA private prime q, u = q ** -1 mod p
30690   * @async
30691   */
30692  generate: async function generate(B, E) {
30693    let key;
30694    E = new _bn2.default(E, 16);
30695    const webCrypto = _util2.default.getWebCryptoAll();
30696
30697    // Native RSA keygen using Web Crypto
30698    if (webCrypto) {
30699      let keyPair;
30700      let keyGenOpt;
30701      if (window.crypto && window.crypto.subtle || window.msCrypto) {
30702        // current standard spec
30703        keyGenOpt = {
30704          name: 'RSASSA-PKCS1-v1_5',
30705          modulusLength: B, // the specified keysize in bits
30706          publicExponent: E.toArrayLike(Uint8Array), // take three bytes (max 65537) for exponent
30707          hash: {
30708            name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'
30709          }
30710        };
30711        keyPair = webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']);
30712        keyPair = await promisifyIE11Op(keyPair, 'Error generating RSA key pair.');
30713      } else if (window.crypto && window.crypto.webkitSubtle) {
30714        // outdated spec implemented by old Webkit
30715        keyGenOpt = {
30716          name: 'RSA-OAEP',
30717          modulusLength: B, // the specified keysize in bits
30718          publicExponent: E.toArrayLike(Uint8Array), // take three bytes (max 65537) for exponent
30719          hash: {
30720            name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'
30721          }
30722        };
30723        keyPair = await webCrypto.generateKey(keyGenOpt, true, ['encrypt', 'decrypt']);
30724      } else {
30725        throw new Error('Unknown WebCrypto implementation');
30726      }
30727
30728      // export the generated keys as JsonWebKey (JWK)
30729      // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33
30730      let jwk = webCrypto.exportKey('jwk', keyPair.privateKey);
30731      jwk = await promisifyIE11Op(jwk, 'Error exporting RSA key pair.');
30732
30733      // parse raw ArrayBuffer bytes to jwk/json (WebKit/Safari/IE11 quirk)
30734      if (jwk instanceof ArrayBuffer) {
30735        jwk = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(jwk)));
30736      }
30737
30738      // map JWK parameters to BN
30739      key = {};
30740      key.n = new _bn2.default(_util2.default.b64_to_Uint8Array(jwk.n));
30741      key.e = E;
30742      key.d = new _bn2.default(_util2.default.b64_to_Uint8Array(jwk.d));
30743      key.p = new _bn2.default(_util2.default.b64_to_Uint8Array(jwk.p));
30744      key.q = new _bn2.default(_util2.default.b64_to_Uint8Array(jwk.q));
30745      key.u = key.p.invm(key.q);
30746      return key;
30747    }
30748
30749    // RSA keygen fallback using 40 iterations of the Miller-Rabin test
30750    // See https://stackoverflow.com/a/6330138 for justification
30751    // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST
30752    let p = await _prime2.default.randomProbablePrime(B - (B >> 1), E, 40);
30753    let q = await _prime2.default.randomProbablePrime(B >> 1, E, 40);
30754
30755    if (p.cmp(q) < 0) {
30756      var _ref = [q, p];
30757      p = _ref[0];
30758      q = _ref[1];
30759    }
30760
30761    const phi = p.subn(1).mul(q.subn(1));
30762    return {
30763      n: p.mul(q),
30764      e: E,
30765      d: E.invm(phi),
30766      p: p,
30767      q: q,
30768      // dp: d.mod(p.subn(1)),
30769      // dq: d.mod(q.subn(1)),
30770      u: p.invm(q)
30771    };
30772  },
30773
30774  prime: _prime2.default
30775};
30776
30777},{"../../config":80,"../../util":153,"../random":110,"./prime":108,"bn.js":17}],110:[function(require,module,exports){
30778'use strict';
30779
30780Object.defineProperty(exports, "__esModule", {
30781  value: true
30782});
30783
30784var _bn = require('bn.js');
30785
30786var _bn2 = _interopRequireDefault(_bn);
30787
30788var _util = require('../util');
30789
30790var _util2 = _interopRequireDefault(_util);
30791
30792function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30793
30794// Do not use util.getNodeCrypto because we need this regardless of use_native setting
30795// GPG4Browsers - An OpenPGP implementation in javascript
30796// Copyright (C) 2011 Recurity Labs GmbH
30797//
30798// This library is free software; you can redistribute it and/or
30799// modify it under the terms of the GNU Lesser General Public
30800// License as published by the Free Software Foundation; either
30801// version 3.0 of the License, or (at your option) any later version.
30802//
30803// This library is distributed in the hope that it will be useful,
30804// but WITHOUT ANY WARRANTY; without even the implied warranty of
30805// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
30806// Lesser General Public License for more details.
30807//
30808// You should have received a copy of the GNU Lesser General Public
30809// License along with this library; if not, write to the Free Software
30810// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
30811
30812// The GPG4Browsers crypto interface
30813
30814/**
30815 * @fileoverview Provides tools for retrieving secure randomness from browsers or Node.js
30816 * @requires bn.js
30817 * @requires util
30818 * @module crypto/random
30819 */
30820
30821const nodeCrypto = _util2.default.detectNode() && require('crypto');
30822
30823exports.default = {
30824  /**
30825   * Retrieve secure random byte array of the specified length
30826   * @param {Integer} length Length in bytes to generate
30827   * @returns {Uint8Array} Random byte array
30828   * @async
30829   */
30830  getRandomBytes: async function getRandomBytes(length) {
30831    const buf = new Uint8Array(length);
30832    if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
30833      window.crypto.getRandomValues(buf);
30834    } else if (typeof window !== 'undefined' && typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function') {
30835      window.msCrypto.getRandomValues(buf);
30836    } else if (nodeCrypto) {
30837      const bytes = nodeCrypto.randomBytes(buf.length);
30838      buf.set(bytes);
30839    } else if (this.randomBuffer.buffer) {
30840      await this.randomBuffer.get(buf);
30841    } else {
30842      throw new Error('No secure random number generator available.');
30843    }
30844    return buf;
30845  },
30846
30847  /**
30848   * Create a secure random MPI that is greater than or equal to min and less than max.
30849   * @param {module:type/mpi} min Lower bound, included
30850   * @param {module:type/mpi} max Upper bound, excluded
30851   * @returns {module:BN} Random MPI
30852   * @async
30853   */
30854  getRandomBN: async function getRandomBN(min, max) {
30855    if (max.cmp(min) <= 0) {
30856      throw new Error('Illegal parameter value: max <= min');
30857    }
30858
30859    const modulus = max.sub(min);
30860    const bytes = modulus.byteLength();
30861
30862    // Using a while loop is necessary to avoid bias introduced by the mod operation.
30863    // However, we request 64 extra random bits so that the bias is negligible.
30864    // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
30865    const r = new _bn2.default((await this.getRandomBytes(bytes + 8)));
30866    return r.mod(modulus).add(min);
30867  },
30868
30869  randomBuffer: new RandomBuffer()
30870};
30871
30872/**
30873 * Buffer for secure random numbers
30874 */
30875
30876function RandomBuffer() {
30877  this.buffer = null;
30878  this.size = null;
30879  this.callback = null;
30880}
30881
30882/**
30883 * Initialize buffer
30884 * @param  {Integer} size size of buffer
30885 */
30886RandomBuffer.prototype.init = function (size, callback) {
30887  this.buffer = new Uint8Array(size);
30888  this.size = 0;
30889  this.callback = callback;
30890};
30891
30892/**
30893 * Concat array of secure random numbers to buffer
30894 * @param {Uint8Array} buf
30895 */
30896RandomBuffer.prototype.set = function (buf) {
30897  if (!this.buffer) {
30898    throw new Error('RandomBuffer is not initialized');
30899  }
30900  if (!(buf instanceof Uint8Array)) {
30901    throw new Error('Invalid type: buf not an Uint8Array');
30902  }
30903  const freeSpace = this.buffer.length - this.size;
30904  if (buf.length > freeSpace) {
30905    buf = buf.subarray(0, freeSpace);
30906  }
30907  // set buf with offset old size of buffer
30908  this.buffer.set(buf, this.size);
30909  this.size += buf.length;
30910};
30911
30912/**
30913 * Take numbers out of buffer and copy to array
30914 * @param {Uint8Array} buf the destination array
30915 */
30916RandomBuffer.prototype.get = async function (buf) {
30917  if (!this.buffer) {
30918    throw new Error('RandomBuffer is not initialized');
30919  }
30920  if (!(buf instanceof Uint8Array)) {
30921    throw new Error('Invalid type: buf not an Uint8Array');
30922  }
30923  if (this.size < buf.length) {
30924    if (!this.callback) {
30925      throw new Error('Random number buffer depleted');
30926    }
30927    // Wait for random bytes from main context, then try again
30928    await this.callback();
30929    return this.get(buf);
30930  }
30931  for (let i = 0; i < buf.length; i++) {
30932    buf[i] = this.buffer[--this.size];
30933    // clear buffer value
30934    this.buffer[this.size] = 0;
30935  }
30936};
30937
30938},{"../util":153,"bn.js":17,"crypto":"crypto"}],111:[function(require,module,exports){
30939'use strict';
30940
30941Object.defineProperty(exports, "__esModule", {
30942  value: true
30943});
30944
30945var _bn = require('bn.js');
30946
30947var _bn2 = _interopRequireDefault(_bn);
30948
30949var _crypto = require('./crypto');
30950
30951var _crypto2 = _interopRequireDefault(_crypto);
30952
30953var _public_key = require('./public_key');
30954
30955var _public_key2 = _interopRequireDefault(_public_key);
30956
30957var _pkcs = require('./pkcs1');
30958
30959var _pkcs2 = _interopRequireDefault(_pkcs);
30960
30961var _enums = require('../enums');
30962
30963var _enums2 = _interopRequireDefault(_enums);
30964
30965var _util = require('../util');
30966
30967var _util2 = _interopRequireDefault(_util);
30968
30969function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30970
30971/**
30972 * @fileoverview Provides functions for asymmetric signing and signature verification
30973 * @requires bn.js
30974 * @requires crypto/crypto
30975 * @requires crypto/public_key
30976 * @requires crypto/pkcs1
30977 * @requires enums
30978 * @requires util
30979 * @module crypto/signature
30980*/
30981
30982exports.default = {
30983  /**
30984   * Verifies the signature provided for data using specified algorithms and public key parameters.
30985   * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
30986   * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
30987   * for public key and hash algorithms.
30988   * @param {module:enums.publicKey} algo      Public key algorithm
30989   * @param {module:enums.hash}      hash_algo Hash algorithm
30990   * @param {Array<module:type/mpi>} msg_MPIs  Algorithm-specific signature parameters
30991   * @param {Array<module:type/mpi>} pub_MPIs  Algorithm-specific public key parameters
30992   * @param {Uint8Array}             data      Data for which the signature was created
30993   * @param {Uint8Array}             hashed    The hashed data
30994   * @returns {Boolean}                        True if signature is valid
30995   * @async
30996   */
30997  verify: async function verify(algo, hash_algo, msg_MPIs, pub_MPIs, data, hashed) {
30998    const types = _crypto2.default.getPubKeyParamTypes(algo);
30999    if (pub_MPIs.length < types.length) {
31000      throw new Error('Missing public key parameters');
31001    }
31002    switch (algo) {
31003      case _enums2.default.publicKey.rsa_encrypt_sign:
31004      case _enums2.default.publicKey.rsa_encrypt:
31005      case _enums2.default.publicKey.rsa_sign:
31006        {
31007          const m = msg_MPIs[0].toBN();
31008          const n = pub_MPIs[0].toBN();
31009          const e = pub_MPIs[1].toBN();
31010          const EM = await _public_key2.default.rsa.verify(m, n, e);
31011          const EM2 = await _pkcs2.default.emsa.encode(hash_algo, hashed, n.byteLength());
31012          return _util2.default.Uint8Array_to_hex(EM) === EM2;
31013        }
31014      case _enums2.default.publicKey.dsa:
31015        {
31016          const r = msg_MPIs[0].toBN();
31017          const s = msg_MPIs[1].toBN();
31018          const p = pub_MPIs[0].toBN();
31019          const q = pub_MPIs[1].toBN();
31020          const g = pub_MPIs[2].toBN();
31021          const y = pub_MPIs[3].toBN();
31022          return _public_key2.default.dsa.verify(hash_algo, r, s, hashed, g, p, q, y);
31023        }
31024      case _enums2.default.publicKey.ecdsa:
31025        {
31026          const oid = pub_MPIs[0];
31027          const signature = { r: msg_MPIs[0].toUint8Array(), s: msg_MPIs[1].toUint8Array() };
31028          const Q = pub_MPIs[1].toUint8Array();
31029          return _public_key2.default.elliptic.ecdsa.verify(oid, hash_algo, signature, data, Q, hashed);
31030        }
31031      case _enums2.default.publicKey.eddsa:
31032        {
31033          const oid = pub_MPIs[0];
31034          // EdDSA signature params are expected in little-endian format
31035          const signature = { R: msg_MPIs[0].toUint8Array('le', 32),
31036            S: msg_MPIs[1].toUint8Array('le', 32) };
31037          const Q = pub_MPIs[1].toUint8Array('be', 33);
31038          return _public_key2.default.elliptic.eddsa.verify(oid, hash_algo, signature, data, Q, hashed);
31039        }
31040      default:
31041        throw new Error('Invalid signature algorithm.');
31042    }
31043  },
31044
31045  /**
31046   * Creates a signature on data using specified algorithms and private key parameters.
31047   * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
31048   * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
31049   * for public key and hash algorithms.
31050   * @param {module:enums.publicKey} algo       Public key algorithm
31051   * @param {module:enums.hash}      hash_algo  Hash algorithm
31052   * @param {Array<module:type/mpi>} key_params Algorithm-specific public and private key parameters
31053   * @param {Uint8Array}             data       Data to be signed
31054   * @param {Uint8Array}             hashed     The hashed data
31055   * @returns {Uint8Array}                      Signature
31056   * @async
31057   */
31058  sign: async function sign(algo, hash_algo, key_params, data, hashed) {
31059    const types = [].concat(_crypto2.default.getPubKeyParamTypes(algo), _crypto2.default.getPrivKeyParamTypes(algo));
31060    if (key_params.length < types.length) {
31061      throw new Error('Missing private key parameters');
31062    }
31063    switch (algo) {
31064      case _enums2.default.publicKey.rsa_encrypt_sign:
31065      case _enums2.default.publicKey.rsa_encrypt:
31066      case _enums2.default.publicKey.rsa_sign:
31067        {
31068          const n = key_params[0].toBN();
31069          const e = key_params[1].toBN();
31070          const d = key_params[2].toBN();
31071          const m = new _bn2.default((await _pkcs2.default.emsa.encode(hash_algo, hashed, n.byteLength())), 16);
31072          const signature = await _public_key2.default.rsa.sign(m, n, e, d);
31073          return _util2.default.Uint8Array_to_MPI(signature);
31074        }
31075      case _enums2.default.publicKey.dsa:
31076        {
31077          const p = key_params[0].toBN();
31078          const q = key_params[1].toBN();
31079          const g = key_params[2].toBN();
31080          const x = key_params[4].toBN();
31081          const signature = await _public_key2.default.dsa.sign(hash_algo, hashed, g, p, q, x);
31082          return _util2.default.concatUint8Array([_util2.default.Uint8Array_to_MPI(signature.r), _util2.default.Uint8Array_to_MPI(signature.s)]);
31083        }
31084      case _enums2.default.publicKey.elgamal:
31085        {
31086          throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');
31087        }
31088      case _enums2.default.publicKey.ecdsa:
31089        {
31090          const oid = key_params[0];
31091          const d = key_params[2].toUint8Array();
31092          const signature = await _public_key2.default.elliptic.ecdsa.sign(oid, hash_algo, data, d, hashed);
31093          return _util2.default.concatUint8Array([_util2.default.Uint8Array_to_MPI(signature.r), _util2.default.Uint8Array_to_MPI(signature.s)]);
31094        }
31095      case _enums2.default.publicKey.eddsa:
31096        {
31097          const oid = key_params[0];
31098          const d = key_params[2].toUint8Array('be', 32);
31099          const signature = await _public_key2.default.elliptic.eddsa.sign(oid, hash_algo, data, d, hashed);
31100          return _util2.default.concatUint8Array([_util2.default.Uint8Array_to_MPI(signature.R), _util2.default.Uint8Array_to_MPI(signature.S)]);
31101        }
31102      default:
31103        throw new Error('Invalid signature algorithm.');
31104    }
31105  }
31106};
31107
31108},{"../enums":114,"../util":153,"./crypto":90,"./pkcs1":97,"./public_key":107,"bn.js":17}],112:[function(require,module,exports){
31109'use strict';
31110
31111Object.defineProperty(exports, "__esModule", {
31112  value: true
31113});
31114
31115var _webStreamTools = require('web-stream-tools');
31116
31117var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
31118
31119var _base = require('./base64.js');
31120
31121var _base2 = _interopRequireDefault(_base);
31122
31123var _enums = require('../enums.js');
31124
31125var _enums2 = _interopRequireDefault(_enums);
31126
31127var _config = require('../config');
31128
31129var _config2 = _interopRequireDefault(_config);
31130
31131var _util = require('../util');
31132
31133var _util2 = _interopRequireDefault(_util);
31134
31135function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
31136
31137/**
31138 * Finds out which Ascii Armoring type is used. Throws error if unknown type.
31139 * @private
31140 * @param {String} text [String] ascii armored text
31141 * @returns {Integer} 0 = MESSAGE PART n of m
31142 *         1 = MESSAGE PART n
31143 *         2 = SIGNED MESSAGE
31144 *         3 = PGP MESSAGE
31145 *         4 = PUBLIC KEY BLOCK
31146 *         5 = PRIVATE KEY BLOCK
31147 *         6 = SIGNATURE
31148 */
31149function getType(text) {
31150  const reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;
31151
31152  const header = text.match(reHeader);
31153
31154  if (!header) {
31155    throw new Error('Unknown ASCII armor type');
31156  }
31157
31158  // BEGIN PGP MESSAGE, PART X/Y
31159  // Used for multi-part messages, where the armor is split amongst Y
31160  // parts, and this is the Xth part out of Y.
31161  if (/MESSAGE, PART \d+\/\d+/.test(header[1])) {
31162    return _enums2.default.armor.multipart_section;
31163  } else
31164    // BEGIN PGP MESSAGE, PART X
31165    // Used for multi-part messages, where this is the Xth part of an
31166    // unspecified number of parts. Requires the MESSAGE-ID Armor
31167    // Header to be used.
31168    if (/MESSAGE, PART \d+/.test(header[1])) {
31169      return _enums2.default.armor.multipart_last;
31170    } else
31171      // BEGIN PGP SIGNED MESSAGE
31172      if (/SIGNED MESSAGE/.test(header[1])) {
31173        return _enums2.default.armor.signed;
31174      } else
31175        // BEGIN PGP MESSAGE
31176        // Used for signed, encrypted, or compressed files.
31177        if (/MESSAGE/.test(header[1])) {
31178          return _enums2.default.armor.message;
31179        } else
31180          // BEGIN PGP PUBLIC KEY BLOCK
31181          // Used for armoring public keys.
31182          if (/PUBLIC KEY BLOCK/.test(header[1])) {
31183            return _enums2.default.armor.public_key;
31184          } else
31185            // BEGIN PGP PRIVATE KEY BLOCK
31186            // Used for armoring private keys.
31187            if (/PRIVATE KEY BLOCK/.test(header[1])) {
31188              return _enums2.default.armor.private_key;
31189            } else
31190              // BEGIN PGP SIGNATURE
31191              // Used for detached signatures, OpenPGP/MIME signatures, and
31192              // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE
31193              // for detached signatures.
31194              if (/SIGNATURE/.test(header[1])) {
31195                return _enums2.default.armor.signature;
31196              }
31197}
31198
31199/**
31200 * Add additional information to the armor version of an OpenPGP binary
31201 * packet block.
31202 * @author  Alex
31203 * @version 2011-12-16
31204 * @param {String} customComment (optional) additional comment to add to the armored string
31205 * @returns {String} The header information
31206 */
31207// GPG4Browsers - An OpenPGP implementation in javascript
31208// Copyright (C) 2011 Recurity Labs GmbH
31209//
31210// This library is free software; you can redistribute it and/or
31211// modify it under the terms of the GNU Lesser General Public
31212// License as published by the Free Software Foundation; either
31213// version 3.0 of the License, or (at your option) any later version.
31214//
31215// This library is distributed in the hope that it will be useful,
31216// but WITHOUT ANY WARRANTY; without even the implied warranty of
31217// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
31218// Lesser General Public License for more details.
31219//
31220// You should have received a copy of the GNU Lesser General Public
31221// License along with this library; if not, write to the Free Software
31222// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
31223
31224/**
31225 * @requires web-stream-tools
31226 * @requires encoding/base64
31227 * @requires enums
31228 * @requires config
31229 * @requires util
31230 * @module encoding/armor
31231 */
31232
31233function addheader(customComment) {
31234  let result = "";
31235  if (_config2.default.show_version) {
31236    result += "Version: " + _config2.default.versionstring + '\r\n';
31237  }
31238  if (_config2.default.show_comment) {
31239    result += "Comment: " + _config2.default.commentstring + '\r\n';
31240  }
31241  if (customComment) {
31242    result += "Comment: " + customComment + '\r\n';
31243  }
31244  result += '\r\n';
31245  return result;
31246}
31247
31248/**
31249 * Calculates a checksum over the given data and returns it base64 encoded
31250 * @param {String | ReadableStream<String>} data Data to create a CRC-24 checksum for
31251 * @returns {String | ReadableStream<String>} Base64 encoded checksum
31252 */
31253function getCheckSum(data) {
31254  const crc = createcrc24(data);
31255  return _base2.default.encode(crc);
31256}
31257
31258const crc_table = [0x00000000, 0x00864cfb, 0x018ad50d, 0x010c99f6, 0x0393e6e1, 0x0315aa1a, 0x021933ec, 0x029f7f17, 0x07a18139, 0x0727cdc2, 0x062b5434, 0x06ad18cf, 0x043267d8, 0x04b42b23, 0x05b8b2d5, 0x053efe2e, 0x0fc54e89, 0x0f430272, 0x0e4f9b84, 0x0ec9d77f, 0x0c56a868, 0x0cd0e493, 0x0ddc7d65, 0x0d5a319e, 0x0864cfb0, 0x08e2834b, 0x09ee1abd, 0x09685646, 0x0bf72951, 0x0b7165aa, 0x0a7dfc5c, 0x0afbb0a7, 0x1f0cd1e9, 0x1f8a9d12, 0x1e8604e4, 0x1e00481f, 0x1c9f3708, 0x1c197bf3, 0x1d15e205, 0x1d93aefe, 0x18ad50d0, 0x182b1c2b, 0x192785dd, 0x19a1c926, 0x1b3eb631, 0x1bb8faca, 0x1ab4633c, 0x1a322fc7, 0x10c99f60, 0x104fd39b, 0x11434a6d, 0x11c50696, 0x135a7981, 0x13dc357a, 0x12d0ac8c, 0x1256e077, 0x17681e59, 0x17ee52a2, 0x16e2cb54, 0x166487af, 0x14fbf8b8, 0x147db443, 0x15712db5, 0x15f7614e, 0x3e19a3d2, 0x3e9fef29, 0x3f9376df, 0x3f153a24, 0x3d8a4533, 0x3d0c09c8, 0x3c00903e, 0x3c86dcc5, 0x39b822eb, 0x393e6e10, 0x3832f7e6, 0x38b4bb1d, 0x3a2bc40a, 0x3aad88f1, 0x3ba11107, 0x3b275dfc, 0x31dced5b, 0x315aa1a0, 0x30563856, 0x30d074ad, 0x324f0bba, 0x32c94741, 0x33c5deb7, 0x3343924c, 0x367d6c62, 0x36fb2099, 0x37f7b96f, 0x3771f594, 0x35ee8a83, 0x3568c678, 0x34645f8e, 0x34e21375, 0x2115723b, 0x21933ec0, 0x209fa736, 0x2019ebcd, 0x228694da, 0x2200d821, 0x230c41d7, 0x238a0d2c, 0x26b4f302, 0x2632bff9, 0x273e260f, 0x27b86af4, 0x252715e3, 0x25a15918, 0x24adc0ee, 0x242b8c15, 0x2ed03cb2, 0x2e567049, 0x2f5ae9bf, 0x2fdca544, 0x2d43da53, 0x2dc596a8, 0x2cc90f5e, 0x2c4f43a5, 0x2971bd8b, 0x29f7f170, 0x28fb6886, 0x287d247d, 0x2ae25b6a, 0x2a641791, 0x2b688e67, 0x2beec29c, 0x7c3347a4, 0x7cb50b5f, 0x7db992a9, 0x7d3fde52, 0x7fa0a145, 0x7f26edbe, 0x7e2a7448, 0x7eac38b3, 0x7b92c69d, 0x7b148a66, 0x7a181390, 0x7a9e5f6b, 0x7801207c, 0x78876c87, 0x798bf571, 0x790db98a, 0x73f6092d, 0x737045d6, 0x727cdc20, 0x72fa90db, 0x7065efcc, 0x70e3a337, 0x71ef3ac1, 0x7169763a, 0x74578814, 0x74d1c4ef, 0x75dd5d19, 0x755b11e2, 0x77c46ef5, 0x7742220e, 0x764ebbf8, 0x76c8f703, 0x633f964d, 0x63b9dab6, 0x62b54340, 0x62330fbb, 0x60ac70ac, 0x602a3c57, 0x6126a5a1, 0x61a0e95a, 0x649e1774, 0x64185b8f, 0x6514c279, 0x65928e82, 0x670df195, 0x678bbd6e, 0x66872498, 0x66016863, 0x6cfad8c4, 0x6c7c943f, 0x6d700dc9, 0x6df64132, 0x6f693e25, 0x6fef72de, 0x6ee3eb28, 0x6e65a7d3, 0x6b5b59fd, 0x6bdd1506, 0x6ad18cf0, 0x6a57c00b, 0x68c8bf1c, 0x684ef3e7, 0x69426a11, 0x69c426ea, 0x422ae476, 0x42aca88d, 0x43a0317b, 0x43267d80, 0x41b90297, 0x413f4e6c, 0x4033d79a, 0x40b59b61, 0x458b654f, 0x450d29b4, 0x4401b042, 0x4487fcb9, 0x461883ae, 0x469ecf55, 0x479256a3, 0x47141a58, 0x4defaaff, 0x4d69e604, 0x4c657ff2, 0x4ce33309, 0x4e7c4c1e, 0x4efa00e5, 0x4ff69913, 0x4f70d5e8, 0x4a4e2bc6, 0x4ac8673d, 0x4bc4fecb, 0x4b42b230, 0x49ddcd27, 0x495b81dc, 0x4857182a, 0x48d154d1, 0x5d26359f, 0x5da07964, 0x5cace092, 0x5c2aac69, 0x5eb5d37e, 0x5e339f85, 0x5f3f0673, 0x5fb94a88, 0x5a87b4a6, 0x5a01f85d, 0x5b0d61ab, 0x5b8b2d50, 0x59145247, 0x59921ebc, 0x589e874a, 0x5818cbb1, 0x52e37b16, 0x526537ed, 0x5369ae1b, 0x53efe2e0, 0x51709df7, 0x51f6d10c, 0x50fa48fa, 0x507c0401, 0x5542fa2f, 0x55c4b6d4, 0x54c82f22, 0x544e63d9, 0x56d11cce, 0x56575035, 0x575bc9c3, 0x57dd8538];
31259
31260/**
31261 * Internal function to calculate a CRC-24 checksum over a given string (data)
31262 * @param {String | ReadableStream<String>} data Data to create a CRC-24 checksum for
31263 * @returns {Uint8Array | ReadableStream<Uint8Array>} The CRC-24 checksum
31264 */
31265function createcrc24(input) {
31266  let crc = 0xB704CE;
31267  return _webStreamTools2.default.transform(input, value => {
31268    for (let index = 0; index < value.length; index++) {
31269      crc = crc << 8 ^ crc_table[(crc >> 16 ^ value[index]) & 0xff];
31270    }
31271  }, () => new Uint8Array([crc >> 16, crc >> 8, crc]));
31272}
31273
31274/**
31275 * Verify armored headers. RFC4880, section 6.3: "OpenPGP should consider improperly formatted
31276 * Armor Headers to be corruption of the ASCII Armor."
31277 * @private
31278 * @param  {Array<String>} headers Armor headers
31279 */
31280function verifyHeaders(headers) {
31281  for (let i = 0; i < headers.length; i++) {
31282    if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) {
31283      throw new Error('Improperly formatted armor header: ' + headers[i]);
31284    }
31285    if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {
31286      _util2.default.print_debug_error(new Error('Unknown header: ' + headers[i]));
31287    }
31288  }
31289}
31290
31291/**
31292 * Splits a message into two parts, the body and the checksum. This is an internal function
31293 * @param {String} text OpenPGP armored message part
31294 * @returns {Object} An object with attribute "body" containing the body
31295 * and an attribute "checksum" containing the checksum.
31296 */
31297function splitChecksum(text) {
31298  let body = text;
31299  let checksum = "";
31300
31301  const lastEquals = text.lastIndexOf("=");
31302
31303  if (lastEquals >= 0 && lastEquals !== text.length - 1) {
31304    // '=' as the last char means no checksum
31305    body = text.slice(0, lastEquals);
31306    checksum = text.slice(lastEquals + 1).substr(0, 4);
31307  }
31308
31309  return { body: body, checksum: checksum };
31310}
31311
31312/**
31313 * DeArmor an OpenPGP armored message; verify the checksum and return
31314 * the encoded bytes
31315 * @param {String} text OpenPGP armored message
31316 * @returns {Promise<Object>} An object with attribute "text" containing the message text,
31317 * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type
31318 * @async
31319 * @static
31320 */
31321function dearmor(input) {
31322  return new Promise(async (resolve, reject) => {
31323    try {
31324      const reSplit = /^-----[^-]+-----$/m;
31325      const reEmptyLine = /^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;
31326
31327      let type;
31328      const headers = [];
31329      let lastHeaders = headers;
31330      let headersDone;
31331      let text = [];
31332      let textDone;
31333      let checksum;
31334      let data = _base2.default.decode(_webStreamTools2.default.transformPair(input, async (readable, writable) => {
31335        const reader = _webStreamTools2.default.getReader(readable);
31336        try {
31337          while (true) {
31338            let line = await reader.readLine();
31339            if (line === undefined) {
31340              throw new Error('Misformed armored text');
31341            }
31342            // remove trailing whitespace at end of lines
31343            line = _util2.default.removeTrailingSpaces(line.replace(/[\r\n]/g, ''));
31344            if (!type) {
31345              if (reSplit.test(line)) {
31346                type = getType(line);
31347              }
31348            } else if (!headersDone) {
31349              if (reSplit.test(line)) {
31350                reject(new Error('Mandatory blank line missing between armor headers and armor data'));
31351              }
31352              if (!reEmptyLine.test(line)) {
31353                lastHeaders.push(line);
31354              } else {
31355                verifyHeaders(lastHeaders);
31356                headersDone = true;
31357                if (textDone || type !== 2) {
31358                  resolve({ text, data, headers, type });
31359                  break;
31360                }
31361              }
31362            } else if (!textDone && type === 2) {
31363              if (!reSplit.test(line)) {
31364                // Reverse dash-escaping for msg
31365                text.push(line.replace(/^- /, ''));
31366              } else {
31367                text = text.join('\r\n');
31368                textDone = true;
31369                verifyHeaders(lastHeaders);
31370                lastHeaders = [];
31371                headersDone = false;
31372              }
31373            }
31374          }
31375        } catch (e) {
31376          reject(e);
31377          return;
31378        }
31379        const writer = _webStreamTools2.default.getWriter(writable);
31380        try {
31381          while (true) {
31382            await writer.ready;
31383
31384            var _ref = await reader.read();
31385
31386            const done = _ref.done,
31387                  value = _ref.value;
31388
31389            if (done) {
31390              throw new Error('Misformed armored text');
31391            }
31392            const line = value + '';
31393            if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {
31394              await writer.write(line);
31395            } else {
31396              let remainder = await reader.readToEnd();
31397              if (!remainder.length) remainder = '';
31398              remainder = line + remainder;
31399              remainder = _util2.default.removeTrailingSpaces(remainder.replace(/\r/g, ''));
31400              const parts = remainder.split(reSplit);
31401              if (parts.length === 1) {
31402                throw new Error('Misformed armored text');
31403              }
31404              const split = splitChecksum(parts[0].slice(0, -1));
31405              checksum = split.checksum;
31406              await writer.write(split.body);
31407              break;
31408            }
31409          }
31410          await writer.ready;
31411          await writer.close();
31412        } catch (e) {
31413          await writer.abort(e);
31414        }
31415      }));
31416      data = _webStreamTools2.default.transformPair(data, async (readable, writable) => {
31417        const checksumVerified = getCheckSum(_webStreamTools2.default.passiveClone(readable));
31418        await _webStreamTools2.default.pipe(readable, writable, {
31419          preventClose: true
31420        });
31421        const writer = _webStreamTools2.default.getWriter(writable);
31422        try {
31423          const checksumVerifiedString = await _webStreamTools2.default.readToEnd(checksumVerified);
31424          if (checksum !== checksumVerifiedString && (checksum || _config2.default.checksum_required)) {
31425            throw new Error("Ascii armor integrity check on message failed: '" + checksum + "' should be '" + checksumVerifiedString + "'");
31426          }
31427          await writer.ready;
31428          await writer.close();
31429        } catch (e) {
31430          await writer.abort(e);
31431        }
31432      });
31433    } catch (e) {
31434      reject(e);
31435    }
31436  });
31437}
31438
31439/**
31440 * Armor an OpenPGP binary packet block
31441 * @param {Integer} messagetype type of the message
31442 * @param body
31443 * @param {Integer} partindex
31444 * @param {Integer} parttotal
31445 * @param {String} customComment (optional) additional comment to add to the armored string
31446 * @returns {String | ReadableStream<String>} Armored text
31447 * @static
31448 */
31449function armor(messagetype, body, partindex, parttotal, customComment) {
31450  let text;
31451  let hash;
31452  if (messagetype === _enums2.default.armor.signed) {
31453    text = body.text;
31454    hash = body.hash;
31455    body = body.data;
31456  }
31457  const bodyClone = _webStreamTools2.default.passiveClone(body);
31458  const result = [];
31459  switch (messagetype) {
31460    case _enums2.default.armor.multipart_section:
31461      result.push("-----BEGIN PGP MESSAGE, PART " + partindex + "/" + parttotal + "-----\r\n");
31462      result.push(addheader(customComment));
31463      result.push(_base2.default.encode(body));
31464      result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
31465      result.push("-----END PGP MESSAGE, PART " + partindex + "/" + parttotal + "-----\r\n");
31466      break;
31467    case _enums2.default.armor.multipart_last:
31468      result.push("-----BEGIN PGP MESSAGE, PART " + partindex + "-----\r\n");
31469      result.push(addheader(customComment));
31470      result.push(_base2.default.encode(body));
31471      result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
31472      result.push("-----END PGP MESSAGE, PART " + partindex + "-----\r\n");
31473      break;
31474    case _enums2.default.armor.signed:
31475      result.push("\r\n-----BEGIN PGP SIGNED MESSAGE-----\r\n");
31476      result.push("Hash: " + hash + "\r\n\r\n");
31477      result.push(text.replace(/^-/mg, "- -"));
31478      result.push("\r\n-----BEGIN PGP SIGNATURE-----\r\n");
31479      result.push(addheader(customComment));
31480      result.push(_base2.default.encode(body));
31481      result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
31482      result.push("-----END PGP SIGNATURE-----\r\n");
31483      break;
31484    case _enums2.default.armor.message:
31485      result.push("-----BEGIN PGP MESSAGE-----\r\n");
31486      result.push(addheader(customComment));
31487      result.push(_base2.default.encode(body));
31488      result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
31489      result.push("-----END PGP MESSAGE-----\r\n");
31490      break;
31491    case _enums2.default.armor.public_key:
31492      result.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\r\n");
31493      result.push(addheader(customComment));
31494      result.push(_base2.default.encode(body));
31495      result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
31496      result.push("-----END PGP PUBLIC KEY BLOCK-----\r\n");
31497      break;
31498    case _enums2.default.armor.private_key:
31499      result.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\r\n");
31500      result.push(addheader(customComment));
31501      result.push(_base2.default.encode(body));
31502      result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
31503      result.push("-----END PGP PRIVATE KEY BLOCK-----\r\n");
31504      break;
31505    case _enums2.default.armor.signature:
31506      result.push("-----BEGIN PGP SIGNATURE-----\r\n");
31507      result.push(addheader(customComment));
31508      result.push(_base2.default.encode(body));
31509      result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
31510      result.push("-----END PGP SIGNATURE-----\r\n");
31511      break;
31512  }
31513
31514  return _util2.default.concat(result);
31515}
31516
31517exports.default = {
31518  encode: armor,
31519  decode: dearmor
31520};
31521
31522},{"../config":80,"../enums.js":114,"../util":153,"./base64.js":113,"web-stream-tools":76}],113:[function(require,module,exports){
31523'use strict';
31524
31525Object.defineProperty(exports, "__esModule", {
31526  value: true
31527});
31528
31529var _webStreamTools = require('web-stream-tools');
31530
31531var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
31532
31533function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
31534
31535const b64s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Standard radix-64
31536/* OpenPGP radix-64/base64 string encoding/decoding
31537 * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de
31538 * version 1.0, check www.haneWIN.de for the latest version
31539 *
31540 * This software is provided as-is, without express or implied warranty.
31541 * Permission to use, copy, modify, distribute or sell this software, with or
31542 * without fee, for any purpose and by any individual or organization, is hereby
31543 * granted, provided that the above copyright notice and this paragraph appear
31544 * in all copies. Distribution as a part of an application or binary must
31545 * include the above copyright notice in the documentation and/or other materials
31546 * provided with the application or distribution.
31547 */
31548
31549/**
31550 * @requires web-stream-tools
31551 * @module encoding/base64
31552 */
31553
31554const b64u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; // URL-safe radix-64
31555
31556const b64toByte = [];
31557for (let i = 0; i < b64s.length; i++) {
31558  b64toByte[b64s.charCodeAt(i)] = i;
31559}
31560b64toByte[b64u.charCodeAt(62)] = 62;
31561b64toByte[b64u.charCodeAt(63)] = 63;
31562
31563/**
31564 * Convert binary array to radix-64
31565 * @param {Uint8Array | ReadableStream<Uint8Array>} t Uint8Array to convert
31566 * @param {bool} u if true, output is URL-safe
31567 * @returns {String | ReadableStream<String>} radix-64 version of input string
31568 * @static
31569 */
31570function s2r(t, u = false) {
31571  // TODO check btoa alternative
31572  const b64 = u ? b64u : b64s;
31573  let a;
31574  let c;
31575
31576  let l = 0;
31577  let s = 0;
31578
31579  return _webStreamTools2.default.transform(t, value => {
31580    const r = [];
31581    const tl = value.length;
31582    for (let n = 0; n < tl; n++) {
31583      if (l && l % 60 === 0 && !u) {
31584        r.push("\r\n");
31585      }
31586      c = value[n];
31587      if (s === 0) {
31588        r.push(b64.charAt(c >> 2 & 63));
31589        a = (c & 3) << 4;
31590      } else if (s === 1) {
31591        r.push(b64.charAt(a | c >> 4 & 15));
31592        a = (c & 15) << 2;
31593      } else if (s === 2) {
31594        r.push(b64.charAt(a | c >> 6 & 3));
31595        l += 1;
31596        if (l % 60 === 0 && !u) {
31597          r.push("\r\n");
31598        }
31599        r.push(b64.charAt(c & 63));
31600      }
31601      l += 1;
31602      s += 1;
31603      if (s === 3) {
31604        s = 0;
31605      }
31606    }
31607    return r.join('');
31608  }, () => {
31609    const r = [];
31610    if (s > 0) {
31611      r.push(b64.charAt(a));
31612      l += 1;
31613      if (l % 60 === 0 && !u) {
31614        r.push("\r\n");
31615      }
31616      if (!u) {
31617        r.push('=');
31618        l += 1;
31619      }
31620    }
31621    if (s === 1 && !u) {
31622      if (l % 60 === 0 && !u) {
31623        r.push("\r\n");
31624      }
31625      r.push('=');
31626    }
31627    return r.join('');
31628  });
31629}
31630
31631/**
31632 * Convert radix-64 to binary array
31633 * @param {String | ReadableStream<String>} t radix-64 string to convert
31634 * @param {bool} u if true, input is interpreted as URL-safe
31635 * @returns {Uint8Array | ReadableStream<Uint8Array>} binary array version of input string
31636 * @static
31637 */
31638function r2s(t, u) {
31639  // TODO check atob alternative
31640  let c;
31641
31642  let s = 0;
31643  let a = 0;
31644
31645  return _webStreamTools2.default.transform(t, value => {
31646    const tl = value.length;
31647    const r = new Uint8Array(Math.ceil(0.75 * tl));
31648    let index = 0;
31649    for (let n = 0; n < tl; n++) {
31650      c = b64toByte[value.charCodeAt(n)];
31651      if (c >= 0) {
31652        if (s) {
31653          r[index++] = a | c >> 6 - s & 255;
31654        }
31655        s = s + 2 & 7;
31656        a = c << s & 255;
31657      }
31658    }
31659    return r.subarray(0, index);
31660  });
31661}
31662
31663exports.default = {
31664  encode: s2r,
31665  decode: r2s
31666};
31667
31668},{"web-stream-tools":76}],114:[function(require,module,exports){
31669"use strict";
31670
31671Object.defineProperty(exports, "__esModule", {
31672  value: true
31673});
31674/**
31675 * @module enums
31676 */
31677
31678const byValue = Symbol('byValue');
31679
31680exports.default = {
31681
31682  /** Maps curve names under various standards to one
31683   * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}
31684   * @enum {String}
31685   * @readonly
31686   */
31687  curve: {
31688    /** NIST P-256 Curve */
31689    "p256": "p256",
31690    "P-256": "p256",
31691    "secp256r1": "p256",
31692    "prime256v1": "p256",
31693    "1.2.840.10045.3.1.7": "p256",
31694    "2a8648ce3d030107": "p256",
31695    "2A8648CE3D030107": "p256",
31696
31697    /** NIST P-384 Curve */
31698    "p384": "p384",
31699    "P-384": "p384",
31700    "secp384r1": "p384",
31701    "1.3.132.0.34": "p384",
31702    "2b81040022": "p384",
31703    "2B81040022": "p384",
31704
31705    /** NIST P-521 Curve */
31706    "p521": "p521",
31707    "P-521": "p521",
31708    "secp521r1": "p521",
31709    "1.3.132.0.35": "p521",
31710    "2b81040023": "p521",
31711    "2B81040023": "p521",
31712
31713    /** SECG SECP256k1 Curve */
31714    "secp256k1": "secp256k1",
31715    "1.3.132.0.10": "secp256k1",
31716    "2b8104000a": "secp256k1",
31717    "2B8104000A": "secp256k1",
31718
31719    /** Ed25519 */
31720    "ED25519": "ed25519",
31721    "ed25519": "ed25519",
31722    "Ed25519": "ed25519",
31723    "1.3.6.1.4.1.11591.15.1": "ed25519",
31724    "2b06010401da470f01": "ed25519",
31725    "2B06010401DA470F01": "ed25519",
31726
31727    /** Curve25519 */
31728    "X25519": "curve25519",
31729    "cv25519": "curve25519",
31730    "curve25519": "curve25519",
31731    "Curve25519": "curve25519",
31732    "1.3.6.1.4.1.3029.1.5.1": "curve25519",
31733    "2b060104019755010501": "curve25519",
31734    "2B060104019755010501": "curve25519",
31735
31736    /** BrainpoolP256r1 Curve */
31737    "brainpoolP256r1": "brainpoolP256r1",
31738    "1.3.36.3.3.2.8.1.1.7": "brainpoolP256r1",
31739    "2b2403030208010107": "brainpoolP256r1",
31740    "2B2403030208010107": "brainpoolP256r1",
31741
31742    /** BrainpoolP384r1 Curve */
31743    "brainpoolP384r1": "brainpoolP384r1",
31744    "1.3.36.3.3.2.8.1.1.11": "brainpoolP384r1",
31745    "2b240303020801010b": "brainpoolP384r1",
31746    "2B240303020801010B": "brainpoolP384r1",
31747
31748    /** BrainpoolP512r1 Curve */
31749    "brainpoolP512r1": "brainpoolP512r1",
31750    "1.3.36.3.3.2.8.1.1.13": "brainpoolP512r1",
31751    "2b240303020801010d": "brainpoolP512r1",
31752    "2B240303020801010D": "brainpoolP512r1"
31753  },
31754
31755  /** A string to key specifier type
31756   * @enum {Integer}
31757   * @readonly
31758   */
31759  s2k: {
31760    simple: 0,
31761    salted: 1,
31762    iterated: 3,
31763    gnu: 101
31764  },
31765
31766  /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.1|RFC4880bis-04, section 9.1}
31767   * @enum {Integer}
31768   * @readonly
31769   */
31770  publicKey: {
31771    /** RSA (Encrypt or Sign) [HAC] */
31772    rsa_encrypt_sign: 1,
31773    /** RSA (Encrypt only) [HAC] */
31774    rsa_encrypt: 2,
31775    /** RSA (Sign only) [HAC] */
31776    rsa_sign: 3,
31777    /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */
31778    elgamal: 16,
31779    /** DSA (Sign only) [FIPS186] [HAC] */
31780    dsa: 17,
31781    /** ECDH (Encrypt only) [RFC6637] */
31782    ecdh: 18,
31783    /** ECDSA (Sign only) [RFC6637] */
31784    ecdsa: 19,
31785    /** EdDSA (Sign only)
31786     * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */
31787    eddsa: 22,
31788    /** Reserved for AEDH */
31789    aedh: 23,
31790    /** Reserved for AEDSA */
31791    aedsa: 24
31792  },
31793
31794  /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}
31795   * @enum {Integer}
31796   * @readonly
31797   */
31798  symmetric: {
31799    plaintext: 0,
31800    /** Not implemented! */
31801    idea: 1,
31802    '3des': 2,
31803    tripledes: 2,
31804    cast5: 3,
31805    blowfish: 4,
31806    aes128: 7,
31807    aes192: 8,
31808    aes256: 9,
31809    twofish: 10
31810  },
31811
31812  /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}
31813   * @enum {Integer}
31814   * @readonly
31815   */
31816  compression: {
31817    uncompressed: 0,
31818    /** RFC1951 */
31819    zip: 1,
31820    /** RFC1950 */
31821    zlib: 2,
31822    bzip2: 3
31823  },
31824
31825  /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}
31826   * @enum {Integer}
31827   * @readonly
31828   */
31829  hash: {
31830    md5: 1,
31831    sha1: 2,
31832    ripemd: 3,
31833    sha256: 8,
31834    sha384: 9,
31835    sha512: 10,
31836    sha224: 11
31837  },
31838
31839  /** A list of hash names as accepted by webCrypto functions.
31840   * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}
31841   * @enum {String}
31842   */
31843  webHash: {
31844    'SHA-1': 2,
31845    'SHA-256': 8,
31846    'SHA-384': 9,
31847    'SHA-512': 10
31848  },
31849
31850  /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}
31851   * @enum {Integer}
31852   * @readonly
31853   */
31854  aead: {
31855    eax: 1,
31856    ocb: 2,
31857    experimental_gcm: 100 // Private algorithm
31858  },
31859
31860  /** A list of packet types and numeric tags associated with them.
31861   * @enum {Integer}
31862   * @readonly
31863   */
31864  packet: {
31865    publicKeyEncryptedSessionKey: 1,
31866    signature: 2,
31867    symEncryptedSessionKey: 3,
31868    onePassSignature: 4,
31869    secretKey: 5,
31870    publicKey: 6,
31871    secretSubkey: 7,
31872    compressed: 8,
31873    symmetricallyEncrypted: 9,
31874    marker: 10,
31875    literal: 11,
31876    trust: 12,
31877    userid: 13,
31878    publicSubkey: 14,
31879    userAttribute: 17,
31880    symEncryptedIntegrityProtected: 18,
31881    modificationDetectionCode: 19,
31882    symEncryptedAEADProtected: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1
31883  },
31884
31885  /** Data types in the literal packet
31886   * @enum {Integer}
31887   * @readonly
31888   */
31889  literal: {
31890    /** Binary data 'b' */
31891    binary: 'b'.charCodeAt(),
31892    /** Text data 't' */
31893    text: 't'.charCodeAt(),
31894    /** Utf8 data 'u' */
31895    utf8: 'u'.charCodeAt(),
31896    /** MIME message body part 'm' */
31897    mime: 'm'.charCodeAt()
31898  },
31899
31900  /** One pass signature packet type
31901   * @enum {Integer}
31902   * @readonly
31903   */
31904  signature: {
31905    /** 0x00: Signature of a binary document. */
31906    binary: 0,
31907    /** 0x01: Signature of a canonical text document.
31908     *
31909     * Canonicalyzing the document by converting line endings. */
31910    text: 1,
31911    /** 0x02: Standalone signature.
31912     *
31913     * This signature is a signature of only its own subpacket contents.
31914     * It is calculated identically to a signature over a zero-lengh
31915     * binary document.  Note that it doesn't make sense to have a V3
31916     * standalone signature. */
31917    standalone: 2,
31918    /** 0x10: Generic certification of a User ID and Public-Key packet.
31919     *
31920     * The issuer of this certification does not make any particular
31921     * assertion as to how well the certifier has checked that the owner
31922     * of the key is in fact the person described by the User ID. */
31923    cert_generic: 16,
31924    /** 0x11: Persona certification of a User ID and Public-Key packet.
31925     *
31926     * The issuer of this certification has not done any verification of
31927     * the claim that the owner of this key is the User ID specified. */
31928    cert_persona: 17,
31929    /** 0x12: Casual certification of a User ID and Public-Key packet.
31930     *
31931     * The issuer of this certification has done some casual
31932     * verification of the claim of identity. */
31933    cert_casual: 18,
31934    /** 0x13: Positive certification of a User ID and Public-Key packet.
31935     *
31936     * The issuer of this certification has done substantial
31937     * verification of the claim of identity.
31938     *
31939     * Most OpenPGP implementations make their "key signatures" as 0x10
31940     * certifications.  Some implementations can issue 0x11-0x13
31941     * certifications, but few differentiate between the types. */
31942    cert_positive: 19,
31943    /** 0x30: Certification revocation signature
31944     *
31945     * This signature revokes an earlier User ID certification signature
31946     * (signature class 0x10 through 0x13) or direct-key signature
31947     * (0x1F).  It should be issued by the same key that issued the
31948     * revoked signature or an authorized revocation key.  The signature
31949     * is computed over the same data as the certificate that it
31950     * revokes, and should have a later creation date than that
31951     * certificate. */
31952    cert_revocation: 48,
31953    /** 0x18: Subkey Binding Signature
31954     *
31955     * This signature is a statement by the top-level signing key that
31956     * indicates that it owns the subkey.  This signature is calculated
31957     * directly on the primary key and subkey, and not on any User ID or
31958     * other packets.  A signature that binds a signing subkey MUST have
31959     * an Embedded Signature subpacket in this binding signature that
31960     * contains a 0x19 signature made by the signing subkey on the
31961     * primary key and subkey. */
31962    subkey_binding: 24,
31963    /** 0x19: Primary Key Binding Signature
31964     *
31965     * This signature is a statement by a signing subkey, indicating
31966     * that it is owned by the primary key and subkey.  This signature
31967     * is calculated the same way as a 0x18 signature: directly on the
31968     * primary key and subkey, and not on any User ID or other packets.
31969     *
31970     * When a signature is made over a key, the hash data starts with the
31971     * octet 0x99, followed by a two-octet length of the key, and then body
31972     * of the key packet.  (Note that this is an old-style packet header for
31973     * a key packet with two-octet length.)  A subkey binding signature
31974     * (type 0x18) or primary key binding signature (type 0x19) then hashes
31975     * the subkey using the same format as the main key (also using 0x99 as
31976     * the first octet). */
31977    key_binding: 25,
31978    /** 0x1F: Signature directly on a key
31979     *
31980     * This signature is calculated directly on a key.  It binds the
31981     * information in the Signature subpackets to the key, and is
31982     * appropriate to be used for subpackets that provide information
31983     * about the key, such as the Revocation Key subpacket.  It is also
31984     * appropriate for statements that non-self certifiers want to make
31985     * about the key itself, rather than the binding between a key and a
31986     * name. */
31987    key: 31,
31988    /** 0x20: Key revocation signature
31989     *
31990     * The signature is calculated directly on the key being revoked.  A
31991     * revoked key is not to be used.  Only revocation signatures by the
31992     * key being revoked, or by an authorized revocation key, should be
31993     * considered valid revocation signatures.a */
31994    key_revocation: 32,
31995    /** 0x28: Subkey revocation signature
31996     *
31997     * The signature is calculated directly on the subkey being revoked.
31998     * A revoked subkey is not to be used.  Only revocation signatures
31999     * by the top-level signature key that is bound to this subkey, or
32000     * by an authorized revocation key, should be considered valid
32001     * revocation signatures.
32002     *
32003     * Key revocation signatures (types 0x20 and 0x28)
32004     * hash only the key being revoked. */
32005    subkey_revocation: 40,
32006    /** 0x40: Timestamp signature.
32007     * This signature is only meaningful for the timestamp contained in
32008     * it. */
32009    timestamp: 64,
32010    /** 0x50: Third-Party Confirmation signature.
32011     *
32012     * This signature is a signature over some other OpenPGP Signature
32013     * packet(s).  It is analogous to a notary seal on the signed data.
32014     * A third-party signature SHOULD include Signature Target
32015     * subpacket(s) to give easy identification.  Note that we really do
32016     * mean SHOULD.  There are plausible uses for this (such as a blind
32017     * party that only sees the signature, not the key or source
32018     * document) that cannot include a target subpacket. */
32019    third_party: 80
32020  },
32021
32022  /** Signature subpacket type
32023   * @enum {Integer}
32024   * @readonly
32025   */
32026  signatureSubpacket: {
32027    signature_creation_time: 2,
32028    signature_expiration_time: 3,
32029    exportable_certification: 4,
32030    trust_signature: 5,
32031    regular_expression: 6,
32032    revocable: 7,
32033    key_expiration_time: 9,
32034    placeholder_backwards_compatibility: 10,
32035    preferred_symmetric_algorithms: 11,
32036    revocation_key: 12,
32037    issuer: 16,
32038    notation_data: 20,
32039    preferred_hash_algorithms: 21,
32040    preferred_compression_algorithms: 22,
32041    key_server_preferences: 23,
32042    preferred_key_server: 24,
32043    primary_user_id: 25,
32044    policy_uri: 26,
32045    key_flags: 27,
32046    signers_user_id: 28,
32047    reason_for_revocation: 29,
32048    features: 30,
32049    signature_target: 31,
32050    embedded_signature: 32,
32051    issuer_fingerprint: 33,
32052    preferred_aead_algorithms: 34
32053  },
32054
32055  /** Key flags
32056   * @enum {Integer}
32057   * @readonly
32058   */
32059  keyFlags: {
32060    /** 0x01 - This key may be used to certify other keys. */
32061    certify_keys: 1,
32062    /** 0x02 - This key may be used to sign data. */
32063    sign_data: 2,
32064    /** 0x04 - This key may be used to encrypt communications. */
32065    encrypt_communication: 4,
32066    /** 0x08 - This key may be used to encrypt storage. */
32067    encrypt_storage: 8,
32068    /** 0x10 - The private component of this key may have been split
32069     *        by a secret-sharing mechanism. */
32070    split_private_key: 16,
32071    /** 0x20 - This key may be used for authentication. */
32072    authentication: 32,
32073    /** 0x80 - The private component of this key may be in the
32074     *        possession of more than one person. */
32075    shared_private_key: 128
32076  },
32077
32078  /** Key status
32079   * @enum {Integer}
32080   * @readonly
32081   */
32082  keyStatus: {
32083    invalid: 0,
32084    expired: 1,
32085    revoked: 2,
32086    valid: 3,
32087    no_self_cert: 4
32088  },
32089
32090  /** Armor type
32091   * @enum {Integer}
32092   * @readonly
32093   */
32094  armor: {
32095    multipart_section: 0,
32096    multipart_last: 1,
32097    signed: 2,
32098    message: 3,
32099    public_key: 4,
32100    private_key: 5,
32101    signature: 6
32102  },
32103
32104  /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}
32105   * @enum {Integer}
32106   * @readonly
32107   */
32108  reasonForRevocation: {
32109    /** No reason specified (key revocations or cert revocations) */
32110    no_reason: 0,
32111    /** Key is superseded (key revocations) */
32112    key_superseded: 1,
32113    /** Key material has been compromised (key revocations) */
32114    key_compromised: 2,
32115    /** Key is retired and no longer used (key revocations) */
32116    key_retired: 3,
32117    /** User ID information is no longer valid (cert revocations) */
32118    userid_invalid: 32
32119  },
32120
32121  /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}
32122   * @enum {Integer}
32123   * @readonly
32124   */
32125  features: {
32126    /** 0x01 - Modification Detection (packets 18 and 19) */
32127    modification_detection: 1,
32128    /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5
32129     *         Symmetric-Key Encrypted Session Key Packets (packet 3) */
32130    aead: 2,
32131    /** 0x04 - Version 5 Public-Key Packet format and corresponding new
32132      *        fingerprint format */
32133    v5_keys: 4
32134  },
32135
32136  /** Asserts validity and converts from string/integer to integer. */
32137  write: function write(type, e) {
32138    if (typeof e === 'number') {
32139      e = this.read(type, e);
32140    }
32141
32142    if (type[e] !== undefined) {
32143      return type[e];
32144    }
32145
32146    throw new Error('Invalid enum value.');
32147  },
32148
32149  /** Converts from an integer to string. */
32150  read: function read(type, e) {
32151    if (!type[byValue]) {
32152      type[byValue] = [];
32153      Object.entries(type).forEach(([key, value]) => {
32154        type[byValue][value] = key;
32155      });
32156    }
32157
32158    if (type[byValue][e] !== undefined) {
32159      return type[byValue][e];
32160    }
32161
32162    throw new Error('Invalid enum value.');
32163  }
32164
32165};
32166
32167},{}],115:[function(require,module,exports){
32168'use strict';
32169
32170Object.defineProperty(exports, "__esModule", {
32171  value: true
32172});
32173
32174var _config = require('./config');
32175
32176var _config2 = _interopRequireDefault(_config);
32177
32178function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
32179
32180/**
32181 * Initialize the HKP client and configure it with the key server url and fetch function.
32182 * @constructor
32183 * @param {String}    keyServerBaseUrl  (optional) The HKP key server base url including
32184 *   the protocol to use, e.g. 'https://pgp.mit.edu'; defaults to
32185 *   openpgp.config.keyserver (https://keyserver.ubuntu.com)
32186 */
32187function HKP(keyServerBaseUrl) {
32188  this._baseUrl = keyServerBaseUrl || _config2.default.keyserver;
32189  this._fetch = typeof window !== 'undefined' ? window.fetch : require('node-fetch');
32190}
32191
32192/**
32193 * Search for a public key on the key server either by key ID or part of the user ID.
32194 * @param  {String}   options.keyID   The long public key ID.
32195 * @param  {String}   options.query   This can be any part of the key user ID such as name
32196 *   or email address.
32197 * @returns {Promise<String>}          The ascii armored public key.
32198 * @async
32199 */
32200// OpenPGP.js - An OpenPGP implementation in javascript
32201// Copyright (C) 2015 Tankred Hase
32202//
32203// This library is free software; you can redistribute it and/or
32204// modify it under the terms of the GNU Lesser General Public
32205// License as published by the Free Software Foundation; either
32206// version 3.0 of the License, or (at your option) any later version.
32207//
32208// This library is distributed in the hope that it will be useful,
32209// but WITHOUT ANY WARRANTY; without even the implied warranty of
32210// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
32211// Lesser General Public License for more details.
32212//
32213// You should have received a copy of the GNU Lesser General Public
32214// License along with this library; if not, write to the Free Software
32215// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
32216
32217/**
32218 * @fileoverview This class implements a client for the OpenPGP HTTP Keyserver Protocol (HKP)
32219 * in order to lookup and upload keys on standard public key servers.
32220 * @module hkp
32221 */
32222
32223HKP.prototype.lookup = function (options) {
32224  //let uri = this._baseUrl + '/pks/lookup?op=get&options=mr&search=';
32225  let uri = this._baseUrl + '/pks/lookup?op=get&search=';
32226  const fetch = this._fetch;
32227
32228  if (options.keyId) {
32229    uri += '0x' + encodeURIComponent(options.keyId);
32230  } else if (options.query) {
32231    uri += encodeURIComponent(options.query);
32232  } else {
32233    throw new Error('You must provide a query parameter!');
32234  }
32235
32236  return fetch(uri).then(function (response) {
32237    if (response.status === 200) {
32238      return response.text();
32239    }
32240  }).then(function (publicKeyArmored) {
32241    if (!publicKeyArmored || publicKeyArmored.indexOf('-----END PGP PUBLIC KEY BLOCK-----') < 0) {
32242      return;
32243    }
32244    return publicKeyArmored.trim();
32245  });
32246};
32247
32248/**
32249 * Upload a public key to the server.
32250 * @param  {String}   publicKeyArmored  An ascii armored public key to be uploaded.
32251 * @returns {Promise}
32252 * @async
32253 */
32254HKP.prototype.upload = function (publicKeyArmored) {
32255  const uri = this._baseUrl + '/pks/add';
32256  const fetch = this._fetch;
32257
32258  return fetch(uri, {
32259    method: 'post',
32260    headers: {
32261      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
32262    },
32263    body: 'keytext=' + encodeURIComponent(publicKeyArmored)
32264  });
32265};
32266
32267exports.default = HKP;
32268
32269},{"./config":80,"node-fetch":"node-fetch"}],116:[function(require,module,exports){
32270'use strict';
32271
32272Object.defineProperty(exports, "__esModule", {
32273  value: true
32274});
32275exports.WKD = exports.HKP = exports.AsyncProxy = exports.Keyring = exports.crypto = exports.config = exports.enums = exports.armor = exports.stream = exports.OID = exports.KDFParams = exports.ECDHSymmetricKey = exports.Keyid = exports.S2K = exports.MPI = exports.packet = exports.util = exports.cleartext = exports.message = exports.signature = exports.key = exports.destroyWorker = exports.getWorker = exports.initWorker = exports.decryptSessionKeys = exports.encryptSessionKey = exports.decryptKey = exports.revokeKey = exports.reformatKey = exports.generateKey = exports.verify = exports.sign = exports.decrypt = exports.encrypt = undefined;
32276
32277var _openpgp = require('./openpgp');
32278
32279Object.defineProperty(exports, 'encrypt', {
32280  enumerable: true,
32281  get: function get() {
32282    return _openpgp.encrypt;
32283  }
32284});
32285Object.defineProperty(exports, 'decrypt', {
32286  enumerable: true,
32287  get: function get() {
32288    return _openpgp.decrypt;
32289  }
32290});
32291Object.defineProperty(exports, 'sign', {
32292  enumerable: true,
32293  get: function get() {
32294    return _openpgp.sign;
32295  }
32296});
32297Object.defineProperty(exports, 'verify', {
32298  enumerable: true,
32299  get: function get() {
32300    return _openpgp.verify;
32301  }
32302});
32303Object.defineProperty(exports, 'generateKey', {
32304  enumerable: true,
32305  get: function get() {
32306    return _openpgp.generateKey;
32307  }
32308});
32309Object.defineProperty(exports, 'reformatKey', {
32310  enumerable: true,
32311  get: function get() {
32312    return _openpgp.reformatKey;
32313  }
32314});
32315Object.defineProperty(exports, 'revokeKey', {
32316  enumerable: true,
32317  get: function get() {
32318    return _openpgp.revokeKey;
32319  }
32320});
32321Object.defineProperty(exports, 'decryptKey', {
32322  enumerable: true,
32323  get: function get() {
32324    return _openpgp.decryptKey;
32325  }
32326});
32327Object.defineProperty(exports, 'encryptSessionKey', {
32328  enumerable: true,
32329  get: function get() {
32330    return _openpgp.encryptSessionKey;
32331  }
32332});
32333Object.defineProperty(exports, 'decryptSessionKeys', {
32334  enumerable: true,
32335  get: function get() {
32336    return _openpgp.decryptSessionKeys;
32337  }
32338});
32339Object.defineProperty(exports, 'initWorker', {
32340  enumerable: true,
32341  get: function get() {
32342    return _openpgp.initWorker;
32343  }
32344});
32345Object.defineProperty(exports, 'getWorker', {
32346  enumerable: true,
32347  get: function get() {
32348    return _openpgp.getWorker;
32349  }
32350});
32351Object.defineProperty(exports, 'destroyWorker', {
32352  enumerable: true,
32353  get: function get() {
32354    return _openpgp.destroyWorker;
32355  }
32356});
32357
32358var _util = require('./util');
32359
32360Object.defineProperty(exports, 'util', {
32361  enumerable: true,
32362  get: function get() {
32363    return _interopRequireDefault(_util).default;
32364  }
32365});
32366
32367var _packet = require('./packet');
32368
32369Object.defineProperty(exports, 'packet', {
32370  enumerable: true,
32371  get: function get() {
32372    return _interopRequireDefault(_packet).default;
32373  }
32374});
32375
32376var _mpi = require('./type/mpi');
32377
32378Object.defineProperty(exports, 'MPI', {
32379  enumerable: true,
32380  get: function get() {
32381    return _interopRequireDefault(_mpi).default;
32382  }
32383});
32384
32385var _s2k = require('./type/s2k');
32386
32387Object.defineProperty(exports, 'S2K', {
32388  enumerable: true,
32389  get: function get() {
32390    return _interopRequireDefault(_s2k).default;
32391  }
32392});
32393
32394var _keyid = require('./type/keyid');
32395
32396Object.defineProperty(exports, 'Keyid', {
32397  enumerable: true,
32398  get: function get() {
32399    return _interopRequireDefault(_keyid).default;
32400  }
32401});
32402
32403var _ecdh_symkey = require('./type/ecdh_symkey');
32404
32405Object.defineProperty(exports, 'ECDHSymmetricKey', {
32406  enumerable: true,
32407  get: function get() {
32408    return _interopRequireDefault(_ecdh_symkey).default;
32409  }
32410});
32411
32412var _kdf_params = require('./type/kdf_params');
32413
32414Object.defineProperty(exports, 'KDFParams', {
32415  enumerable: true,
32416  get: function get() {
32417    return _interopRequireDefault(_kdf_params).default;
32418  }
32419});
32420
32421var _oid = require('./type/oid');
32422
32423Object.defineProperty(exports, 'OID', {
32424  enumerable: true,
32425  get: function get() {
32426    return _interopRequireDefault(_oid).default;
32427  }
32428});
32429
32430var _webStreamTools = require('web-stream-tools');
32431
32432Object.defineProperty(exports, 'stream', {
32433  enumerable: true,
32434  get: function get() {
32435    return _interopRequireDefault(_webStreamTools).default;
32436  }
32437});
32438
32439var _armor = require('./encoding/armor');
32440
32441Object.defineProperty(exports, 'armor', {
32442  enumerable: true,
32443  get: function get() {
32444    return _interopRequireDefault(_armor).default;
32445  }
32446});
32447
32448var _enums = require('./enums');
32449
32450Object.defineProperty(exports, 'enums', {
32451  enumerable: true,
32452  get: function get() {
32453    return _interopRequireDefault(_enums).default;
32454  }
32455});
32456
32457var _config = require('./config/config');
32458
32459Object.defineProperty(exports, 'config', {
32460  enumerable: true,
32461  get: function get() {
32462    return _interopRequireDefault(_config).default;
32463  }
32464});
32465
32466var _crypto = require('./crypto');
32467
32468Object.defineProperty(exports, 'crypto', {
32469  enumerable: true,
32470  get: function get() {
32471    return _interopRequireDefault(_crypto).default;
32472  }
32473});
32474
32475var _keyring = require('./keyring');
32476
32477Object.defineProperty(exports, 'Keyring', {
32478  enumerable: true,
32479  get: function get() {
32480    return _interopRequireDefault(_keyring).default;
32481  }
32482});
32483
32484var _async_proxy = require('./worker/async_proxy');
32485
32486Object.defineProperty(exports, 'AsyncProxy', {
32487  enumerable: true,
32488  get: function get() {
32489    return _interopRequireDefault(_async_proxy).default;
32490  }
32491});
32492
32493var _hkp = require('./hkp');
32494
32495Object.defineProperty(exports, 'HKP', {
32496  enumerable: true,
32497  get: function get() {
32498    return _interopRequireDefault(_hkp).default;
32499  }
32500});
32501
32502var _wkd = require('./wkd');
32503
32504Object.defineProperty(exports, 'WKD', {
32505  enumerable: true,
32506  get: function get() {
32507    return _interopRequireDefault(_wkd).default;
32508  }
32509});
32510
32511var openpgp = _interopRequireWildcard(_openpgp);
32512
32513var _key = require('./key');
32514
32515var keyMod = _interopRequireWildcard(_key);
32516
32517var _signature = require('./signature');
32518
32519var signatureMod = _interopRequireWildcard(_signature);
32520
32521var _message = require('./message');
32522
32523var messageMod = _interopRequireWildcard(_message);
32524
32525var _cleartext = require('./cleartext');
32526
32527var cleartextMod = _interopRequireWildcard(_cleartext);
32528
32529function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
32530
32531function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
32532
32533exports.default = openpgp;
32534
32535/**
32536 * Export each high level api function separately.
32537 * Usage:
32538 *
32539 *   import { encryptMessage } from 'openpgp.js'
32540 *   encryptMessage(keys, text)
32541 */
32542/* eslint-disable import/newline-after-import, import/first */
32543
32544/**
32545 * Export high level api as default.
32546 * Usage:
32547 *
32548 *   import openpgp from 'openpgp.js'
32549 *   openpgp.encryptMessage(keys, text)
32550 */
32551
32552
32553/**
32554 * @see module:key
32555 * @name module:openpgp.key
32556 */
32557
32558const key = exports.key = keyMod;
32559
32560/**
32561 * @see module:signature
32562 * @name module:openpgp.signature
32563 */
32564const signature = exports.signature = signatureMod;
32565
32566/**
32567 * @see module:message
32568 * @name module:openpgp.message
32569 */
32570const message = exports.message = messageMod;
32571
32572/**
32573 * @see module:cleartext
32574 * @name module:openpgp.cleartext
32575 */
32576const cleartext = exports.cleartext = cleartextMod;
32577
32578/**
32579 * @see module:util
32580 * @name module:openpgp.util
32581 */
32582
32583},{"./cleartext":78,"./config/config":79,"./crypto":95,"./encoding/armor":112,"./enums":114,"./hkp":115,"./key":117,"./keyring":118,"./message":121,"./openpgp":122,"./packet":126,"./signature":146,"./type/ecdh_symkey":147,"./type/kdf_params":148,"./type/keyid":149,"./type/mpi":150,"./type/oid":151,"./type/s2k":152,"./util":153,"./wkd":154,"./worker/async_proxy":155,"web-stream-tools":76}],117:[function(require,module,exports){
32584'use strict';
32585
32586Object.defineProperty(exports, "__esModule", {
32587  value: true
32588});
32589
32590var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); // GPG4Browsers - An OpenPGP implementation in javascript
32591// Copyright (C) 2011 Recurity Labs GmbH
32592//
32593// This library is free software; you can redistribute it and/or
32594// modify it under the terms of the GNU Lesser General Public
32595// License as published by the Free Software Foundation; either
32596// version 3.0 of the License, or (at your option) any later version.
32597//
32598// This library is distributed in the hope that it will be useful,
32599// but WITHOUT ANY WARRANTY; without even the implied warranty of
32600// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
32601// Lesser General Public License for more details.
32602//
32603// You should have received a copy of the GNU Lesser General Public
32604// License along with this library; if not, write to the Free Software
32605// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
32606
32607/**
32608 * @requires encoding/armor
32609 * @requires crypto
32610 * @requires packet
32611 * @requires config
32612 * @requires enums
32613 * @requires util
32614 * @module key
32615 */
32616
32617exports.Key = Key;
32618exports.createSignaturePacket = createSignaturePacket;
32619exports.read = read;
32620exports.readArmored = readArmored;
32621exports.generate = generate;
32622exports.reformat = reformat;
32623exports.getPreferredHashAlgo = getPreferredHashAlgo;
32624exports.getPreferredAlgo = getPreferredAlgo;
32625exports.isAeadSupported = isAeadSupported;
32626
32627var _armor = require('./encoding/armor');
32628
32629var _armor2 = _interopRequireDefault(_armor);
32630
32631var _crypto = require('./crypto');
32632
32633var _crypto2 = _interopRequireDefault(_crypto);
32634
32635var _packet = require('./packet');
32636
32637var _packet2 = _interopRequireDefault(_packet);
32638
32639var _config = require('./config');
32640
32641var _config2 = _interopRequireDefault(_config);
32642
32643var _enums = require('./enums');
32644
32645var _enums2 = _interopRequireDefault(_enums);
32646
32647var _util = require('./util');
32648
32649var _util2 = _interopRequireDefault(_util);
32650
32651function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
32652
32653/**
32654 * @class
32655 * @classdesc Class that represents an OpenPGP key. Must contain a primary key.
32656 * Can contain additional subkeys, signatures, user ids, user attributes.
32657 * @param  {module:packet.List} packetlist The packets that form this key
32658 * @borrows module:packet.PublicKey#getKeyId as Key#getKeyId
32659 * @borrows module:packet.PublicKey#getFingerprint as Key#getFingerprint
32660 * @borrows module:packet.PublicKey#hasSameFingerprintAs as Key#hasSameFingerprintAs
32661 * @borrows module:packet.PublicKey#getAlgorithmInfo as Key#getAlgorithmInfo
32662 * @borrows module:packet.PublicKey#getCreationTime as Key#getCreationTime
32663 * @borrows module:packet.PublicKey#isDecrypted as Key#isDecrypted
32664 */
32665function Key(packetlist) {
32666  if (!(this instanceof Key)) {
32667    return new Key(packetlist);
32668  }
32669  // same data as in packetlist but in structured form
32670  this.keyPacket = null;
32671  this.revocationSignatures = [];
32672  this.directSignatures = [];
32673  this.users = [];
32674  this.subKeys = [];
32675  this.packetlist2structure(packetlist);
32676  if (!this.keyPacket || !this.users.length) {
32677    throw new Error('Invalid key: need at least key and user ID packet');
32678  }
32679}
32680
32681Object.defineProperty(Key.prototype, 'primaryKey', {
32682  get() {
32683    return this.keyPacket;
32684  },
32685  configurable: true,
32686  enumerable: true
32687});
32688
32689/**
32690 * Transforms packetlist to structured key data
32691 * @param  {module:packet.List} packetlist The packets that form a key
32692 */
32693Key.prototype.packetlist2structure = function (packetlist) {
32694  let user;
32695  let primaryKeyId;
32696  let subKey;
32697  for (let i = 0; i < packetlist.length; i++) {
32698    switch (packetlist[i].tag) {
32699      case _enums2.default.packet.publicKey:
32700      case _enums2.default.packet.secretKey:
32701        this.keyPacket = packetlist[i];
32702        primaryKeyId = this.getKeyId();
32703        break;
32704      case _enums2.default.packet.userid:
32705      case _enums2.default.packet.userAttribute:
32706        user = new User(packetlist[i]);
32707        this.users.push(user);
32708        break;
32709      case _enums2.default.packet.publicSubkey:
32710      case _enums2.default.packet.secretSubkey:
32711        user = null;
32712        subKey = new SubKey(packetlist[i]);
32713        this.subKeys.push(subKey);
32714        break;
32715      case _enums2.default.packet.signature:
32716        switch (packetlist[i].signatureType) {
32717          case _enums2.default.signature.cert_generic:
32718          case _enums2.default.signature.cert_persona:
32719          case _enums2.default.signature.cert_casual:
32720          case _enums2.default.signature.cert_positive:
32721            if (!user) {
32722              _util2.default.print_debug('Dropping certification signatures without preceding user packet');
32723              continue;
32724            }
32725            if (packetlist[i].issuerKeyId.equals(primaryKeyId)) {
32726              checkRevocationKey(packetlist[i], primaryKeyId);
32727              user.selfCertifications.push(packetlist[i]);
32728            } else {
32729              user.otherCertifications.push(packetlist[i]);
32730            }
32731            break;
32732          case _enums2.default.signature.cert_revocation:
32733            if (user) {
32734              user.revocationSignatures.push(packetlist[i]);
32735            } else {
32736              this.directSignatures.push(packetlist[i]);
32737            }
32738            break;
32739          case _enums2.default.signature.key:
32740            checkRevocationKey(packetlist[i], primaryKeyId);
32741            this.directSignatures.push(packetlist[i]);
32742            break;
32743          case _enums2.default.signature.subkey_binding:
32744            if (!subKey) {
32745              _util2.default.print_debug('Dropping subkey binding signature without preceding subkey packet');
32746              continue;
32747            }
32748            checkRevocationKey(packetlist[i], primaryKeyId);
32749            subKey.bindingSignatures.push(packetlist[i]);
32750            break;
32751          case _enums2.default.signature.key_revocation:
32752            this.revocationSignatures.push(packetlist[i]);
32753            break;
32754          case _enums2.default.signature.subkey_revocation:
32755            if (!subKey) {
32756              _util2.default.print_debug('Dropping subkey revocation signature without preceding subkey packet');
32757              continue;
32758            }
32759            subKey.revocationSignatures.push(packetlist[i]);
32760            break;
32761        }
32762        break;
32763    }
32764  }
32765};
32766
32767/**
32768 * Transforms structured key data to packetlist
32769 * @returns {module:packet.List} The packets that form a key
32770 */
32771Key.prototype.toPacketlist = function () {
32772  const packetlist = new _packet2.default.List();
32773  packetlist.push(this.keyPacket);
32774  packetlist.concat(this.revocationSignatures);
32775  packetlist.concat(this.directSignatures);
32776  this.users.map(user => packetlist.concat(user.toPacketlist()));
32777  this.subKeys.map(subKey => packetlist.concat(subKey.toPacketlist()));
32778  return packetlist;
32779};
32780
32781/**
32782 * Returns an array containing all public or private subkeys matching keyId;
32783 * If keyId is not present, returns all subkeys.
32784 * @param  {type/keyid} keyId
32785 * @returns {Array<module:key~SubKey>}
32786 */
32787Key.prototype.getSubkeys = function (keyId = null) {
32788  const subKeys = [];
32789  this.subKeys.forEach(subKey => {
32790    if (!keyId || subKey.getKeyId().equals(keyId, true)) {
32791      subKeys.push(subKey);
32792    }
32793  });
32794  return subKeys;
32795};
32796
32797/**
32798 * Returns an array containing all public or private keys matching keyId.
32799 * If keyId is not present, returns all keys starting with the primary key.
32800 * @param  {type/keyid} keyId
32801 * @returns {Array<module:key.Key|module:key~SubKey>}
32802 */
32803Key.prototype.getKeys = function (keyId = null) {
32804  const keys = [];
32805  if (!keyId || this.getKeyId().equals(keyId, true)) {
32806    keys.push(this);
32807  }
32808  return keys.concat(this.getSubkeys(keyId));
32809};
32810
32811/**
32812 * Returns key IDs of all keys
32813 * @returns {Array<module:type/keyid>}
32814 */
32815Key.prototype.getKeyIds = function () {
32816  return this.getKeys().map(key => key.getKeyId());
32817};
32818
32819/**
32820 * Returns userids
32821 * @returns {Array<string>} array of userids
32822 */
32823Key.prototype.getUserIds = function () {
32824  return this.users.map(user => {
32825    return user.userId ? user.userId.userid : null;
32826  }).filter(userid => userid !== null);
32827};
32828
32829/**
32830 * Returns true if this is a public key
32831 * @returns {Boolean}
32832 */
32833Key.prototype.isPublic = function () {
32834  return this.keyPacket.tag === _enums2.default.packet.publicKey;
32835};
32836
32837/**
32838 * Returns true if this is a private key
32839 * @returns {Boolean}
32840 */
32841Key.prototype.isPrivate = function () {
32842  return this.keyPacket.tag === _enums2.default.packet.secretKey;
32843};
32844
32845/**
32846 * Returns key as public key (shallow copy)
32847 * @returns {module:key.Key} new public Key
32848 */
32849Key.prototype.toPublic = function () {
32850  const packetlist = new _packet2.default.List();
32851  const keyPackets = this.toPacketlist();
32852  let bytes;
32853  let pubKeyPacket;
32854  let pubSubkeyPacket;
32855  for (let i = 0; i < keyPackets.length; i++) {
32856    switch (keyPackets[i].tag) {
32857      case _enums2.default.packet.secretKey:
32858        bytes = keyPackets[i].writePublicKey();
32859        pubKeyPacket = new _packet2.default.PublicKey();
32860        pubKeyPacket.read(bytes);
32861        packetlist.push(pubKeyPacket);
32862        break;
32863      case _enums2.default.packet.secretSubkey:
32864        bytes = keyPackets[i].writePublicKey();
32865        pubSubkeyPacket = new _packet2.default.PublicSubkey();
32866        pubSubkeyPacket.read(bytes);
32867        packetlist.push(pubSubkeyPacket);
32868        break;
32869      default:
32870        packetlist.push(keyPackets[i]);
32871    }
32872  }
32873  return new Key(packetlist);
32874};
32875
32876/**
32877 * Returns ASCII armored text of key
32878 * @returns {ReadableStream<String>} ASCII armor
32879 */
32880Key.prototype.armor = function () {
32881  const type = this.isPublic() ? _enums2.default.armor.public_key : _enums2.default.armor.private_key;
32882  return _armor2.default.encode(type, this.toPacketlist().write());
32883};
32884
32885/**
32886 * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.
32887 * @param  {Array<module:packet.Signature>} signatures  List of signatures
32888 * @param  {Date}                           date        Use the given date instead of the current time
32889 * @returns {Promise<module:packet.Signature>} The latest valid signature
32890 * @async
32891 */
32892async function getLatestValidSignature(signatures, primaryKey, signatureType, dataToVerify, date = new Date()) {
32893  let signature;
32894  for (let i = signatures.length - 1; i >= 0; i--) {
32895    if ((!signature || signatures[i].created >= signature.created) &&
32896    // check binding signature is not expired (ie, check for V4 expiration time)
32897    !signatures[i].isExpired(date) && (
32898    // check binding signature is verified
32899    signatures[i].verified || (await signatures[i].verify(primaryKey, signatureType, dataToVerify)))) {
32900      signature = signatures[i];
32901    }
32902  }
32903  return signature;
32904}
32905
32906/**
32907 * Returns last created key or key by given keyId that is available for signing and verification
32908 * @param  {module:type/keyid} keyId, optional
32909 * @param  {Date} date (optional) use the given date for verification instead of the current time
32910 * @param  {Object} userId, optional user ID
32911 * @returns {Promise<module:key.Key|module:key~SubKey|null>} key or null if no signing key has been found
32912 * @async
32913 */
32914Key.prototype.getSigningKey = async function (keyId = null, date = new Date(), userId = {}) {
32915  const primaryKey = this.keyPacket;
32916  if ((await this.verifyPrimaryKey(date, userId)) === _enums2.default.keyStatus.valid) {
32917    const subKeys = this.subKeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);
32918    for (let i = 0; i < subKeys.length; i++) {
32919      if (!keyId || subKeys[i].getKeyId().equals(keyId)) {
32920        if ((await subKeys[i].verify(primaryKey, date)) === _enums2.default.keyStatus.valid) {
32921          const dataToVerify = { key: primaryKey, bind: subKeys[i].keyPacket };
32922          const bindingSignature = await getLatestValidSignature(subKeys[i].bindingSignatures, primaryKey, _enums2.default.signature.subkey_binding, dataToVerify, date);
32923          if (bindingSignature && bindingSignature.embeddedSignature && isValidSigningKeyPacket(subKeys[i].keyPacket, bindingSignature) && (await getLatestValidSignature([bindingSignature.embeddedSignature], subKeys[i].keyPacket, _enums2.default.signature.key_binding, dataToVerify, date))) {
32924            return subKeys[i];
32925          }
32926        }
32927      }
32928    }
32929    const primaryUser = await this.getPrimaryUser(date, userId);
32930    if (primaryUser && (!keyId || primaryKey.getKeyId().equals(keyId)) && isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification)) {
32931      return this;
32932    }
32933  }
32934  return null;
32935
32936  function isValidSigningKeyPacket(keyPacket, signature) {
32937    if (!signature.verified || signature.revoked !== false) {
32938      // Sanity check
32939      throw new Error('Signature not verified');
32940    }
32941    return keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.rsa_encrypt) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.elgamal) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.ecdh) && (!signature.keyFlags || (signature.keyFlags[0] & _enums2.default.keyFlags.sign_data) !== 0);
32942  }
32943};
32944
32945/**
32946 * Returns last created key or key by given keyId that is available for encryption or decryption
32947 * @param  {module:type/keyid} keyId, optional
32948 * @param  {Date}              date, optional
32949 * @param  {String}            userId, optional
32950 * @returns {Promise<module:key.Key|module:key~SubKey|null>} key or null if no encryption key has been found
32951 * @async
32952 */
32953Key.prototype.getEncryptionKey = async function (keyId, date = new Date(), userId = {}) {
32954  const primaryKey = this.keyPacket;
32955  if ((await this.verifyPrimaryKey(date, userId)) === _enums2.default.keyStatus.valid) {
32956    // V4: by convention subkeys are preferred for encryption service
32957    const subKeys = this.subKeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);
32958    for (let i = 0; i < subKeys.length; i++) {
32959      if (!keyId || subKeys[i].getKeyId().equals(keyId)) {
32960        if ((await subKeys[i].verify(primaryKey, date)) === _enums2.default.keyStatus.valid) {
32961          const dataToVerify = { key: primaryKey, bind: subKeys[i].keyPacket };
32962          const bindingSignature = await getLatestValidSignature(subKeys[i].bindingSignatures, primaryKey, _enums2.default.signature.subkey_binding, dataToVerify, date);
32963          if (bindingSignature && isValidEncryptionKeyPacket(subKeys[i].keyPacket, bindingSignature)) {
32964            return subKeys[i];
32965          }
32966        }
32967      }
32968    }
32969    // if no valid subkey for encryption, evaluate primary key
32970    const primaryUser = await this.getPrimaryUser(date, userId);
32971    if (primaryUser && (!keyId || primaryKey.getKeyId().equals(keyId)) && isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) {
32972      return this;
32973    }
32974  }
32975  return null;
32976
32977  function isValidEncryptionKeyPacket(keyPacket, signature) {
32978    if (!signature.verified || signature.revoked !== false) {
32979      // Sanity check
32980      throw new Error('Signature not verified');
32981    }
32982    return keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.dsa) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.rsa_sign) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.ecdsa) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.eddsa) && (!signature.keyFlags || (signature.keyFlags[0] & _enums2.default.keyFlags.encrypt_communication) !== 0 || (signature.keyFlags[0] & _enums2.default.keyFlags.encrypt_storage) !== 0);
32983  }
32984};
32985
32986/**
32987 * Encrypts all secret key and subkey packets matching keyId
32988 * @param  {String|Array<String>} passphrases - if multiple passphrases, then should be in same order as packets each should encrypt
32989 * @param  {module:type/keyid} keyId
32990 * @returns {Promise<Array<module:packet.SecretKey|module:packet.SecretSubkey>>}
32991 * @async
32992 */
32993Key.prototype.encrypt = async function (passphrases, keyId = null) {
32994  if (!this.isPrivate()) {
32995    throw new Error("Nothing to encrypt in a public key");
32996  }
32997
32998  const keys = this.getKeys(keyId);
32999  passphrases = _util2.default.isArray(passphrases) ? passphrases : new Array(keys.length).fill(passphrases);
33000  if (passphrases.length !== keys.length) {
33001    throw new Error("Invalid number of passphrases for key");
33002  }
33003
33004  return Promise.all(keys.map(async function (key, i) {
33005    const keyPacket = key.keyPacket;
33006
33007    await keyPacket.encrypt(passphrases[i]);
33008    keyPacket.clearPrivateParams();
33009    return keyPacket;
33010  }));
33011};
33012
33013/**
33014 * Decrypts all secret key and subkey packets matching keyId
33015 * @param  {String|Array<String>} passphrases
33016 * @param  {module:type/keyid} keyId
33017 * @returns {Promise<Boolean>} true if all matching key and subkey packets decrypted successfully
33018 * @async
33019 */
33020Key.prototype.decrypt = async function (passphrases, keyId = null) {
33021  if (!this.isPrivate()) {
33022    throw new Error("Nothing to decrypt in a public key");
33023  }
33024  passphrases = _util2.default.isArray(passphrases) ? passphrases : [passphrases];
33025
33026  const results = await Promise.all(this.getKeys(keyId).map(async function (key) {
33027    let decrypted = false;
33028    let error = null;
33029    await Promise.all(passphrases.map(async function (passphrase) {
33030      try {
33031        await key.keyPacket.decrypt(passphrase);
33032        decrypted = true;
33033      } catch (e) {
33034        error = e;
33035      }
33036    }));
33037    if (!decrypted) {
33038      throw error;
33039    }
33040    return decrypted;
33041  }));
33042  return results.every(result => result === true);
33043};
33044
33045/**
33046 * Checks if a signature on a key is revoked
33047 * @param  {module:packet.SecretKey|
33048 * @param  {module:packet.Signature}  signature    The signature to verify
33049 * @param  {module:packet.PublicSubkey|
33050 *          module:packet.SecretSubkey|
33051 *          module:packet.PublicKey|
33052 *          module:packet.SecretKey} key, optional The key to verify the signature
33053 * @param  {Date}                     date          Use the given date instead of the current time
33054 * @returns {Promise<Boolean>}                      True if the certificate is revoked
33055 * @async
33056 */
33057Key.prototype.isRevoked = async function (signature, key, date = new Date()) {
33058  return isDataRevoked(this.keyPacket, _enums2.default.signature.key_revocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date);
33059};
33060
33061/**
33062 * Verify primary key. Checks for revocation signatures, expiration time
33063 * and valid self signature
33064 * @param {Date} date (optional) use the given date for verification instead of the current time
33065 * @param  {Object} userId (optional) user ID
33066 * @returns {Promise<module:enums.keyStatus>} The status of the primary key
33067 * @async
33068 */
33069Key.prototype.verifyPrimaryKey = async function (date = new Date(), userId = {}) {
33070  const primaryKey = this.keyPacket;
33071  // check for key revocation signatures
33072  if (await this.isRevoked(null, null, date)) {
33073    return _enums2.default.keyStatus.revoked;
33074  }
33075  // check for at least one self signature. Self signature of user ID not mandatory
33076  // See {@link https://tools.ietf.org/html/rfc4880#section-11.1}
33077  if (!this.users.some(user => user.userId && user.selfCertifications.length)) {
33078    return _enums2.default.keyStatus.no_self_cert;
33079  }
33080  // check for valid, unrevoked, unexpired self signature
33081
33082  var _ref = (await this.getPrimaryUser(date, userId)) || {};
33083
33084  const user = _ref.user,
33085        selfCertification = _ref.selfCertification;
33086
33087  if (!user) {
33088    return _enums2.default.keyStatus.invalid;
33089  }
33090  // check for expiration time
33091  if (isDataExpired(primaryKey, selfCertification, date)) {
33092    return _enums2.default.keyStatus.expired;
33093  }
33094  return _enums2.default.keyStatus.valid;
33095};
33096
33097/**
33098 * Returns the latest date when the key can be used for encrypting, signing, or both, depending on the `capabilities` paramater.
33099 * When `capabilities` is null, defaults to returning the expiry date of the primary key.
33100 * Returns null if `capabilities` is passed and the key does not have the specified capabilities or is revoked or invalid.
33101 * Returns Infinity if the key doesn't expire.
33102 * @param  {encrypt|sign|encrypt_sign} capabilities, optional
33103 * @param  {module:type/keyid} keyId, optional
33104 * @param  {Object} userId, optional user ID
33105 * @returns {Promise<Date | Infinity | null>}
33106 * @async
33107 */
33108Key.prototype.getExpirationTime = async function (capabilities, keyId, userId) {
33109  const primaryUser = await this.getPrimaryUser(null, userId);
33110  if (!primaryUser) {
33111    throw new Error('Could not find primary user');
33112  }
33113  const selfCert = primaryUser.selfCertification;
33114  const keyExpiry = getExpirationTime(this.keyPacket, selfCert);
33115  const sigExpiry = selfCert.getExpirationTime();
33116  let expiry = keyExpiry < sigExpiry ? keyExpiry : sigExpiry;
33117  if (capabilities === 'encrypt' || capabilities === 'encrypt_sign') {
33118    const encryptKey = (await this.getEncryptionKey(keyId, expiry, userId)) || (await this.getEncryptionKey(keyId, null, userId));
33119    if (!encryptKey) return null;
33120    const encryptExpiry = await encryptKey.getExpirationTime(this.keyPacket);
33121    if (encryptExpiry < expiry) expiry = encryptExpiry;
33122  }
33123  if (capabilities === 'sign' || capabilities === 'encrypt_sign') {
33124    const signKey = (await this.getSigningKey(keyId, expiry, userId)) || (await this.getSigningKey(keyId, null, userId));
33125    if (!signKey) return null;
33126    const signExpiry = await signKey.getExpirationTime(this.keyPacket);
33127    if (signExpiry < expiry) expiry = signExpiry;
33128  }
33129  return expiry;
33130};
33131
33132/**
33133 * Returns primary user and most significant (latest valid) self signature
33134 * - if multiple primary users exist, returns the one with the latest self signature
33135 * - otherwise, returns the user with the latest self signature
33136 * @param  {Date} date (optional) use the given date for verification instead of the current time
33137 * @param  {Object} userId (optional) user ID to get instead of the primary user, if it exists
33138 * @returns {Promise<{user: module:key.User,
33139 *                    selfCertification: module:packet.Signature}>} The primary user and the self signature
33140 * @async
33141 */
33142Key.prototype.getPrimaryUser = async function (date = new Date(), userId = {}) {
33143  const primaryKey = this.keyPacket;
33144  const users = [];
33145  for (let i = 0; i < this.users.length; i++) {
33146    const user = this.users[i];
33147    if (!user.userId || !((userId.name === undefined || user.userId.name === userId.name) && (userId.email === undefined || user.userId.email === userId.email) && (userId.comment === undefined || user.userId.comment === userId.comment))) continue;
33148    const dataToVerify = { userId: user.userId, key: primaryKey };
33149    const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, _enums2.default.signature.cert_generic, dataToVerify, date);
33150    if (!selfCertification) continue;
33151    users.push({ index: i, user, selfCertification });
33152  }
33153  if (!users.length) {
33154    if (userId.name !== undefined || userId.email !== undefined || userId.comment !== undefined) {
33155      throw new Error('Could not find user that matches that user ID');
33156    }
33157    return null;
33158  }
33159  await Promise.all(users.map(async function (a) {
33160    return a.user.revoked || a.user.isRevoked(primaryKey, a.selfCertification, null, date);
33161  }));
33162  // sort by primary user flag and signature creation time
33163  const primaryUser = users.sort(function (a, b) {
33164    const A = a.selfCertification;
33165    const B = b.selfCertification;
33166    return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;
33167  }).pop();
33168  const user = primaryUser.user,
33169        cert = primaryUser.selfCertification;
33170
33171  if (cert.revoked || (await user.isRevoked(primaryKey, cert, null, date))) {
33172    return null;
33173  }
33174  return primaryUser;
33175};
33176
33177/**
33178 * Update key with new components from specified key with same key ID:
33179 * users, subkeys, certificates are merged into the destination key,
33180 * duplicates and expired signatures are ignored.
33181 *
33182 * If the specified key is a private key and the destination key is public,
33183 * the destination key is transformed to a private key.
33184 * @param  {module:key.Key} key Source key to merge
33185 * @returns {Promise<undefined>}
33186 * @async
33187 */
33188Key.prototype.update = async function (key) {
33189  if ((await key.verifyPrimaryKey()) === _enums2.default.keyStatus.invalid) {
33190    return;
33191  }
33192  if (!this.hasSameFingerprintAs(key)) {
33193    throw new Error('Key update method: fingerprints of keys not equal');
33194  }
33195  if (this.isPublic() && key.isPrivate()) {
33196    // check for equal subkey packets
33197    const equal = this.subKeys.length === key.subKeys.length && this.subKeys.every(destSubKey => {
33198      return key.subKeys.some(srcSubKey => {
33199        return destSubKey.hasSameFingerprintAs(srcSubKey);
33200      });
33201    });
33202    if (!equal) {
33203      throw new Error('Cannot update public key with private key if subkey mismatch');
33204    }
33205    this.keyPacket = key.keyPacket;
33206  }
33207  // revocation signatures
33208  await mergeSignatures(key, this, 'revocationSignatures', srcRevSig => {
33209    return isDataRevoked(this.keyPacket, _enums2.default.signature.key_revocation, this, [srcRevSig], null, key.keyPacket);
33210  });
33211  // direct signatures
33212  await mergeSignatures(key, this, 'directSignatures');
33213  // TODO replace when Promise.some or Promise.any are implemented
33214  // users
33215  await Promise.all(key.users.map(async srcUser => {
33216    let found = false;
33217    await Promise.all(this.users.map(async dstUser => {
33218      if (srcUser.userId && dstUser.userId && srcUser.userId.userid === dstUser.userId.userid || srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute)) {
33219        await dstUser.update(srcUser, this.keyPacket);
33220        found = true;
33221      }
33222    }));
33223    if (!found) {
33224      this.users.push(srcUser);
33225    }
33226  }));
33227  // TODO replace when Promise.some or Promise.any are implemented
33228  // subkeys
33229  await Promise.all(key.subKeys.map(async srcSubKey => {
33230    let found = false;
33231    await Promise.all(this.subKeys.map(async dstSubKey => {
33232      if (dstSubKey.hasSameFingerprintAs(srcSubKey)) {
33233        await dstSubKey.update(srcSubKey, this.keyPacket);
33234        found = true;
33235      }
33236    }));
33237    if (!found) {
33238      this.subKeys.push(srcSubKey);
33239    }
33240  }));
33241};
33242
33243/**
33244 * Merges signatures from source[attr] to dest[attr]
33245 * @private
33246 * @param  {Object} source
33247 * @param  {Object} dest
33248 * @param  {String} attr
33249 * @param  {Function} checkFn optional, signature only merged if true
33250 */
33251async function mergeSignatures(source, dest, attr, checkFn) {
33252  source = source[attr];
33253  if (source) {
33254    if (!dest[attr].length) {
33255      dest[attr] = source;
33256    } else {
33257      await Promise.all(source.map(async function (sourceSig) {
33258        if (!sourceSig.isExpired() && (!checkFn || (await checkFn(sourceSig))) && !dest[attr].some(function (destSig) {
33259          return _util2.default.equalsUint8Array(destSig.signature, sourceSig.signature);
33260        })) {
33261          dest[attr].push(sourceSig);
33262        }
33263      }));
33264    }
33265  }
33266}
33267
33268/**
33269 * Revokes the key
33270 * @param  {Object} reasonForRevocation optional, object indicating the reason for revocation
33271 * @param  {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
33272 * @param  {String} reasonForRevocation.string optional, string explaining the reason for revocation
33273 * @param  {Date} date optional, override the creationtime of the revocation signature
33274 * @returns {Promise<module:key.Key>} new key with revocation signature
33275 * @async
33276 */
33277Key.prototype.revoke = async function ({
33278  flag: reasonForRevocationFlag = _enums2.default.reasonForRevocation.no_reason,
33279  string: reasonForRevocationString = ''
33280} = {}, date = new Date()) {
33281  if (this.isPublic()) {
33282    throw new Error('Need private key for revoking');
33283  }
33284  const dataToSign = { key: this.keyPacket };
33285  const key = new Key(this.toPacketlist());
33286  key.revocationSignatures.push((await createSignaturePacket(dataToSign, null, this.keyPacket, {
33287    signatureType: _enums2.default.signature.key_revocation,
33288    reasonForRevocationFlag: _enums2.default.write(_enums2.default.reasonForRevocation, reasonForRevocationFlag),
33289    reasonForRevocationString
33290  }, date)));
33291  return key;
33292};
33293
33294/**
33295 * Get revocation certificate from a revoked key.
33296 *   (To get a revocation certificate for an unrevoked key, call revoke() first.)
33297 * @returns {Promise<String>} armored revocation certificate
33298 * @async
33299 */
33300Key.prototype.getRevocationCertificate = async function () {
33301  const dataToVerify = { key: this.keyPacket };
33302  const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, _enums2.default.signature.key_revocation, dataToVerify);
33303  if (revocationSignature) {
33304    const packetlist = new _packet2.default.List();
33305    packetlist.push(revocationSignature);
33306    return _armor2.default.encode(_enums2.default.armor.public_key, packetlist.write(), null, null, 'This is a revocation certificate');
33307  }
33308};
33309
33310/**
33311 * Applies a revocation certificate to a key
33312 * This adds the first signature packet in the armored text to the key,
33313 * if it is a valid revocation signature.
33314 * @param  {String} revocationCertificate armored revocation certificate
33315 * @returns {Promise<module:key.Key>} new revoked key
33316 * @async
33317 */
33318Key.prototype.applyRevocationCertificate = async function (revocationCertificate) {
33319  const input = await _armor2.default.decode(revocationCertificate);
33320  const packetlist = new _packet2.default.List();
33321  await packetlist.read(input.data);
33322  const revocationSignature = packetlist.findPacket(_enums2.default.packet.signature);
33323  if (!revocationSignature || revocationSignature.signatureType !== _enums2.default.signature.key_revocation) {
33324    throw new Error('Could not find revocation signature packet');
33325  }
33326  if (!revocationSignature.issuerKeyId.equals(this.getKeyId())) {
33327    throw new Error('Revocation signature does not match key');
33328  }
33329  if (revocationSignature.isExpired()) {
33330    throw new Error('Revocation signature is expired');
33331  }
33332  if (!(await revocationSignature.verify(this.keyPacket, _enums2.default.signature.key_revocation, { key: this.keyPacket }))) {
33333    throw new Error('Could not verify revocation signature');
33334  }
33335  const key = new Key(this.toPacketlist());
33336  key.revocationSignatures.push(revocationSignature);
33337  return key;
33338};
33339
33340/**
33341 * Signs primary user of key
33342 * @param  {Array<module:key.Key>} privateKey decrypted private keys for signing
33343 * @param  {Date} date (optional) use the given date for verification instead of the current time
33344 * @param  {Object} userId (optional) user ID to get instead of the primary user, if it exists
33345 * @returns {Promise<module:key.Key>} new public key with new certificate signature
33346 * @async
33347 */
33348Key.prototype.signPrimaryUser = async function (privateKeys, date, userId) {
33349  var _ref2 = (await this.getPrimaryUser(date, userId)) || {};
33350
33351  const index = _ref2.index,
33352        user = _ref2.user;
33353
33354  if (!user) {
33355    throw new Error('Could not find primary user');
33356  }
33357  const userSign = await user.sign(this.keyPacket, privateKeys);
33358  const key = new Key(this.toPacketlist());
33359  key.users[index] = userSign;
33360  return key;
33361};
33362
33363/**
33364 * Signs all users of key
33365 * @param  {Array<module:key.Key>} privateKeys decrypted private keys for signing
33366 * @returns {Promise<module:key.Key>} new public key with new certificate signature
33367 * @async
33368 */
33369Key.prototype.signAllUsers = async function (privateKeys) {
33370  const that = this;
33371  const key = new Key(this.toPacketlist());
33372  key.users = await Promise.all(this.users.map(function (user) {
33373    return user.sign(that.keyPacket, privateKeys);
33374  }));
33375  return key;
33376};
33377
33378/**
33379 * Verifies primary user of key
33380 * - if no arguments are given, verifies the self certificates;
33381 * - otherwise, verifies all certificates signed with given keys.
33382 * @param  {Array<module:key.Key>} keys array of keys to verify certificate signatures
33383 * @param  {Date} date (optional) use the given date for verification instead of the current time
33384 * @param  {Object} userId (optional) user ID to get instead of the primary user, if it exists
33385 * @returns {Promise<Array<{keyid: module:type/keyid,
33386 *                          valid: Boolean}>>}    List of signer's keyid and validity of signature
33387 * @async
33388 */
33389Key.prototype.verifyPrimaryUser = async function (keys, date, userId) {
33390  const primaryKey = this.keyPacket;
33391
33392  var _ref3 = (await this.getPrimaryUser(date, userId)) || {};
33393
33394  const user = _ref3.user;
33395
33396  if (!user) {
33397    throw new Error('Could not find primary user');
33398  }
33399  const results = keys ? await user.verifyAllCertifications(primaryKey, keys) : [{ keyid: primaryKey.keyid, valid: (await user.verify(primaryKey)) === _enums2.default.keyStatus.valid }];
33400  return results;
33401};
33402
33403/**
33404 * Verifies all users of key
33405 * - if no arguments are given, verifies the self certificates;
33406 * - otherwise, verifies all certificates signed with given keys.
33407 * @param  {Array<module:key.Key>} keys array of keys to verify certificate signatures
33408 * @returns {Promise<Array<{userid: String,
33409 *                          keyid: module:type/keyid,
33410 *                          valid: Boolean}>>} list of userid, signer's keyid and validity of signature
33411 * @async
33412 */
33413Key.prototype.verifyAllUsers = async function (keys) {
33414  const results = [];
33415  const primaryKey = this.keyPacket;
33416  await Promise.all(this.users.map(async function (user) {
33417    const signatures = keys ? await user.verifyAllCertifications(primaryKey, keys) : [{ keyid: primaryKey.keyid, valid: (await user.verify(primaryKey)) === _enums2.default.keyStatus.valid }];
33418    signatures.forEach(signature => {
33419      results.push({
33420        userid: user.userId.userid,
33421        keyid: signature.keyid,
33422        valid: signature.valid
33423      });
33424    });
33425  }));
33426  return results;
33427};
33428
33429/**
33430 * @class
33431 * @classdesc Class that represents an user ID or attribute packet and the relevant signatures.
33432 */
33433function User(userPacket) {
33434  if (!(this instanceof User)) {
33435    return new User(userPacket);
33436  }
33437  this.userId = userPacket.tag === _enums2.default.packet.userid ? userPacket : null;
33438  this.userAttribute = userPacket.tag === _enums2.default.packet.userAttribute ? userPacket : null;
33439  this.selfCertifications = [];
33440  this.otherCertifications = [];
33441  this.revocationSignatures = [];
33442}
33443
33444/**
33445 * Transforms structured user data to packetlist
33446 * @returns {module:packet.List}
33447 */
33448User.prototype.toPacketlist = function () {
33449  const packetlist = new _packet2.default.List();
33450  packetlist.push(this.userId || this.userAttribute);
33451  packetlist.concat(this.revocationSignatures);
33452  packetlist.concat(this.selfCertifications);
33453  packetlist.concat(this.otherCertifications);
33454  return packetlist;
33455};
33456
33457/**
33458 * Signs user
33459 * @param  {module:packet.SecretKey|
33460 *          module:packet.PublicKey} primaryKey  The primary key packet
33461 * @param  {Array<module:key.Key>}    privateKeys Decrypted private keys for signing
33462 * @returns {Promise<module:key.Key>}             New user with new certificate signatures
33463 * @async
33464 */
33465User.prototype.sign = async function (primaryKey, privateKeys) {
33466  const dataToSign = {
33467    userId: this.userId,
33468    userAttribute: this.userAttribute,
33469    key: primaryKey
33470  };
33471  const user = new User(dataToSign.userId || dataToSign.userAttribute);
33472  user.otherCertifications = await Promise.all(privateKeys.map(async function (privateKey) {
33473    if (privateKey.isPublic()) {
33474      throw new Error('Need private key for signing');
33475    }
33476    if (privateKey.hasSameFingerprintAs(primaryKey)) {
33477      throw new Error('Not implemented for self signing');
33478    }
33479    const signingKey = await privateKey.getSigningKey();
33480    if (!signingKey) {
33481      throw new Error('Could not find valid signing key packet in key ' + privateKey.getKeyId().toHex());
33482    }
33483    return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, {
33484      // Most OpenPGP implementations use generic certification (0x10)
33485      signatureType: _enums2.default.signature.cert_generic,
33486      keyFlags: [_enums2.default.keyFlags.certify_keys | _enums2.default.keyFlags.sign_data]
33487    });
33488  }));
33489  await user.update(this, primaryKey);
33490  return user;
33491};
33492
33493/**
33494 * Checks if a given certificate of the user is revoked
33495 * @param  {module:packet.SecretKey|
33496 *          module:packet.PublicKey} primaryKey    The primary key packet
33497 * @param  {module:packet.Signature}  certificate   The certificate to verify
33498 * @param  {module:packet.PublicSubkey|
33499 *          module:packet.SecretSubkey|
33500 *          module:packet.PublicKey|
33501 *          module:packet.SecretKey} key, optional The key to verify the signature
33502 * @param  {Date}                     date          Use the given date instead of the current time
33503 * @returns {Promise<Boolean>}                      True if the certificate is revoked
33504 * @async
33505 */
33506User.prototype.isRevoked = async function (primaryKey, certificate, key, date = new Date()) {
33507  return isDataRevoked(primaryKey, _enums2.default.signature.cert_revocation, {
33508    key: primaryKey,
33509    userId: this.userId,
33510    userAttribute: this.userAttribute
33511  }, this.revocationSignatures, certificate, key, date);
33512};
33513
33514/**
33515 * Create signature packet
33516 * @param  {Object}                          dataToSign Contains packets to be signed
33517 * @param  {module:packet.SecretKey|
33518 *          module:packet.SecretSubkey}      signingKeyPacket secret key packet for signing
33519 * @param  {Object} signatureProperties      (optional) properties to write on the signature packet before signing
33520 * @param  {Date} date                       (optional) override the creationtime of the signature
33521 * @param  {Object} userId                   (optional) user ID
33522 * @returns {module:packet/signature}         signature packet
33523 */
33524async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userId) {
33525  if (!signingKeyPacket.isDecrypted()) {
33526    throw new Error('Private key is not decrypted.');
33527  }
33528  const signaturePacket = new _packet2.default.Signature(date);
33529  Object.assign(signaturePacket, signatureProperties);
33530  signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;
33531  signaturePacket.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKeyPacket, date, userId);
33532  await signaturePacket.sign(signingKeyPacket, dataToSign);
33533  return signaturePacket;
33534}
33535
33536/**
33537 * Verifies the user certificate
33538 * @param  {module:packet.SecretKey|
33539 *          module:packet.PublicKey} primaryKey  The primary key packet
33540 * @param  {module:packet.Signature}  certificate A certificate of this user
33541 * @param  {Array<module:key.Key>}    keys        Array of keys to verify certificate signatures
33542 * @param  {Date}                     date        Use the given date instead of the current time
33543 * @returns {Promise<module:enums.keyStatus>}     status of the certificate
33544 * @async
33545 */
33546User.prototype.verifyCertificate = async function (primaryKey, certificate, keys, date = new Date()) {
33547  const that = this;
33548  const keyid = certificate.issuerKeyId;
33549  const dataToVerify = {
33550    userId: this.userId,
33551    userAttribute: this.userAttribute,
33552    key: primaryKey
33553  };
33554  const results = await Promise.all(keys.map(async function (key) {
33555    if (!key.getKeyIds().some(id => id.equals(keyid))) {
33556      return;
33557    }
33558    const signingKey = await key.getSigningKey(keyid, date);
33559    if (certificate.revoked || (await that.isRevoked(primaryKey, certificate, signingKey.keyPacket, date))) {
33560      return _enums2.default.keyStatus.revoked;
33561    }
33562    if (!(certificate.verified || (await certificate.verify(signingKey.keyPacket, _enums2.default.signature.cert_generic, dataToVerify)))) {
33563      return _enums2.default.keyStatus.invalid;
33564    }
33565    if (certificate.isExpired(date)) {
33566      return _enums2.default.keyStatus.expired;
33567    }
33568    return _enums2.default.keyStatus.valid;
33569  }));
33570  return results.find(result => result !== undefined);
33571};
33572
33573/**
33574 * Verifies all user certificates
33575 * @param  {module:packet.SecretKey|
33576 *          module:packet.PublicKey} primaryKey The primary key packet
33577 * @param  {Array<module:key.Key>}    keys       Array of keys to verify certificate signatures
33578 * @param  {Date}                     date        Use the given date instead of the current time
33579 * @returns {Promise<Array<{keyid: module:type/keyid,
33580 *                          valid: Boolean}>>}   List of signer's keyid and validity of signature
33581 * @async
33582 */
33583User.prototype.verifyAllCertifications = async function (primaryKey, keys, date = new Date()) {
33584  const that = this;
33585  const certifications = this.selfCertifications.concat(this.otherCertifications);
33586  return Promise.all(certifications.map(async function (certification) {
33587    const status = await that.verifyCertificate(primaryKey, certification, keys, date);
33588    return {
33589      keyid: certification.issuerKeyId,
33590      valid: status === undefined ? null : status === _enums2.default.keyStatus.valid
33591    };
33592  }));
33593};
33594
33595/**
33596 * Verify User. Checks for existence of self signatures, revocation signatures
33597 * and validity of self signature
33598 * @param  {module:packet.SecretKey|
33599 *          module:packet.PublicKey} primaryKey The primary key packet
33600 * @param  {Date}                    date       Use the given date instead of the current time
33601 * @returns {Promise<module:enums.keyStatus>}    Status of user
33602 * @async
33603 */
33604User.prototype.verify = async function (primaryKey, date = new Date()) {
33605  if (!this.selfCertifications.length) {
33606    return _enums2.default.keyStatus.no_self_cert;
33607  }
33608  const that = this;
33609  const dataToVerify = {
33610    userId: this.userId,
33611    userAttribute: this.userAttribute,
33612    key: primaryKey
33613  };
33614  // TODO replace when Promise.some or Promise.any are implemented
33615  const results = [_enums2.default.keyStatus.invalid].concat((await Promise.all(this.selfCertifications.map(async function (selfCertification) {
33616    if (selfCertification.revoked || (await that.isRevoked(primaryKey, selfCertification, undefined, date))) {
33617      return _enums2.default.keyStatus.revoked;
33618    }
33619    if (!(selfCertification.verified || (await selfCertification.verify(primaryKey, _enums2.default.signature.cert_generic, dataToVerify)))) {
33620      return _enums2.default.keyStatus.invalid;
33621    }
33622    if (selfCertification.isExpired(date)) {
33623      return _enums2.default.keyStatus.expired;
33624    }
33625    return _enums2.default.keyStatus.valid;
33626  }))));
33627  return results.some(status => status === _enums2.default.keyStatus.valid) ? _enums2.default.keyStatus.valid : results.pop();
33628};
33629
33630/**
33631 * Update user with new components from specified user
33632 * @param  {module:key.User}             user       Source user to merge
33633 * @param  {module:packet.SecretKey|
33634 *          module:packet.SecretSubkey} primaryKey primary key used for validation
33635 * @returns {Promise<undefined>}
33636 * @async
33637 */
33638User.prototype.update = async function (user, primaryKey) {
33639  const dataToVerify = {
33640    userId: this.userId,
33641    userAttribute: this.userAttribute,
33642    key: primaryKey
33643  };
33644  // self signatures
33645  await mergeSignatures(user, this, 'selfCertifications', async function (srcSelfSig) {
33646    return srcSelfSig.verified || srcSelfSig.verify(primaryKey, _enums2.default.signature.cert_generic, dataToVerify);
33647  });
33648  // other signatures
33649  await mergeSignatures(user, this, 'otherCertifications');
33650  // revocation signatures
33651  await mergeSignatures(user, this, 'revocationSignatures', function (srcRevSig) {
33652    return isDataRevoked(primaryKey, _enums2.default.signature.cert_revocation, dataToVerify, [srcRevSig]);
33653  });
33654};
33655
33656/**
33657 * @class
33658 * @classdesc Class that represents a subkey packet and the relevant signatures.
33659 * @borrows module:packet.PublicSubkey#getKeyId as SubKey#getKeyId
33660 * @borrows module:packet.PublicSubkey#getFingerprint as SubKey#getFingerprint
33661 * @borrows module:packet.PublicSubkey#hasSameFingerprintAs as SubKey#hasSameFingerprintAs
33662 * @borrows module:packet.PublicSubkey#getAlgorithmInfo as SubKey#getAlgorithmInfo
33663 * @borrows module:packet.PublicSubkey#getCreationTime as SubKey#getCreationTime
33664 * @borrows module:packet.PublicSubkey#isDecrypted as SubKey#isDecrypted
33665 */
33666function SubKey(subKeyPacket) {
33667  if (!(this instanceof SubKey)) {
33668    return new SubKey(subKeyPacket);
33669  }
33670  this.keyPacket = subKeyPacket;
33671  this.bindingSignatures = [];
33672  this.revocationSignatures = [];
33673}
33674
33675/**
33676 * Transforms structured subkey data to packetlist
33677 * @returns {module:packet.List}
33678 */
33679SubKey.prototype.toPacketlist = function () {
33680  const packetlist = new _packet2.default.List();
33681  packetlist.push(this.keyPacket);
33682  packetlist.concat(this.revocationSignatures);
33683  packetlist.concat(this.bindingSignatures);
33684  return packetlist;
33685};
33686
33687/**
33688 * Checks if a binding signature of a subkey is revoked
33689 * @param  {module:packet.SecretKey|
33690 *          module:packet.PublicKey} primaryKey    The primary key packet
33691 * @param  {module:packet.Signature}  signature     The binding signature to verify
33692 * @param  {module:packet.PublicSubkey|
33693 *          module:packet.SecretSubkey|
33694 *          module:packet.PublicKey|
33695 *          module:packet.SecretKey} key, optional The key to verify the signature
33696 * @param  {Date}                     date          Use the given date instead of the current time
33697 * @returns {Promise<Boolean>}                      True if the binding signature is revoked
33698 * @async
33699 */
33700SubKey.prototype.isRevoked = async function (primaryKey, signature, key, date = new Date()) {
33701  return isDataRevoked(primaryKey, _enums2.default.signature.subkey_revocation, {
33702    key: primaryKey,
33703    bind: this.keyPacket
33704  }, this.revocationSignatures, signature, key, date);
33705};
33706
33707/**
33708 * Verify subkey. Checks for revocation signatures, expiration time
33709 * and valid binding signature
33710 * @param  {module:packet.SecretKey|
33711 *          module:packet.PublicKey} primaryKey The primary key packet
33712 * @param  {Date}                     date       Use the given date instead of the current time
33713 * @returns {Promise<module:enums.keyStatus>}    The status of the subkey
33714 * @async
33715 */
33716SubKey.prototype.verify = async function (primaryKey, date = new Date()) {
33717  const that = this;
33718  const dataToVerify = { key: primaryKey, bind: this.keyPacket };
33719  // check subkey binding signatures
33720  const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, _enums2.default.signature.subkey_binding, dataToVerify, date);
33721  // check binding signature is verified
33722  if (!bindingSignature) {
33723    return _enums2.default.keyStatus.invalid;
33724  }
33725  // check binding signature is not revoked
33726  if (bindingSignature.revoked || (await that.isRevoked(primaryKey, bindingSignature, null, date))) {
33727    return _enums2.default.keyStatus.revoked;
33728  }
33729  // check for expiration time
33730  if (isDataExpired(this.keyPacket, bindingSignature, date)) {
33731    return _enums2.default.keyStatus.expired;
33732  }
33733  return _enums2.default.keyStatus.valid; // binding signature passed all checks
33734};
33735
33736/**
33737 * Returns the expiration time of the subkey or Infinity if key does not expire
33738 * Returns null if the subkey is invalid.
33739 * @param  {module:packet.SecretKey|
33740 *          module:packet.PublicKey} primaryKey  The primary key packet
33741 * @param  {Date}                     date       Use the given date instead of the current time
33742 * @returns {Promise<Date | Infinity | null>}
33743 * @async
33744 */
33745SubKey.prototype.getExpirationTime = async function (primaryKey, date = new Date()) {
33746  const dataToVerify = { key: primaryKey, bind: this.keyPacket };
33747  const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, _enums2.default.signature.subkey_binding, dataToVerify, date);
33748  if (!bindingSignature) return null;
33749  const keyExpiry = getExpirationTime(this.keyPacket, bindingSignature);
33750  const sigExpiry = bindingSignature.getExpirationTime();
33751  return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;
33752};
33753
33754/**
33755 * Update subkey with new components from specified subkey
33756 * @param  {module:key~SubKey}           subKey     Source subkey to merge
33757 * @param  {module:packet.SecretKey|
33758            module:packet.SecretSubkey} primaryKey primary key used for validation
33759 * @returns {Promise<undefined>}
33760 * @async
33761 */
33762SubKey.prototype.update = async function (subKey, primaryKey) {
33763  if ((await subKey.verify(primaryKey)) === _enums2.default.keyStatus.invalid) {
33764    return;
33765  }
33766  if (!this.hasSameFingerprintAs(subKey)) {
33767    throw new Error('SubKey update method: fingerprints of subkeys not equal');
33768  }
33769  // key packet
33770  if (this.keyPacket.tag === _enums2.default.packet.publicSubkey && subKey.keyPacket.tag === _enums2.default.packet.secretSubkey) {
33771    this.keyPacket = subKey.keyPacket;
33772  }
33773  // update missing binding signatures
33774  const that = this;
33775  const dataToVerify = { key: primaryKey, bind: that.keyPacket };
33776  await mergeSignatures(subKey, this, 'bindingSignatures', async function (srcBindSig) {
33777    if (!(srcBindSig.verified || (await srcBindSig.verify(primaryKey, _enums2.default.signature.subkey_binding, dataToVerify)))) {
33778      return false;
33779    }
33780    for (let i = 0; i < that.bindingSignatures.length; i++) {
33781      if (that.bindingSignatures[i].issuerKeyId.equals(srcBindSig.issuerKeyId)) {
33782        if (srcBindSig.created > that.bindingSignatures[i].created) {
33783          that.bindingSignatures[i] = srcBindSig;
33784        }
33785        return false;
33786      }
33787    }
33788    return true;
33789  });
33790  // revocation signatures
33791  await mergeSignatures(subKey, this, 'revocationSignatures', function (srcRevSig) {
33792    return isDataRevoked(primaryKey, _enums2.default.signature.subkey_revocation, dataToVerify, [srcRevSig]);
33793  });
33794};
33795
33796/**
33797 * Revokes the subkey
33798 * @param  {module:packet.SecretKey} primaryKey decrypted private primary key for revocation
33799 * @param  {Object} reasonForRevocation optional, object indicating the reason for revocation
33800 * @param  {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
33801 * @param  {String} reasonForRevocation.string optional, string explaining the reason for revocation
33802 * @param  {Date} date optional, override the creationtime of the revocation signature
33803 * @returns {Promise<module:key~SubKey>} new subkey with revocation signature
33804 * @async
33805 */
33806SubKey.prototype.revoke = async function (primaryKey, {
33807  flag: reasonForRevocationFlag = _enums2.default.reasonForRevocation.no_reason,
33808  string: reasonForRevocationString = ''
33809} = {}, date = new Date()) {
33810  const dataToSign = { key: primaryKey, bind: this.keyPacket };
33811  const subKey = new SubKey(this.keyPacket);
33812  subKey.revocationSignatures.push((await createSignaturePacket(dataToSign, null, primaryKey, {
33813    signatureType: _enums2.default.signature.subkey_revocation,
33814    reasonForRevocationFlag: _enums2.default.write(_enums2.default.reasonForRevocation, reasonForRevocationFlag),
33815    reasonForRevocationString
33816  }, date)));
33817  await subKey.update(this, primaryKey);
33818  return subKey;
33819};
33820
33821['getKeyId', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {
33822  Key.prototype[name] = SubKey.prototype[name] = function () {
33823    return this.keyPacket[name]();
33824  };
33825});
33826
33827Key.prototype.hasSameFingerprintAs = SubKey.prototype.hasSameFingerprintAs = function (other) {
33828  return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);
33829};
33830
33831/**
33832 * Reads an unarmored OpenPGP key list and returns one or multiple key objects
33833 * @param {Uint8Array} data to be parsed
33834 * @returns {Promise<{keys: Array<module:key.Key>,
33835 *            err: (Array<Error>|null)}>} result object with key and error arrays
33836 * @async
33837 * @static
33838 */
33839async function read(data) {
33840  const result = {};
33841  result.keys = [];
33842  const err = [];
33843  try {
33844    const packetlist = new _packet2.default.List();
33845    await packetlist.read(data);
33846    const keyIndex = packetlist.indexOfTag(_enums2.default.packet.publicKey, _enums2.default.packet.secretKey);
33847    if (keyIndex.length === 0) {
33848      throw new Error('No key packet found');
33849    }
33850    for (let i = 0; i < keyIndex.length; i++) {
33851      const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);
33852      try {
33853        const newKey = new Key(oneKeyList);
33854        result.keys.push(newKey);
33855      } catch (e) {
33856        err.push(e);
33857      }
33858    }
33859  } catch (e) {
33860    err.push(e);
33861  }
33862  if (err.length) {
33863    result.err = err;
33864  }
33865  return result;
33866}
33867
33868/**
33869 * Reads an OpenPGP armored text and returns one or multiple key objects
33870 * @param {String | ReadableStream<String>} armoredText text to be parsed
33871 * @returns {Promise<{keys: Array<module:key.Key>,
33872 *            err: (Array<Error>|null)}>} result object with key and error arrays
33873 * @async
33874 * @static
33875 */
33876async function readArmored(armoredText) {
33877  try {
33878    const input = await _armor2.default.decode(armoredText);
33879    if (!(input.type === _enums2.default.armor.public_key || input.type === _enums2.default.armor.private_key)) {
33880      throw new Error('Armored text not of type key');
33881    }
33882    return read(input.data);
33883  } catch (e) {
33884    const result = { keys: [], err: [] };
33885    result.err.push(e);
33886    return result;
33887  }
33888}
33889
33890/**
33891 * Generates a new OpenPGP key. Supports RSA and ECC keys.
33892 * Primary and subkey will be of same type.
33893 * @param {module:enums.publicKey} [options.keyType=module:enums.publicKey.rsa_encrypt_sign]
33894 *                             To indicate what type of key to make.
33895 *                             RSA is 1. See {@link https://tools.ietf.org/html/rfc4880#section-9.1}
33896 * @param {Integer} options.numBits    number of bits for the key creation.
33897 * @param {String|Array<String>}  options.userIds
33898 *                             Assumes already in form of "User Name <username@email.com>"
33899 *                             If array is used, the first userId is set as primary user Id
33900 * @param {String}  options.passphrase The passphrase used to encrypt the resulting private key
33901 * @param {Number} [options.keyExpirationTime=0]
33902 *                             The number of seconds after the key creation time that the key expires
33903 * @param  {String} curve            (optional) elliptic curve for ECC keys
33904 * @param  {Date} date         Override the creation date of the key and the key signatures
33905 * @param  {Array<Object>} subkeys   (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
33906 *                                              sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt
33907 * @returns {Promise<module:key.Key>}
33908 * @async
33909 * @static
33910 */
33911async function generate(options) {
33912  options.sign = true; // primary key is always a signing key
33913  options = sanitizeKeyOptions(options);
33914  options.subkeys = options.subkeys.map(function (subkey, index) {
33915    return sanitizeKeyOptions(options.subkeys[index], options);
33916  });
33917
33918  let promises = [generateSecretKey(options)];
33919  promises = promises.concat(options.subkeys.map(generateSecretSubkey));
33920  return Promise.all(promises).then(packets => wrapKeyObject(packets[0], packets.slice(1), options));
33921
33922  function sanitizeKeyOptions(options, subkeyDefaults = {}) {
33923    options.curve = options.curve || subkeyDefaults.curve;
33924    options.numBits = options.numBits || subkeyDefaults.numBits;
33925    options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;
33926    options.passphrase = _util2.default.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
33927    options.date = options.date || subkeyDefaults.date;
33928
33929    options.sign = options.sign || false;
33930
33931    if (options.curve) {
33932      try {
33933        options.curve = _enums2.default.write(_enums2.default.curve, options.curve);
33934      } catch (e) {
33935        throw new Error('Not valid curve.');
33936      }
33937      if (options.curve === _enums2.default.curve.ed25519 || options.curve === _enums2.default.curve.curve25519) {
33938        if (options.sign) {
33939          options.algorithm = _enums2.default.publicKey.eddsa;
33940          options.curve = _enums2.default.curve.ed25519;
33941        } else {
33942          options.algorithm = _enums2.default.publicKey.ecdh;
33943          options.curve = _enums2.default.curve.curve25519;
33944        }
33945      } else {
33946        if (options.sign) {
33947          options.algorithm = _enums2.default.publicKey.ecdsa;
33948        } else {
33949          options.algorithm = _enums2.default.publicKey.ecdh;
33950        }
33951      }
33952    } else if (options.numBits) {
33953      options.algorithm = _enums2.default.publicKey.rsa_encrypt_sign;
33954    } else {
33955      throw new Error('Unrecognized key type');
33956    }
33957    return options;
33958  }
33959
33960  async function generateSecretKey(options) {
33961    const secretKeyPacket = new _packet2.default.SecretKey(options.date);
33962    secretKeyPacket.packets = null;
33963    secretKeyPacket.algorithm = _enums2.default.read(_enums2.default.publicKey, options.algorithm);
33964    await secretKeyPacket.generate(options.numBits, options.curve);
33965    return secretKeyPacket;
33966  }
33967
33968  async function generateSecretSubkey(options) {
33969    const secretSubkeyPacket = new _packet2.default.SecretSubkey(options.date);
33970    secretSubkeyPacket.packets = null;
33971    secretSubkeyPacket.algorithm = _enums2.default.read(_enums2.default.publicKey, options.algorithm);
33972    await secretSubkeyPacket.generate(options.numBits, options.curve);
33973    return secretSubkeyPacket;
33974  }
33975}
33976
33977/**
33978 * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.
33979 * @param {module:key.Key} options.privateKey   The private key to reformat
33980 * @param {module:enums.publicKey} [options.keyType=module:enums.publicKey.rsa_encrypt_sign]
33981 * @param {String|Array<String>}  options.userIds
33982 *                             Assumes already in form of "User Name <username@email.com>"
33983 *                             If array is used, the first userId is set as primary user Id
33984 * @param {String}  options.passphrase The passphrase used to encrypt the resulting private key
33985 * @param {Number} [options.keyExpirationTime=0]
33986 *                             The number of seconds after the key creation time that the key expires
33987 * @param  {Date} date         Override the creation date of the key and the key signatures
33988 * @param  {Array<Object>} subkeys   (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
33989 *
33990 * @returns {Promise<module:key.Key>}
33991 * @async
33992 * @static
33993 */
33994async function reformat(options) {
33995  options = sanitizeKeyOptions(options);
33996
33997  try {
33998    const isDecrypted = options.privateKey.getKeys().every(key => key.isDecrypted());
33999    if (!isDecrypted) {
34000      await options.privateKey.decrypt();
34001    }
34002  } catch (err) {
34003    throw new Error('Key not decrypted');
34004  }
34005
34006  const packetlist = options.privateKey.toPacketlist();
34007  let secretKeyPacket;
34008  const secretSubkeyPackets = [];
34009  for (let i = 0; i < packetlist.length; i++) {
34010    if (packetlist[i].tag === _enums2.default.packet.secretKey) {
34011      secretKeyPacket = packetlist[i];
34012    } else if (packetlist[i].tag === _enums2.default.packet.secretSubkey) {
34013      secretSubkeyPackets.push(packetlist[i]);
34014    }
34015  }
34016  if (!secretKeyPacket) {
34017    throw new Error('Key does not contain a secret key packet');
34018  }
34019
34020  if (!options.subkeys) {
34021    options.subkeys = secretSubkeyPackets.map(() => ({}));
34022  }
34023
34024  if (options.subkeys.length !== secretSubkeyPackets.length) {
34025    throw new Error('Number of subkey options does not match number of subkeys');
34026  }
34027
34028  options.subkeys = options.subkeys.map(function (subkey, index) {
34029    return sanitizeKeyOptions(options.subkeys[index], options);
34030  });
34031
34032  return wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options);
34033
34034  function sanitizeKeyOptions(options, subkeyDefaults = {}) {
34035    options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;
34036    options.passphrase = _util2.default.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
34037    options.date = options.date || subkeyDefaults.date;
34038
34039    return options;
34040  }
34041}
34042
34043async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options) {
34044  // set passphrase protection
34045  if (options.passphrase) {
34046    await secretKeyPacket.encrypt(options.passphrase);
34047  }
34048
34049  await Promise.all(secretSubkeyPackets.map(async function (secretSubkeyPacket, index) {
34050    const subkeyPassphrase = options.subkeys[index].passphrase;
34051    if (subkeyPassphrase) {
34052      await secretSubkeyPacket.encrypt(subkeyPassphrase);
34053    }
34054  }));
34055
34056  const packetlist = new _packet2.default.List();
34057
34058  packetlist.push(secretKeyPacket);
34059
34060  await Promise.all(options.userIds.map(async function (userId, index) {
34061    function createdPreferredAlgos(algos, configAlgo) {
34062      if (configAlgo) {
34063        // Not `uncompressed` / `plaintext`
34064        const configIndex = algos.indexOf(configAlgo);
34065        if (configIndex >= 1) {
34066          // If it is included and not in first place,
34067          algos.splice(configIndex, 1); // remove it.
34068        }
34069        if (configIndex !== 0) {
34070          // If it was included and not in first place, or wasn't included,
34071          algos.unshift(configAlgo); // add it to the front.
34072        }
34073      }
34074      return algos;
34075    }
34076
34077    const userIdPacket = new _packet2.default.Userid();
34078    userIdPacket.format(userId);
34079
34080    const dataToSign = {};
34081    dataToSign.userId = userIdPacket;
34082    dataToSign.key = secretKeyPacket;
34083    const signaturePacket = new _packet2.default.Signature(options.date);
34084    signaturePacket.signatureType = _enums2.default.signature.cert_generic;
34085    signaturePacket.publicKeyAlgorithm = secretKeyPacket.algorithm;
34086    signaturePacket.hashAlgorithm = await getPreferredHashAlgo(null, secretKeyPacket);
34087    signaturePacket.keyFlags = [_enums2.default.keyFlags.certify_keys | _enums2.default.keyFlags.sign_data];
34088    signaturePacket.preferredSymmetricAlgorithms = createdPreferredAlgos([
34089    // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support)
34090    _enums2.default.symmetric.aes256, _enums2.default.symmetric.aes128, _enums2.default.symmetric.aes192, _enums2.default.symmetric.cast5, _enums2.default.symmetric.tripledes], _config2.default.encryption_cipher);
34091    if (_config2.default.aead_protect && _config2.default.aead_protect_version === 4) {
34092      signaturePacket.preferredAeadAlgorithms = createdPreferredAlgos([_enums2.default.aead.eax, _enums2.default.aead.ocb], _config2.default.aead_mode);
34093    }
34094    signaturePacket.preferredHashAlgorithms = createdPreferredAlgos([
34095    // prefer fast asm.js implementations (SHA-256). SHA-1 will not be secure much longer...move to bottom of list
34096    _enums2.default.hash.sha256, _enums2.default.hash.sha512, _enums2.default.hash.sha1], _config2.default.prefer_hash_algorithm);
34097    signaturePacket.preferredCompressionAlgorithms = createdPreferredAlgos([_enums2.default.compression.zlib, _enums2.default.compression.zip], _config2.default.compression);
34098    if (index === 0) {
34099      signaturePacket.isPrimaryUserID = true;
34100    }
34101    if (_config2.default.integrity_protect) {
34102      signaturePacket.features = [0];
34103      signaturePacket.features[0] |= _enums2.default.features.modification_detection;
34104    }
34105    if (_config2.default.aead_protect && _config2.default.aead_protect_version === 4) {
34106      signaturePacket.features || (signaturePacket.features = [0]);
34107      signaturePacket.features[0] |= _enums2.default.features.aead;
34108      signaturePacket.features[0] |= _enums2.default.features.v5_keys;
34109    }
34110    if (options.keyExpirationTime > 0) {
34111      signaturePacket.keyExpirationTime = options.keyExpirationTime;
34112      signaturePacket.keyNeverExpires = false;
34113    }
34114    await signaturePacket.sign(secretKeyPacket, dataToSign);
34115
34116    return { userIdPacket, signaturePacket };
34117  })).then(list => {
34118    list.forEach(({ userIdPacket, signaturePacket }) => {
34119      packetlist.push(userIdPacket);
34120      packetlist.push(signaturePacket);
34121    });
34122  });
34123
34124  await Promise.all(secretSubkeyPackets.map(async function (secretSubkeyPacket, index) {
34125    const subkeyOptions = options.subkeys[index];
34126    const dataToSign = {};
34127    dataToSign.key = secretKeyPacket;
34128    dataToSign.bind = secretSubkeyPacket;
34129    const subkeySignaturePacket = new _packet2.default.Signature(subkeyOptions.date);
34130    subkeySignaturePacket.signatureType = _enums2.default.signature.subkey_binding;
34131    subkeySignaturePacket.publicKeyAlgorithm = secretKeyPacket.algorithm;
34132    subkeySignaturePacket.hashAlgorithm = await getPreferredHashAlgo(null, secretSubkeyPacket);
34133    if (subkeyOptions.sign) {
34134      subkeySignaturePacket.keyFlags = [_enums2.default.keyFlags.sign_data];
34135      subkeySignaturePacket.embeddedSignature = await createSignaturePacket(dataToSign, null, secretSubkeyPacket, {
34136        signatureType: _enums2.default.signature.key_binding
34137      }, subkeyOptions.date);
34138    } else {
34139      subkeySignaturePacket.keyFlags = [_enums2.default.keyFlags.encrypt_communication | _enums2.default.keyFlags.encrypt_storage];
34140    }
34141    if (subkeyOptions.keyExpirationTime > 0) {
34142      subkeySignaturePacket.keyExpirationTime = subkeyOptions.keyExpirationTime;
34143      subkeySignaturePacket.keyNeverExpires = false;
34144    }
34145    await subkeySignaturePacket.sign(secretKeyPacket, dataToSign);
34146
34147    return { secretSubkeyPacket, subkeySignaturePacket };
34148  })).then(packets => {
34149    packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {
34150      packetlist.push(secretSubkeyPacket);
34151      packetlist.push(subkeySignaturePacket);
34152    });
34153  });
34154
34155  // Add revocation signature packet for creating a revocation certificate.
34156  // This packet should be removed before returning the key.
34157  const dataToSign = { key: secretKeyPacket };
34158  packetlist.push((await createSignaturePacket(dataToSign, null, secretKeyPacket, {
34159    signatureType: _enums2.default.signature.key_revocation,
34160    reasonForRevocationFlag: _enums2.default.reasonForRevocation.no_reason,
34161    reasonForRevocationString: ''
34162  }, options.date)));
34163
34164  // set passphrase protection
34165  if (options.passphrase) {
34166    secretKeyPacket.clearPrivateParams();
34167  }
34168
34169  await Promise.all(secretSubkeyPackets.map(async function (secretSubkeyPacket, index) {
34170    const subkeyPassphrase = options.subkeys[index].passphrase;
34171    if (subkeyPassphrase) {
34172      secretSubkeyPacket.clearPrivateParams();
34173    }
34174  }));
34175
34176  return new Key(packetlist);
34177}
34178
34179/**
34180 * Checks if a given certificate or binding signature is revoked
34181 * @param  {module:packet.SecretKey|
34182 *          module:packet.PublicKey}       primaryKey   The primary key packet
34183 * @param  {Object}                         dataToVerify The data to check
34184 * @param  {Array<module:packet.Signature>} revocations  The revocation signatures to check
34185 * @param  {module:packet.Signature}        signature    The certificate or signature to check
34186 * @param  {module:packet.PublicSubkey|
34187 *          module:packet.SecretSubkey|
34188 *          module:packet.PublicKey|
34189 *          module:packet.SecretKey} key, optional The key packet to check the signature
34190 * @param  {Date}                     date          Use the given date instead of the current time
34191 * @returns {Promise<Boolean>}                      True if the signature revokes the data
34192 * @async
34193 */
34194async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date()) {
34195  key = key || primaryKey;
34196  const normDate = _util2.default.normalizeDate(date);
34197  const revocationKeyIds = [];
34198  await Promise.all(revocations.map(async function (revocationSignature) {
34199    if (
34200    // Note: a third-party revocation signature could legitimately revoke a
34201    // self-signature if the signature has an authorized revocation key.
34202    // However, we don't support passing authorized revocation keys, nor
34203    // verifying such revocation signatures. Instead, we indicate an error
34204    // when parsing a key with an authorized revocation key, and ignore
34205    // third-party revocation signatures here. (It could also be revoking a
34206    // third-party key certification, which should only affect
34207    // `verifyAllCertifications`.)
34208    (!signature || revocationSignature.issuerKeyId.equals(signature.issuerKeyId)) && !(_config2.default.revocations_expire && revocationSignature.isExpired(normDate)) && (revocationSignature.verified || (await revocationSignature.verify(key, signatureType, dataToVerify)))) {
34209      // TODO get an identifier of the revoked object instead
34210      revocationKeyIds.push(revocationSignature.issuerKeyId);
34211      return true;
34212    }
34213    return false;
34214  }));
34215  // TODO further verify that this is the signature that should be revoked
34216  if (signature) {
34217    signature.revoked = revocationKeyIds.some(keyId => keyId.equals(signature.issuerKeyId)) ? true : signature.revoked || false;
34218    return signature.revoked;
34219  }
34220  return revocationKeyIds.length > 0;
34221}
34222
34223function isDataExpired(keyPacket, signature, date = new Date()) {
34224  const normDate = _util2.default.normalizeDate(date);
34225  if (normDate !== null) {
34226    const expirationTime = getExpirationTime(keyPacket, signature);
34227    return !(keyPacket.created <= normDate && normDate <= expirationTime) || signature && signature.isExpired(date);
34228  }
34229  return false;
34230}
34231
34232function getExpirationTime(keyPacket, signature) {
34233  let expirationTime;
34234  // check V4 expiration time
34235  if (signature.keyNeverExpires === false) {
34236    expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;
34237  }
34238  return expirationTime ? new Date(expirationTime) : Infinity;
34239}
34240
34241/**
34242 * Check if signature has revocation key sub packet (not supported by OpenPGP.js)
34243 * and throw error if found
34244 * @param {module:packet.Signature} signature The certificate or signature to check
34245 * @param {type/keyid} keyId Check only certificates or signatures from a certain issuer key ID
34246 */
34247function checkRevocationKey(signature, keyId) {
34248  if (signature.revocationKeyClass !== null && signature.issuerKeyId.equals(keyId)) {
34249    throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');
34250  }
34251}
34252
34253/**
34254 * Returns the preferred signature hash algorithm of a key
34255 * @param  {module:key.Key} key (optional) the key to get preferences from
34256 * @param  {module:packet.SecretKey|module:packet.SecretSubkey} keyPacket key packet used for signing
34257 * @param  {Date} date (optional) use the given date for verification instead of the current time
34258 * @param  {Object} userId (optional) user ID
34259 * @returns {Promise<String>}
34260 * @async
34261 */
34262async function getPreferredHashAlgo(key, keyPacket, date = new Date(), userId = {}) {
34263  let hash_algo = _config2.default.prefer_hash_algorithm;
34264  let pref_algo = hash_algo;
34265  if (key instanceof Key) {
34266    const primaryUser = await key.getPrimaryUser(date, userId);
34267    if (primaryUser && primaryUser.selfCertification.preferredHashAlgorithms) {
34268      var _primaryUser$selfCert = _slicedToArray(primaryUser.selfCertification.preferredHashAlgorithms, 1);
34269
34270      pref_algo = _primaryUser$selfCert[0];
34271
34272      hash_algo = _crypto2.default.hash.getHashByteLength(hash_algo) <= _crypto2.default.hash.getHashByteLength(pref_algo) ? pref_algo : hash_algo;
34273    }
34274  }
34275  switch (Object.getPrototypeOf(keyPacket)) {
34276    case _packet2.default.SecretKey.prototype:
34277    case _packet2.default.PublicKey.prototype:
34278    case _packet2.default.SecretSubkey.prototype:
34279    case _packet2.default.PublicSubkey.prototype:
34280      switch (keyPacket.algorithm) {
34281        case 'ecdh':
34282        case 'ecdsa':
34283        case 'eddsa':
34284          pref_algo = _crypto2.default.publicKey.elliptic.getPreferredHashAlgo(keyPacket.params[0]);
34285      }
34286  }
34287  return _crypto2.default.hash.getHashByteLength(hash_algo) <= _crypto2.default.hash.getHashByteLength(pref_algo) ? pref_algo : hash_algo;
34288}
34289
34290/**
34291 * Returns the preferred symmetric/aead algorithm for a set of keys
34292 * @param  {symmetric|aead} type Type of preference to return
34293 * @param  {Array<module:key.Key>} keys Set of keys
34294 * @param  {Date} date (optional) use the given date for verification instead of the current time
34295 * @param  {Array} userIds (optional) user IDs
34296 * @returns {Promise<module:enums.symmetric>}   Preferred symmetric algorithm
34297 * @async
34298 */
34299async function getPreferredAlgo(type, keys, date = new Date(), userIds = []) {
34300  const prefProperty = type === 'symmetric' ? 'preferredSymmetricAlgorithms' : 'preferredAeadAlgorithms';
34301  const defaultAlgo = type === 'symmetric' ? _enums2.default.symmetric.aes128 : _enums2.default.aead.eax;
34302  const prioMap = {};
34303  await Promise.all(keys.map(async function (key, i) {
34304    const primaryUser = await key.getPrimaryUser(date, userIds[i]);
34305    if (!primaryUser || !primaryUser.selfCertification[prefProperty]) {
34306      return defaultAlgo;
34307    }
34308    primaryUser.selfCertification[prefProperty].forEach(function (algo, index) {
34309      const entry = prioMap[algo] || (prioMap[algo] = { prio: 0, count: 0, algo: algo });
34310      entry.prio += 64 >> index;
34311      entry.count++;
34312    });
34313  }));
34314  let prefAlgo = { prio: 0, algo: defaultAlgo };
34315  Object.values(prioMap).forEach(({ prio, count, algo }) => {
34316    try {
34317      if (algo !== _enums2.default[type].plaintext && algo !== _enums2.default[type].idea && // not implemented
34318      _enums2.default.read(_enums2.default[type], algo) && // known algorithm
34319      count === keys.length && // available for all keys
34320      prio > prefAlgo.prio) {
34321        prefAlgo = prioMap[algo];
34322      }
34323    } catch (e) {}
34324  });
34325  return prefAlgo.algo;
34326}
34327
34328/**
34329 * Returns whether aead is supported by all keys in the set
34330 * @param  {Array<module:key.Key>} keys Set of keys
34331 * @param  {Date} date (optional) use the given date for verification instead of the current time
34332 * @param  {Array} userIds (optional) user IDs
34333 * @returns {Promise<Boolean>}
34334 * @async
34335 */
34336async function isAeadSupported(keys, date = new Date(), userIds = []) {
34337  let supported = true;
34338  // TODO replace when Promise.some or Promise.any are implemented
34339  await Promise.all(keys.map(async function (key, i) {
34340    const primaryUser = await key.getPrimaryUser(date, userIds[i]);
34341    if (!primaryUser || !primaryUser.selfCertification.features || !(primaryUser.selfCertification.features[0] & _enums2.default.features.aead)) {
34342      supported = false;
34343    }
34344  }));
34345  return supported;
34346}
34347
34348},{"./config":80,"./crypto":95,"./encoding/armor":112,"./enums":114,"./packet":126,"./util":153}],118:[function(require,module,exports){
34349'use strict';
34350
34351Object.defineProperty(exports, "__esModule", {
34352  value: true
34353});
34354
34355var _keyring = require('./keyring.js');
34356
34357var _keyring2 = _interopRequireDefault(_keyring);
34358
34359var _localstore = require('./localstore.js');
34360
34361var _localstore2 = _interopRequireDefault(_localstore);
34362
34363function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
34364
34365/**
34366 * @fileoverview Functions dealing with storage of the keyring.
34367 * @see module:keyring/keyring
34368 * @see module:keyring/localstore
34369 * @module keyring
34370 */
34371_keyring2.default.localstore = _localstore2.default;
34372
34373exports.default = _keyring2.default;
34374
34375},{"./keyring.js":119,"./localstore.js":120}],119:[function(require,module,exports){
34376'use strict';
34377
34378Object.defineProperty(exports, "__esModule", {
34379  value: true
34380});
34381
34382var _key = require('../key');
34383
34384var _localstore = require('./localstore');
34385
34386var _localstore2 = _interopRequireDefault(_localstore);
34387
34388function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
34389
34390/**
34391 * Initialization routine for the keyring.
34392 * @constructor
34393 * @param {keyring/localstore} [storeHandler] class implementing loadPublic(), loadPrivate(), storePublic(), and storePrivate() methods
34394 */
34395// GPG4Browsers - An OpenPGP implementation in javascript
34396// Copyright (C) 2011 Recurity Labs GmbH
34397//
34398// This library is free software; you can redistribute it and/or
34399// modify it under the terms of the GNU Lesser General Public
34400// License as published by the Free Software Foundation; either
34401// version 3.0 of the License, or (at your option) any later version.
34402//
34403// This library is distributed in the hope that it will be useful,
34404// but WITHOUT ANY WARRANTY; without even the implied warranty of
34405// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
34406// Lesser General Public License for more details.
34407//
34408// You should have received a copy of the GNU Lesser General Public
34409// License along with this library; if not, write to the Free Software
34410// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
34411
34412/**
34413 * @fileoverview Provides the Keyring class
34414 * @requires key
34415 * @requires keyring/localstore
34416 * @module keyring/keyring
34417 */
34418
34419function Keyring(storeHandler) {
34420  this.storeHandler = storeHandler || new _localstore2.default();
34421}
34422
34423/**
34424 * Calls the storeHandler to load the keys
34425 * @async
34426 */
34427Keyring.prototype.load = async function () {
34428  this.publicKeys = new KeyArray((await this.storeHandler.loadPublic()));
34429  this.privateKeys = new KeyArray((await this.storeHandler.loadPrivate()));
34430};
34431
34432/**
34433 * Calls the storeHandler to save the keys
34434 * @async
34435 */
34436Keyring.prototype.store = async function () {
34437  await Promise.all([this.storeHandler.storePublic(this.publicKeys.keys), this.storeHandler.storePrivate(this.privateKeys.keys)]);
34438};
34439
34440/**
34441 * Clear the keyring - erase all the keys
34442 */
34443Keyring.prototype.clear = function () {
34444  this.publicKeys.keys = [];
34445  this.privateKeys.keys = [];
34446};
34447
34448/**
34449 * Searches the keyring for keys having the specified key id
34450 * @param {String} keyId provided as string of lowercase hex number
34451 * withouth 0x prefix (can be 16-character key ID or fingerprint)
34452 * @param  {Boolean} deep if true search also in subkeys
34453 * @returns {Array<module:key.Key>|null} keys found or null
34454 */
34455Keyring.prototype.getKeysForId = function (keyId, deep) {
34456  let result = [];
34457  result = result.concat(this.publicKeys.getForId(keyId, deep) || []);
34458  result = result.concat(this.privateKeys.getForId(keyId, deep) || []);
34459  return result.length ? result : null;
34460};
34461
34462/**
34463 * Removes keys having the specified key id from the keyring
34464 * @param {String} keyId provided as string of lowercase hex number
34465 * withouth 0x prefix (can be 16-character key ID or fingerprint)
34466 * @returns {Array<module:key.Key>|null} keys found or null
34467 */
34468Keyring.prototype.removeKeysForId = function (keyId) {
34469  let result = [];
34470  result = result.concat(this.publicKeys.removeForId(keyId) || []);
34471  result = result.concat(this.privateKeys.removeForId(keyId) || []);
34472  return result.length ? result : null;
34473};
34474
34475/**
34476 * Get all public and private keys
34477 * @returns {Array<module:key.Key>} all keys
34478 */
34479Keyring.prototype.getAllKeys = function () {
34480  return this.publicKeys.keys.concat(this.privateKeys.keys);
34481};
34482
34483/**
34484 * Array of keys
34485 * @param {Array<module:key.Key>} keys The keys to store in this array
34486 */
34487function KeyArray(keys) {
34488  this.keys = keys;
34489}
34490
34491/**
34492 * Searches all keys in the KeyArray matching the address or address part of the user ids
34493 * @param {String} email email address to search for
34494 * @returns {Array<module:key.Key>} The public keys associated with provided email address.
34495 */
34496KeyArray.prototype.getForAddress = function (email) {
34497  const results = [];
34498  for (let i = 0; i < this.keys.length; i++) {
34499    if (emailCheck(email, this.keys[i])) {
34500      results.push(this.keys[i]);
34501    }
34502  }
34503  return results;
34504};
34505
34506/**
34507 * Checks a key to see if it matches the specified email address
34508 * @private
34509 * @param {String} email email address to search for
34510 * @param {module:key.Key} key The key to be checked.
34511 * @returns {Boolean} True if the email address is defined in the specified key
34512 */
34513function emailCheck(email, key) {
34514  email = email.toLowerCase();
34515  // escape email before using in regular expression
34516  const emailEsc = email.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
34517  const emailRegex = new RegExp('<' + emailEsc + '>');
34518  const userIds = key.getUserIds();
34519  for (let i = 0; i < userIds.length; i++) {
34520    const userId = userIds[i].toLowerCase();
34521    if (email === userId || emailRegex.test(userId)) {
34522      return true;
34523    }
34524  }
34525  return false;
34526}
34527
34528/**
34529 * Checks a key to see if it matches the specified keyid
34530 * @private
34531 * @param {String} keyId provided as string of lowercase hex number
34532 * withouth 0x prefix (can be 16-character key ID or fingerprint)
34533 * @param {module:key.Key|module:key.SubKey} key The key to be checked
34534 * @returns {Boolean} True if key has the specified keyid
34535 */
34536function keyIdCheck(keyId, key) {
34537  if (keyId.length === 16) {
34538    return keyId === key.getKeyId().toHex();
34539  }
34540  return keyId === key.getFingerprint();
34541}
34542
34543/**
34544 * Searches the KeyArray for a key having the specified key id
34545 * @param {String} keyId provided as string of lowercase hex number
34546 * withouth 0x prefix (can be 16-character key ID or fingerprint)
34547 * @param  {Boolean} deep if true search also in subkeys
34548 * @returns {module:key.Key|null} key found or null
34549 */
34550KeyArray.prototype.getForId = function (keyId, deep) {
34551  for (let i = 0; i < this.keys.length; i++) {
34552    if (keyIdCheck(keyId, this.keys[i])) {
34553      return this.keys[i];
34554    }
34555    if (deep && this.keys[i].subKeys.length) {
34556      for (let j = 0; j < this.keys[i].subKeys.length; j++) {
34557        if (keyIdCheck(keyId, this.keys[i].subKeys[j])) {
34558          return this.keys[i];
34559        }
34560      }
34561    }
34562  }
34563  return null;
34564};
34565
34566/**
34567 * Imports a key from an ascii armored message
34568 * @param {String} armored message to read the keys/key from
34569 * @returns {Promise<Array<Error>|null>} array of error objects or null
34570 * @async
34571 */
34572KeyArray.prototype.importKey = async function (armored) {
34573  const imported = await (0, _key.readArmored)(armored);
34574  for (let i = 0; i < imported.keys.length; i++) {
34575    const key = imported.keys[i];
34576    // check if key already in key array
34577    const keyidHex = key.getKeyId().toHex();
34578    const keyFound = this.getForId(keyidHex);
34579    if (keyFound) {
34580      await keyFound.update(key);
34581    } else {
34582      this.push(key);
34583    }
34584  }
34585  return imported.err ? imported.err : null;
34586};
34587
34588/**
34589 * Add key to KeyArray
34590 * @param {module:key.Key} key The key that will be added to the keyring
34591 * @returns {Number} The new length of the KeyArray
34592 */
34593KeyArray.prototype.push = function (key) {
34594  return this.keys.push(key);
34595};
34596
34597/**
34598 * Removes a key with the specified keyid from the keyring
34599 * @param {String} keyId provided as string of lowercase hex number
34600 * withouth 0x prefix (can be 16-character key ID or fingerprint)
34601 * @returns {module:key.Key|null} The key object which has been removed or null
34602 */
34603KeyArray.prototype.removeForId = function (keyId) {
34604  for (let i = 0; i < this.keys.length; i++) {
34605    if (keyIdCheck(keyId, this.keys[i])) {
34606      return this.keys.splice(i, 1)[0];
34607    }
34608  }
34609  return null;
34610};
34611
34612exports.default = Keyring;
34613
34614},{"../key":117,"./localstore":120}],120:[function(require,module,exports){
34615'use strict';
34616
34617Object.defineProperty(exports, "__esModule", {
34618  value: true
34619});
34620
34621var _webStreamTools = require('web-stream-tools');
34622
34623var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
34624
34625var _config = require('../config');
34626
34627var _config2 = _interopRequireDefault(_config);
34628
34629var _key = require('../key');
34630
34631var _util = require('../util');
34632
34633var _util2 = _interopRequireDefault(_util);
34634
34635function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
34636
34637/**
34638 * The class that deals with storage of the keyring.
34639 * Currently the only option is to use HTML5 local storage.
34640 * @constructor
34641 * @param {String} prefix prefix for itemnames in localstore
34642 */
34643// GPG4Browsers - An OpenPGP implementation in javascript
34644// Copyright (C) 2011 Recurity Labs GmbH
34645//
34646// This library is free software; you can redistribute it and/or
34647// modify it under the terms of the GNU Lesser General Public
34648// License as published by the Free Software Foundation; either
34649// version 3.0 of the License, or (at your option) any later version.
34650//
34651// This library is distributed in the hope that it will be useful,
34652// but WITHOUT ANY WARRANTY; without even the implied warranty of
34653// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
34654// Lesser General Public License for more details.
34655//
34656// You should have received a copy of the GNU Lesser General Public
34657// License along with this library; if not, write to the Free Software
34658// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
34659
34660/**
34661 * @fileoverview Provides the LocalStore class
34662 * @requires web-stream-tools
34663 * @requires config
34664 * @requires key
34665 * @requires util
34666 * @module keyring/localstore
34667 */
34668
34669function LocalStore(prefix) {
34670  prefix = prefix || 'openpgp-';
34671  this.publicKeysItem = prefix + this.publicKeysItem;
34672  this.privateKeysItem = prefix + this.privateKeysItem;
34673  if (typeof window !== 'undefined' && window.localStorage) {
34674    this.storage = window.localStorage;
34675  } else {
34676    this.storage = new (require('node-localstorage').LocalStorage)(_config2.default.node_store);
34677  }
34678}
34679
34680/*
34681 * Declare the localstore itemnames
34682 */
34683LocalStore.prototype.publicKeysItem = 'public-keys';
34684LocalStore.prototype.privateKeysItem = 'private-keys';
34685
34686/**
34687 * Load the public keys from HTML5 local storage.
34688 * @returns {Array<module:key.Key>} array of keys retrieved from localstore
34689 * @async
34690 */
34691LocalStore.prototype.loadPublic = async function () {
34692  return loadKeys(this.storage, this.publicKeysItem);
34693};
34694
34695/**
34696 * Load the private keys from HTML5 local storage.
34697 * @returns {Array<module:key.Key>} array of keys retrieved from localstore
34698 * @async
34699 */
34700LocalStore.prototype.loadPrivate = async function () {
34701  return loadKeys(this.storage, this.privateKeysItem);
34702};
34703
34704async function loadKeys(storage, itemname) {
34705  const armoredKeys = JSON.parse(storage.getItem(itemname));
34706  const keys = [];
34707  if (armoredKeys !== null && armoredKeys.length !== 0) {
34708    let key;
34709    for (let i = 0; i < armoredKeys.length; i++) {
34710      key = await (0, _key.readArmored)(armoredKeys[i]);
34711      if (!key.err) {
34712        keys.push(key.keys[0]);
34713      } else {
34714        _util2.default.print_debug("Error reading armored key from keyring index: " + i);
34715      }
34716    }
34717  }
34718  return keys;
34719}
34720
34721/**
34722 * Saves the current state of the public keys to HTML5 local storage.
34723 * The key array gets stringified using JSON
34724 * @param {Array<module:key.Key>} keys array of keys to save in localstore
34725 * @async
34726 */
34727LocalStore.prototype.storePublic = async function (keys) {
34728  await storeKeys(this.storage, this.publicKeysItem, keys);
34729};
34730
34731/**
34732 * Saves the current state of the private keys to HTML5 local storage.
34733 * The key array gets stringified using JSON
34734 * @param {Array<module:key.Key>} keys array of keys to save in localstore
34735 * @async
34736 */
34737LocalStore.prototype.storePrivate = async function (keys) {
34738  await storeKeys(this.storage, this.privateKeysItem, keys);
34739};
34740
34741async function storeKeys(storage, itemname, keys) {
34742  if (keys.length) {
34743    const armoredKeys = await Promise.all(keys.map(key => _webStreamTools2.default.readToEnd(key.armor())));
34744    storage.setItem(itemname, JSON.stringify(armoredKeys));
34745  } else {
34746    storage.removeItem(itemname);
34747  }
34748}
34749
34750exports.default = LocalStore;
34751
34752},{"../config":80,"../key":117,"../util":153,"node-localstorage":"node-localstorage","web-stream-tools":76}],121:[function(require,module,exports){
34753'use strict';
34754
34755Object.defineProperty(exports, "__esModule", {
34756  value: true
34757});
34758exports.Message = Message;
34759exports.encryptSessionKey = encryptSessionKey;
34760exports.createSignaturePackets = createSignaturePackets;
34761exports.createVerificationObjects = createVerificationObjects;
34762exports.readArmored = readArmored;
34763exports.read = read;
34764exports.fromText = fromText;
34765exports.fromBinary = fromBinary;
34766
34767var _webStreamTools = require('web-stream-tools');
34768
34769var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
34770
34771var _armor = require('./encoding/armor');
34772
34773var _armor2 = _interopRequireDefault(_armor);
34774
34775var _keyid = require('./type/keyid');
34776
34777var _keyid2 = _interopRequireDefault(_keyid);
34778
34779var _config = require('./config');
34780
34781var _config2 = _interopRequireDefault(_config);
34782
34783var _crypto = require('./crypto');
34784
34785var _crypto2 = _interopRequireDefault(_crypto);
34786
34787var _enums = require('./enums');
34788
34789var _enums2 = _interopRequireDefault(_enums);
34790
34791var _util = require('./util');
34792
34793var _util2 = _interopRequireDefault(_util);
34794
34795var _packet = require('./packet');
34796
34797var _packet2 = _interopRequireDefault(_packet);
34798
34799var _signature = require('./signature');
34800
34801var _key = require('./key');
34802
34803function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
34804
34805/**
34806 * @class
34807 * @classdesc Class that represents an OpenPGP message.
34808 * Can be an encrypted message, signed message, compressed message or literal message
34809 * @param  {module:packet.List} packetlist The packets that form this message
34810 * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}
34811 */
34812
34813// GPG4Browsers - An OpenPGP implementation in javascript
34814// Copyright (C) 2011 Recurity Labs GmbH
34815//
34816// This library is free software; you can redistribute it and/or
34817// modify it under the terms of the GNU Lesser General Public
34818// License as published by the Free Software Foundation; either
34819// version 3.0 of the License, or (at your option) any later version.
34820//
34821// This library is distributed in the hope that it will be useful,
34822// but WITHOUT ANY WARRANTY; without even the implied warranty of
34823// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
34824// Lesser General Public License for more details.
34825//
34826// You should have received a copy of the GNU Lesser General Public
34827// License along with this library; if not, write to the Free Software
34828// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
34829
34830/**
34831 * @requires web-stream-tools
34832 * @requires encoding/armor
34833 * @requires type/keyid
34834 * @requires config
34835 * @requires crypto
34836 * @requires enums
34837 * @requires util
34838 * @requires packet
34839 * @requires signature
34840 * @requires key
34841 * @module message
34842 */
34843
34844function Message(packetlist) {
34845  if (!(this instanceof Message)) {
34846    return new Message(packetlist);
34847  }
34848  this.packets = packetlist || new _packet2.default.List();
34849}
34850
34851/**
34852 * Returns the key IDs of the keys to which the session key is encrypted
34853 * @returns {Array<module:type/keyid>} array of keyid objects
34854 */
34855Message.prototype.getEncryptionKeyIds = function () {
34856  const keyIds = [];
34857  const pkESKeyPacketlist = this.packets.filterByTag(_enums2.default.packet.publicKeyEncryptedSessionKey);
34858  pkESKeyPacketlist.forEach(function (packet) {
34859    keyIds.push(packet.publicKeyId);
34860  });
34861  return keyIds;
34862};
34863
34864/**
34865 * Returns the key IDs of the keys that signed the message
34866 * @returns {Array<module:type/keyid>} array of keyid objects
34867 */
34868Message.prototype.getSigningKeyIds = function () {
34869  const keyIds = [];
34870  const msg = this.unwrapCompressed();
34871  // search for one pass signatures
34872  const onePassSigList = msg.packets.filterByTag(_enums2.default.packet.onePassSignature);
34873  onePassSigList.forEach(function (packet) {
34874    keyIds.push(packet.issuerKeyId);
34875  });
34876  // if nothing found look for signature packets
34877  if (!keyIds.length) {
34878    const signatureList = msg.packets.filterByTag(_enums2.default.packet.signature);
34879    signatureList.forEach(function (packet) {
34880      keyIds.push(packet.issuerKeyId);
34881    });
34882  }
34883  return keyIds;
34884};
34885
34886/**
34887 * Decrypt the message. Either a private key, a session key, or a password must be specified.
34888 * @param  {Array<Key>} privateKeys     (optional) private keys with decrypted secret data
34889 * @param  {Array<String>} passwords    (optional) passwords used to decrypt
34890 * @param  {Array<Object>} sessionKeys  (optional) session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
34891 * @param  {Boolean} streaming          (optional) whether to process data as a stream
34892 * @returns {Promise<Message>}             new message with decrypted content
34893 * @async
34894 */
34895Message.prototype.decrypt = async function (privateKeys, passwords, sessionKeys, streaming) {
34896  const keyObjs = sessionKeys || (await this.decryptSessionKeys(privateKeys, passwords));
34897
34898  const symEncryptedPacketlist = this.packets.filterByTag(_enums2.default.packet.symmetricallyEncrypted, _enums2.default.packet.symEncryptedIntegrityProtected, _enums2.default.packet.symEncryptedAEADProtected);
34899
34900  if (symEncryptedPacketlist.length === 0) {
34901    return this;
34902  }
34903
34904  const symEncryptedPacket = symEncryptedPacketlist[0];
34905  let exception = null;
34906  for (let i = 0; i < keyObjs.length; i++) {
34907    if (!keyObjs[i] || !_util2.default.isUint8Array(keyObjs[i].data) || !_util2.default.isString(keyObjs[i].algorithm)) {
34908      throw new Error('Invalid session key for decryption.');
34909    }
34910
34911    try {
34912      await symEncryptedPacket.decrypt(keyObjs[i].algorithm, keyObjs[i].data, streaming);
34913      break;
34914    } catch (e) {
34915      _util2.default.print_debug_error(e);
34916      exception = e;
34917    }
34918  }
34919  // We don't await stream.cancel here because it only returns when the other copy is canceled too.
34920  _webStreamTools2.default.cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.
34921  symEncryptedPacket.encrypted = null;
34922
34923  if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {
34924    throw exception || new Error('Decryption failed.');
34925  }
34926
34927  const resultMsg = new Message(symEncryptedPacket.packets);
34928  symEncryptedPacket.packets = new _packet2.default.List(); // remove packets after decryption
34929
34930  return resultMsg;
34931};
34932
34933/**
34934 * Decrypt encrypted session keys either with private keys or passwords.
34935 * @param  {Array<Key>} privateKeys    (optional) private keys with decrypted secret data
34936 * @param  {Array<String>} passwords   (optional) passwords used to decrypt
34937 * @returns {Promise<Array<{ data:      Uint8Array,
34938                             algorithm: String }>>} array of object with potential sessionKey, algorithm pairs
34939 * @async
34940 */
34941Message.prototype.decryptSessionKeys = async function (privateKeys, passwords) {
34942  let keyPackets = [];
34943
34944  let exception;
34945  if (passwords) {
34946    const symESKeyPacketlist = this.packets.filterByTag(_enums2.default.packet.symEncryptedSessionKey);
34947    if (!symESKeyPacketlist) {
34948      throw new Error('No symmetrically encrypted session key packet found.');
34949    }
34950    await Promise.all(passwords.map(async function (password, i) {
34951      let packets;
34952      if (i) {
34953        packets = new _packet2.default.List();
34954        await packets.read(symESKeyPacketlist.write());
34955      } else {
34956        packets = symESKeyPacketlist;
34957      }
34958      await Promise.all(packets.map(async function (keyPacket) {
34959        try {
34960          await keyPacket.decrypt(password);
34961          keyPackets.push(keyPacket);
34962        } catch (err) {
34963          _util2.default.print_debug_error(err);
34964        }
34965      }));
34966    }));
34967  } else if (privateKeys) {
34968    const pkESKeyPacketlist = this.packets.filterByTag(_enums2.default.packet.publicKeyEncryptedSessionKey);
34969    if (!pkESKeyPacketlist) {
34970      throw new Error('No public key encrypted session key packet found.');
34971    }
34972    await Promise.all(pkESKeyPacketlist.map(async function (keyPacket) {
34973      await Promise.all(privateKeys.map(async function (privateKey) {
34974        const primaryUser = await privateKey.getPrimaryUser(); // TODO: Pass userId from somewhere.
34975        let algos = [_enums2.default.symmetric.aes256, // Old OpenPGP.js default fallback
34976        _enums2.default.symmetric.aes128, // RFC4880bis fallback
34977        _enums2.default.symmetric.tripledes, // RFC4880 fallback
34978        _enums2.default.symmetric.cast5 // Golang OpenPGP fallback
34979        ];
34980        if (primaryUser && primaryUser.selfCertification.preferredSymmetricAlgorithms) {
34981          algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms);
34982        }
34983
34984        const privateKeyPackets = privateKey.getKeys(keyPacket.publicKeyId).map(key => key.keyPacket);
34985        await Promise.all(privateKeyPackets.map(async function (privateKeyPacket) {
34986          if (!privateKeyPacket) {
34987            return;
34988          }
34989          if (!privateKeyPacket.isDecrypted()) {
34990            throw new Error('Private key is not decrypted.');
34991          }
34992          try {
34993            await keyPacket.decrypt(privateKeyPacket);
34994            if (!algos.includes(_enums2.default.write(_enums2.default.symmetric, keyPacket.sessionKeyAlgorithm))) {
34995              throw new Error('A non-preferred symmetric algorithm was used.');
34996            }
34997            keyPackets.push(keyPacket);
34998          } catch (err) {
34999            _util2.default.print_debug_error(err);
35000            exception = err;
35001          }
35002        }));
35003      }));
35004      _webStreamTools2.default.cancel(keyPacket.encrypted); // Don't keep copy of encrypted data in memory.
35005      keyPacket.encrypted = null;
35006    }));
35007  } else {
35008    throw new Error('No key or password specified.');
35009  }
35010
35011  if (keyPackets.length) {
35012    // Return only unique session keys
35013    if (keyPackets.length > 1) {
35014      const seen = {};
35015      keyPackets = keyPackets.filter(function (item) {
35016        const k = item.sessionKeyAlgorithm + _util2.default.Uint8Array_to_str(item.sessionKey);
35017        if (seen.hasOwnProperty(k)) {
35018          return false;
35019        }
35020        seen[k] = true;
35021        return true;
35022      });
35023    }
35024
35025    return keyPackets.map(packet => ({ data: packet.sessionKey, algorithm: packet.sessionKeyAlgorithm }));
35026  }
35027  throw exception || new Error('Session key decryption failed.');
35028};
35029
35030/**
35031 * Get literal data that is the body of the message
35032 * @returns {(Uint8Array|null)} literal body of the message as Uint8Array
35033 */
35034Message.prototype.getLiteralData = function () {
35035  const msg = this.unwrapCompressed();
35036  const literal = msg.packets.findPacket(_enums2.default.packet.literal);
35037  return literal && literal.getBytes() || null;
35038};
35039
35040/**
35041 * Get filename from literal data packet
35042 * @returns {(String|null)} filename of literal data packet as string
35043 */
35044Message.prototype.getFilename = function () {
35045  const msg = this.unwrapCompressed();
35046  const literal = msg.packets.findPacket(_enums2.default.packet.literal);
35047  return literal && literal.getFilename() || null;
35048};
35049
35050/**
35051 * Get literal data as text
35052 * @returns {(String|null)} literal body of the message interpreted as text
35053 */
35054Message.prototype.getText = function () {
35055  const msg = this.unwrapCompressed();
35056  const literal = msg.packets.findPacket(_enums2.default.packet.literal);
35057  if (literal) {
35058    return literal.getText();
35059  }
35060  return null;
35061};
35062
35063/**
35064 * Encrypt the message either with public keys, passwords, or both at once.
35065 * @param  {Array<Key>} keys           (optional) public key(s) for message encryption
35066 * @param  {Array<String>} passwords   (optional) password(s) for message encryption
35067 * @param  {Object} sessionKey         (optional) session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
35068 * @param  {Boolean} wildcard          (optional) use a key ID of 0 instead of the public key IDs
35069 * @param  {Date} date                 (optional) override the creation date of the literal package
35070 * @param  {Array} userIds             (optional) user IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
35071 * @param  {Boolean} streaming         (optional) whether to process data as a stream
35072 * @returns {Promise<Message>}                   new message with encrypted content
35073 * @async
35074 */
35075Message.prototype.encrypt = async function (keys, passwords, sessionKey, wildcard = false, date = new Date(), userIds = [], streaming) {
35076  let symAlgo;
35077  let aeadAlgo;
35078  let symEncryptedPacket;
35079
35080  if (sessionKey) {
35081    if (!_util2.default.isUint8Array(sessionKey.data) || !_util2.default.isString(sessionKey.algorithm)) {
35082      throw new Error('Invalid session key for encryption.');
35083    }
35084    symAlgo = sessionKey.algorithm;
35085    aeadAlgo = sessionKey.aeadAlgorithm;
35086    sessionKey = sessionKey.data;
35087  } else if (keys && keys.length) {
35088    symAlgo = _enums2.default.read(_enums2.default.symmetric, (await (0, _key.getPreferredAlgo)('symmetric', keys, date, userIds)));
35089    if (_config2.default.aead_protect && _config2.default.aead_protect_version === 4 && (await (0, _key.isAeadSupported)(keys, date, userIds))) {
35090      aeadAlgo = _enums2.default.read(_enums2.default.aead, (await (0, _key.getPreferredAlgo)('aead', keys, date, userIds)));
35091    }
35092  } else if (passwords && passwords.length) {
35093    symAlgo = _enums2.default.read(_enums2.default.symmetric, _config2.default.encryption_cipher);
35094    aeadAlgo = _enums2.default.read(_enums2.default.aead, _config2.default.aead_mode);
35095  } else {
35096    throw new Error('No keys, passwords, or session key provided.');
35097  }
35098
35099  if (!sessionKey) {
35100    sessionKey = await _crypto2.default.generateSessionKey(symAlgo);
35101  }
35102
35103  const msg = await encryptSessionKey(sessionKey, symAlgo, aeadAlgo, keys, passwords, wildcard, date, userIds);
35104
35105  if (_config2.default.aead_protect && (_config2.default.aead_protect_version !== 4 || aeadAlgo)) {
35106    symEncryptedPacket = new _packet2.default.SymEncryptedAEADProtected();
35107    symEncryptedPacket.aeadAlgorithm = aeadAlgo;
35108  } else if (_config2.default.integrity_protect) {
35109    symEncryptedPacket = new _packet2.default.SymEncryptedIntegrityProtected();
35110  } else {
35111    symEncryptedPacket = new _packet2.default.SymmetricallyEncrypted();
35112  }
35113  symEncryptedPacket.packets = this.packets;
35114
35115  await symEncryptedPacket.encrypt(symAlgo, sessionKey, streaming);
35116
35117  msg.packets.push(symEncryptedPacket);
35118  symEncryptedPacket.packets = new _packet2.default.List(); // remove packets after encryption
35119  return {
35120    message: msg,
35121    sessionKey: {
35122      data: sessionKey,
35123      algorithm: symAlgo,
35124      aeadAlgorithm: aeadAlgo
35125    }
35126  };
35127};
35128
35129/**
35130 * Encrypt a session key either with public keys, passwords, or both at once.
35131 * @param  {Uint8Array} sessionKey     session key for encryption
35132 * @param  {String} symAlgo            session key algorithm
35133 * @param  {String} aeadAlgo           (optional) aead algorithm, e.g. 'eax' or 'ocb'
35134 * @param  {Array<Key>} publicKeys     (optional) public key(s) for message encryption
35135 * @param  {Array<String>} passwords   (optional) for message encryption
35136 * @param  {Boolean} wildcard          (optional) use a key ID of 0 instead of the public key IDs
35137 * @param  {Date} date                 (optional) override the date
35138 * @param  {Array} userIds             (optional) user IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
35139 * @returns {Promise<Message>}          new message with encrypted content
35140 * @async
35141 */
35142async function encryptSessionKey(sessionKey, symAlgo, aeadAlgo, publicKeys, passwords, wildcard = false, date = new Date(), userIds = []) {
35143  const packetlist = new _packet2.default.List();
35144
35145  if (publicKeys) {
35146    const results = await Promise.all(publicKeys.map(async function (publicKey) {
35147      const encryptionKey = await publicKey.getEncryptionKey(undefined, date, userIds);
35148      if (!encryptionKey) {
35149        throw new Error('Could not find valid key packet for encryption in key ' + publicKey.getKeyId().toHex());
35150      }
35151      const pkESKeyPacket = new _packet2.default.PublicKeyEncryptedSessionKey();
35152      pkESKeyPacket.publicKeyId = wildcard ? _keyid2.default.wildcard() : encryptionKey.getKeyId();
35153      pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm;
35154      pkESKeyPacket.sessionKey = sessionKey;
35155      pkESKeyPacket.sessionKeyAlgorithm = symAlgo;
35156      await pkESKeyPacket.encrypt(encryptionKey.keyPacket);
35157      delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption
35158      return pkESKeyPacket;
35159    }));
35160    packetlist.concat(results);
35161  }
35162  if (passwords) {
35163    const testDecrypt = async function testDecrypt(keyPacket, password) {
35164      try {
35165        await keyPacket.decrypt(password);
35166        return 1;
35167      } catch (e) {
35168        return 0;
35169      }
35170    };
35171
35172    const sum = (accumulator, currentValue) => accumulator + currentValue;
35173
35174    const encryptPassword = async function encryptPassword(sessionKey, symAlgo, aeadAlgo, password) {
35175      const symEncryptedSessionKeyPacket = new _packet2.default.SymEncryptedSessionKey();
35176      symEncryptedSessionKeyPacket.sessionKey = sessionKey;
35177      symEncryptedSessionKeyPacket.sessionKeyAlgorithm = symAlgo;
35178      if (aeadAlgo) {
35179        symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgo;
35180      }
35181      await symEncryptedSessionKeyPacket.encrypt(password);
35182
35183      if (_config2.default.password_collision_check) {
35184        const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));
35185        if (results.reduce(sum) !== 1) {
35186          return encryptPassword(sessionKey, symAlgo, password);
35187        }
35188      }
35189
35190      delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption
35191      return symEncryptedSessionKeyPacket;
35192    };
35193
35194    const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symAlgo, aeadAlgo, pwd)));
35195    packetlist.concat(results);
35196  }
35197
35198  return new Message(packetlist);
35199}
35200
35201/**
35202 * Sign the message (the literal data packet of the message)
35203 * @param  {Array<module:key.Key>}        privateKeys private keys with decrypted secret key data for signing
35204 * @param  {Signature} signature          (optional) any existing detached signature to add to the message
35205 * @param  {Date} date                    (optional) override the creation time of the signature
35206 * @param  {Array} userIds                (optional) user IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
35207 * @returns {Promise<Message>}             new message with signed content
35208 * @async
35209 */
35210Message.prototype.sign = async function (privateKeys = [], signature = null, date = new Date(), userIds = []) {
35211  const packetlist = new _packet2.default.List();
35212
35213  const literalDataPacket = this.packets.findPacket(_enums2.default.packet.literal);
35214  if (!literalDataPacket) {
35215    throw new Error('No literal data packet to sign.');
35216  }
35217
35218  let i;
35219  let existingSigPacketlist;
35220  // If data packet was created from Uint8Array, use binary, otherwise use text
35221  const signatureType = literalDataPacket.text === null ? _enums2.default.signature.binary : _enums2.default.signature.text;
35222
35223  if (signature) {
35224    existingSigPacketlist = signature.packets.filterByTag(_enums2.default.packet.signature);
35225    for (i = existingSigPacketlist.length - 1; i >= 0; i--) {
35226      const signaturePacket = existingSigPacketlist[i];
35227      const onePassSig = new _packet2.default.OnePassSignature();
35228      onePassSig.signatureType = signaturePacket.signatureType;
35229      onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;
35230      onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;
35231      onePassSig.issuerKeyId = signaturePacket.issuerKeyId;
35232      if (!privateKeys.length && i === 0) {
35233        onePassSig.flags = 1;
35234      }
35235      packetlist.push(onePassSig);
35236    }
35237  }
35238
35239  await Promise.all(Array.from(privateKeys).reverse().map(async function (privateKey, i) {
35240    if (privateKey.isPublic()) {
35241      throw new Error('Need private key for signing');
35242    }
35243    const signingKey = await privateKey.getSigningKey(undefined, date, userIds);
35244    if (!signingKey) {
35245      throw new Error('Could not find valid key packet for signing in key ' + privateKey.getKeyId().toHex());
35246    }
35247    const onePassSig = new _packet2.default.OnePassSignature();
35248    onePassSig.signatureType = signatureType;
35249    onePassSig.hashAlgorithm = await (0, _key.getPreferredHashAlgo)(privateKey, signingKey.keyPacket, date, userIds);
35250    onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm;
35251    onePassSig.issuerKeyId = signingKey.getKeyId();
35252    if (i === privateKeys.length - 1) {
35253      onePassSig.flags = 1;
35254    }
35255    return onePassSig;
35256  })).then(onePassSignatureList => {
35257    onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig));
35258  });
35259
35260  packetlist.push(literalDataPacket);
35261  packetlist.concat((await createSignaturePackets(literalDataPacket, privateKeys, signature, date)));
35262
35263  return new Message(packetlist);
35264};
35265
35266/**
35267 * Compresses the message (the literal and -if signed- signature data packets of the message)
35268 * @param  {module:enums.compression}   compression     compression algorithm to be used
35269 * @returns {module:message.Message}       new message with compressed content
35270 */
35271Message.prototype.compress = function (compression) {
35272  if (compression === _enums2.default.compression.uncompressed) {
35273    return this;
35274  }
35275
35276  const compressed = new _packet2.default.Compressed();
35277  compressed.packets = this.packets;
35278  compressed.algorithm = _enums2.default.read(_enums2.default.compression, compression);
35279
35280  const packetList = new _packet2.default.List();
35281  packetList.push(compressed);
35282
35283  return new Message(packetList);
35284};
35285
35286/**
35287 * Create a detached signature for the message (the literal data packet of the message)
35288 * @param  {Array<module:key.Key>}               privateKeys private keys with decrypted secret key data for signing
35289 * @param  {Signature} signature                 (optional) any existing detached signature
35290 * @param  {Date} date                           (optional) override the creation time of the signature
35291 * @param  {Array} userIds                       (optional) user IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
35292 * @returns {Promise<module:signature.Signature>} new detached signature of message content
35293 * @async
35294 */
35295Message.prototype.signDetached = async function (privateKeys = [], signature = null, date = new Date(), userIds = []) {
35296  const literalDataPacket = this.packets.findPacket(_enums2.default.packet.literal);
35297  if (!literalDataPacket) {
35298    throw new Error('No literal data packet to sign.');
35299  }
35300  return new _signature.Signature((await createSignaturePackets(literalDataPacket, privateKeys, signature, date, userIds)));
35301};
35302
35303/**
35304 * Create signature packets for the message
35305 * @param  {module:packet.Literal}             literalDataPacket the literal data packet to sign
35306 * @param  {Array<module:key.Key>}             privateKeys private keys with decrypted secret key data for signing
35307 * @param  {Signature} signature               (optional) any existing detached signature to append
35308 * @param  {Date} date                         (optional) override the creationtime of the signature
35309 * @param  {Array} userIds                     (optional) user IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
35310 * @returns {Promise<module:packet.List>} list of signature packets
35311 * @async
35312 */
35313async function createSignaturePackets(literalDataPacket, privateKeys, signature = null, date = new Date(), userIds = []) {
35314  const packetlist = new _packet2.default.List();
35315
35316  // If data packet was created from Uint8Array, use binary, otherwise use text
35317  const signatureType = literalDataPacket.text === null ? _enums2.default.signature.binary : _enums2.default.signature.text;
35318
35319  await Promise.all(privateKeys.map(async (privateKey, i) => {
35320    const userId = userIds[i];
35321    if (privateKey.isPublic()) {
35322      throw new Error('Need private key for signing');
35323    }
35324    const signingKey = await privateKey.getSigningKey(undefined, date, userId);
35325    if (!signingKey) {
35326      throw new Error(`Could not find valid signing key packet in key ${privateKey.getKeyId().toHex()}`);
35327    }
35328    return (0, _key.createSignaturePacket)(literalDataPacket, privateKey, signingKey.keyPacket, { signatureType }, date, userId);
35329  })).then(signatureList => {
35330    signatureList.forEach(signaturePacket => packetlist.push(signaturePacket));
35331  });
35332
35333  if (signature) {
35334    const existingSigPacketlist = signature.packets.filterByTag(_enums2.default.packet.signature);
35335    packetlist.concat(existingSigPacketlist);
35336  }
35337  return packetlist;
35338}
35339
35340/**
35341 * Verify message signatures
35342 * @param {Array<module:key.Key>} keys array of keys to verify signatures
35343 * @param {Date} date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time
35344 * @param  {Boolean} streaming (optional) whether to process data as a stream
35345 * @returns {Promise<Array<({keyid: module:type/keyid, valid: Boolean})>>} list of signer's keyid and validity of signature
35346 * @async
35347 */
35348Message.prototype.verify = async function (keys, date = new Date(), streaming) {
35349  const msg = this.unwrapCompressed();
35350  const literalDataList = msg.packets.filterByTag(_enums2.default.packet.literal);
35351  if (literalDataList.length !== 1) {
35352    throw new Error('Can only verify message with one literal data packet.');
35353  }
35354  const onePassSigList = msg.packets.filterByTag(_enums2.default.packet.onePassSignature).reverse();
35355  const signatureList = msg.packets.filterByTag(_enums2.default.packet.signature);
35356  if (onePassSigList.length && !signatureList.length && msg.packets.stream) {
35357    await Promise.all(onePassSigList.map(async onePassSig => {
35358      onePassSig.correspondingSig = new Promise((resolve, reject) => {
35359        onePassSig.correspondingSigResolve = resolve;
35360        onePassSig.correspondingSigReject = reject;
35361      });
35362      onePassSig.signatureData = _webStreamTools2.default.fromAsync(async () => (await onePassSig.correspondingSig).signatureData);
35363      onePassSig.hashed = await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, streaming);
35364    }));
35365    msg.packets.stream = _webStreamTools2.default.transformPair(msg.packets.stream, async (readable, writable) => {
35366      const reader = _webStreamTools2.default.getReader(readable);
35367      const writer = _webStreamTools2.default.getWriter(writable);
35368      try {
35369        for (let i = 0; i < onePassSigList.length; i++) {
35370          var _ref = await reader.read();
35371
35372          const signature = _ref.value;
35373
35374          onePassSigList[i].correspondingSigResolve(signature);
35375        }
35376        await reader.readToEnd();
35377        await writer.ready;
35378        await writer.close();
35379      } catch (e) {
35380        onePassSigList.forEach(onePassSig => {
35381          onePassSig.correspondingSigReject(e);
35382        });
35383        await writer.abort(e);
35384      }
35385    });
35386    return createVerificationObjects(onePassSigList, literalDataList, keys, date);
35387  }
35388  return createVerificationObjects(signatureList, literalDataList, keys, date);
35389};
35390
35391/**
35392 * Verify detached message signature
35393 * @param {Array<module:key.Key>} keys array of keys to verify signatures
35394 * @param {Signature} signature
35395 * @param {Date} date Verify the signature against the given date, i.e. check signature creation time < date < expiration time
35396 * @returns {Promise<Array<({keyid: module:type/keyid, valid: Boolean})>>} list of signer's keyid and validity of signature
35397 * @async
35398 */
35399Message.prototype.verifyDetached = function (signature, keys, date = new Date()) {
35400  const msg = this.unwrapCompressed();
35401  const literalDataList = msg.packets.filterByTag(_enums2.default.packet.literal);
35402  if (literalDataList.length !== 1) {
35403    throw new Error('Can only verify message with one literal data packet.');
35404  }
35405  const signatureList = signature.packets;
35406  return createVerificationObjects(signatureList, literalDataList, keys, date);
35407};
35408
35409/**
35410 * Create object containing signer's keyid and validity of signature
35411 * @param {module:packet.Signature} signature signature packets
35412 * @param {Array<module:packet.Literal>} literalDataList array of literal data packets
35413 * @param {Array<module:key.Key>} keys array of keys to verify signatures
35414 * @param {Date} date Verify the signature against the given date,
35415 *                    i.e. check signature creation time < date < expiration time
35416 * @returns {Promise<Array<{keyid: module:type/keyid,
35417 *                          valid: Boolean}>>} list of signer's keyid and validity of signature
35418 * @async
35419 */
35420async function createVerificationObject(signature, literalDataList, keys, date = new Date()) {
35421  let primaryKey = null;
35422  let signingKey = null;
35423  await Promise.all(keys.map(async function (key) {
35424    // Look for the unique key that matches issuerKeyId of signature
35425    const result = await key.getSigningKey(signature.issuerKeyId, null);
35426    if (result) {
35427      primaryKey = key;
35428      signingKey = result;
35429    }
35430  }));
35431
35432  const signaturePacket = signature.correspondingSig || signature;
35433  const verifiedSig = {
35434    keyid: signature.issuerKeyId,
35435    verified: (async () => {
35436      if (!signingKey) {
35437        return null;
35438      }
35439      const verified = await signature.verify(signingKey.keyPacket, signature.signatureType, literalDataList[0]);
35440      const sig = await signaturePacket;
35441      if (sig.isExpired(date) || !(sig.created >= signingKey.getCreationTime() && sig.created < (await (signingKey === primaryKey ? signingKey.getExpirationTime() : signingKey.getExpirationTime(primaryKey, date))))) {
35442        return null;
35443      }
35444      return verified;
35445    })(),
35446    signature: (async () => {
35447      const sig = await signaturePacket;
35448      const packetlist = new _packet2.default.List();
35449      packetlist.push(sig);
35450      return new _signature.Signature(packetlist);
35451    })()
35452  };
35453
35454  // Mark potential promise rejections as "handled". This is needed because in
35455  // some cases, we reject them before the user has a reasonable chance to
35456  // handle them (e.g. `await readToEnd(result.data); await result.verified` and
35457  // the data stream errors).
35458  verifiedSig.signature.catch(() => {});
35459  verifiedSig.verified.catch(() => {});
35460
35461  return verifiedSig;
35462}
35463
35464/**
35465 * Create list of objects containing signer's keyid and validity of signature
35466 * @param {Array<module:packet.Signature>} signatureList array of signature packets
35467 * @param {Array<module:packet.Literal>} literalDataList array of literal data packets
35468 * @param {Array<module:key.Key>} keys array of keys to verify signatures
35469 * @param {Date} date Verify the signature against the given date,
35470 *                    i.e. check signature creation time < date < expiration time
35471 * @returns {Promise<Array<{keyid: module:type/keyid,
35472 *                          valid: Boolean}>>} list of signer's keyid and validity of signature
35473 * @async
35474 */
35475async function createVerificationObjects(signatureList, literalDataList, keys, date = new Date()) {
35476  return Promise.all(signatureList.filter(function (signature) {
35477    return ['text', 'binary'].includes(_enums2.default.read(_enums2.default.signature, signature.signatureType));
35478  }).map(async function (signature) {
35479    return createVerificationObject(signature, literalDataList, keys, date);
35480  }));
35481}
35482
35483/**
35484 * Unwrap compressed message
35485 * @returns {module:message.Message} message Content of compressed message
35486 */
35487Message.prototype.unwrapCompressed = function () {
35488  const compressed = this.packets.filterByTag(_enums2.default.packet.compressed);
35489  if (compressed.length) {
35490    return new Message(compressed[0].packets);
35491  }
35492  return this;
35493};
35494
35495/**
35496 * Append signature to unencrypted message object
35497 * @param {String|Uint8Array} detachedSignature The detached ASCII-armored or Uint8Array PGP signature
35498 */
35499Message.prototype.appendSignature = async function (detachedSignature) {
35500  await this.packets.read(_util2.default.isUint8Array(detachedSignature) ? detachedSignature : (await _armor2.default.decode(detachedSignature)).data);
35501};
35502
35503/**
35504 * Returns ASCII armored text of message
35505 * @returns {ReadableStream<String>} ASCII armor
35506 */
35507Message.prototype.armor = function () {
35508  return _armor2.default.encode(_enums2.default.armor.message, this.packets.write());
35509};
35510
35511/**
35512 * reads an OpenPGP armored message and returns a message object
35513 * @param {String | ReadableStream<String>} armoredText text to be parsed
35514 * @returns {Promise<module:message.Message>} new message object
35515 * @async
35516 * @static
35517 */
35518async function readArmored(armoredText) {
35519  //TODO how do we want to handle bad text? Exception throwing
35520  //TODO don't accept non-message armored texts
35521  const streamType = _util2.default.isStream(armoredText);
35522  if (streamType === 'node') {
35523    armoredText = _webStreamTools2.default.nodeToWeb(armoredText);
35524  }
35525  const input = await _armor2.default.decode(armoredText);
35526  return read(input.data, streamType);
35527}
35528
35529/**
35530 * reads an OpenPGP message as byte array and returns a message object
35531 * @param {Uint8Array | ReadableStream<Uint8Array>} input    binary message
35532 * @param {Boolean} fromStream  whether the message was created from a Stream
35533 * @returns {Promise<module:message.Message>} new message object
35534 * @async
35535 * @static
35536 */
35537async function read(input, fromStream = _util2.default.isStream(input)) {
35538  const streamType = _util2.default.isStream(input);
35539  if (streamType === 'node') {
35540    input = _webStreamTools2.default.nodeToWeb(input);
35541  }
35542  const packetlist = new _packet2.default.List();
35543  await packetlist.read(input, fromStream);
35544  const message = new Message(packetlist);
35545  message.fromStream = fromStream;
35546  return message;
35547}
35548
35549/**
35550 * creates new message object from text
35551 * @param {String | ReadableStream<String>} text
35552 * @param {String} filename (optional)
35553 * @param {Date} date (optional)
35554 * @param {utf8|binary|text|mime} type (optional) data packet type
35555 * @returns {module:message.Message} new message object
35556 * @static
35557 */
35558function fromText(text, filename, date = new Date(), type = 'utf8') {
35559  const streamType = _util2.default.isStream(text);
35560  if (streamType === 'node') {
35561    text = _webStreamTools2.default.nodeToWeb(text);
35562  }
35563  const literalDataPacket = new _packet2.default.Literal(date);
35564  // text will be converted to UTF8
35565  literalDataPacket.setText(text, type);
35566  if (filename !== undefined) {
35567    literalDataPacket.setFilename(filename);
35568  }
35569  const literalDataPacketlist = new _packet2.default.List();
35570  literalDataPacketlist.push(literalDataPacket);
35571  const message = new Message(literalDataPacketlist);
35572  message.fromStream = streamType;
35573  return message;
35574}
35575
35576/**
35577 * creates new message object from binary data
35578 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes
35579 * @param {String} filename (optional)
35580 * @param {Date} date (optional)
35581 * @param {utf8|binary|text|mime} type (optional) data packet type
35582 * @returns {module:message.Message} new message object
35583 * @static
35584 */
35585function fromBinary(bytes, filename, date = new Date(), type = 'binary') {
35586  const streamType = _util2.default.isStream(bytes);
35587  if (!_util2.default.isUint8Array(bytes) && !streamType) {
35588    throw new Error('Data must be in the form of a Uint8Array or Stream');
35589  }
35590  if (streamType === 'node') {
35591    bytes = _webStreamTools2.default.nodeToWeb(bytes);
35592  }
35593
35594  const literalDataPacket = new _packet2.default.Literal(date);
35595  literalDataPacket.setBytes(bytes, type);
35596  if (filename !== undefined) {
35597    literalDataPacket.setFilename(filename);
35598  }
35599  const literalDataPacketlist = new _packet2.default.List();
35600  literalDataPacketlist.push(literalDataPacket);
35601  const message = new Message(literalDataPacketlist);
35602  message.fromStream = streamType;
35603  return message;
35604}
35605
35606},{"./config":80,"./crypto":95,"./encoding/armor":112,"./enums":114,"./key":117,"./packet":126,"./signature":146,"./type/keyid":149,"./util":153,"web-stream-tools":76}],122:[function(require,module,exports){
35607'use strict';
35608
35609Object.defineProperty(exports, "__esModule", {
35610  value: true
35611});
35612exports.initWorker = initWorker;
35613exports.getWorker = getWorker;
35614exports.destroyWorker = destroyWorker;
35615exports.generateKey = generateKey;
35616exports.reformatKey = reformatKey;
35617exports.revokeKey = revokeKey;
35618exports.decryptKey = decryptKey;
35619exports.encryptKey = encryptKey;
35620exports.encrypt = encrypt;
35621exports.decrypt = decrypt;
35622exports.sign = sign;
35623exports.verify = verify;
35624exports.encryptSessionKey = encryptSessionKey;
35625exports.decryptSessionKeys = decryptSessionKeys;
35626
35627var _webStreamTools = require('web-stream-tools');
35628
35629var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
35630
35631var _message = require('./message');
35632
35633var messageLib = _interopRequireWildcard(_message);
35634
35635var _cleartext = require('./cleartext');
35636
35637var _key = require('./key');
35638
35639var _config = require('./config/config');
35640
35641var _config2 = _interopRequireDefault(_config);
35642
35643var _enums = require('./enums');
35644
35645var _enums2 = _interopRequireDefault(_enums);
35646
35647require('./polyfills');
35648
35649var _util = require('./util');
35650
35651var _util2 = _interopRequireDefault(_util);
35652
35653var _async_proxy = require('./worker/async_proxy');
35654
35655var _async_proxy2 = _interopRequireDefault(_async_proxy);
35656
35657function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
35658
35659function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
35660
35661//////////////////////////
35662//                      //
35663//   Web Worker setup   //
35664//                      //
35665//////////////////////////
35666
35667
35668let asyncProxy; // instance of the asyncproxy
35669
35670/**
35671 * Set the path for the web worker script and create an instance of the async proxy
35672 * @param {String} path            relative path to the worker scripts, default: 'openpgp.worker.js'
35673 * @param {Number} n               number of workers to initialize
35674 * @param {Array<Object>} workers  alternative to path parameter: web workers initialized with 'openpgp.worker.js'
35675 * @returns {Promise<Boolean>}     returns a promise that resolves to true if all workers have succesfully finished loading
35676 * @async
35677 */
35678// OpenPGP.js - An OpenPGP implementation in javascript
35679// Copyright (C) 2016 Tankred Hase
35680//
35681// This library is free software; you can redistribute it and/or
35682// modify it under the terms of the GNU Lesser General Public
35683// License as published by the Free Software Foundation; either
35684// version 3.0 of the License, or (at your option) any later version.
35685//
35686// This library is distributed in the hope that it will be useful,
35687// but WITHOUT ANY WARRANTY; without even the implied warranty of
35688// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
35689// Lesser General Public License for more details.
35690//
35691// You should have received a copy of the GNU Lesser General Public
35692// License along with this library; if not, write to the Free Software
35693// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
35694
35695/**
35696 * @fileoverview The openpgp base module should provide all of the functionality
35697 * to consume the openpgp.js library. All additional classes are documented
35698 * for extending and developing on top of the base library.
35699 * @requires web-stream-tools
35700 * @requires message
35701 * @requires cleartext
35702 * @requires key
35703 * @requires config
35704 * @requires enums
35705 * @requires util
35706 * @requires polyfills
35707 * @requires worker/async_proxy
35708 * @module openpgp
35709 */
35710
35711// This file intentionally has two separate file overviews so that
35712// a reference to this module appears at the end of doc/index.html.
35713
35714/**
35715 * @fileoverview To view the full API documentation, start from
35716 * {@link module:openpgp}
35717 */
35718
35719async function initWorker({ path = 'openpgp.worker.js', n = 1, workers = [] } = {}) {
35720  if (workers.length || typeof window !== 'undefined' && window.Worker && window.MessageChannel) {
35721    const proxy = new _async_proxy2.default({ path, n, workers, config: _config2.default });
35722    const loaded = await proxy.loaded();
35723    if (loaded) {
35724      asyncProxy = proxy;
35725      return true;
35726    }
35727  }
35728  return false;
35729}
35730
35731/**
35732 * Returns a reference to the async proxy if the worker was initialized with openpgp.initWorker()
35733 * @returns {module:worker/async_proxy.AsyncProxy|null} the async proxy or null if not initialized
35734 */
35735function getWorker() {
35736  return asyncProxy;
35737}
35738
35739/**
35740 * Cleanup the current instance of the web worker.
35741 */
35742function destroyWorker() {
35743  asyncProxy = undefined;
35744}
35745
35746//////////////////////
35747//                  //
35748//   Key handling   //
35749//                  //
35750//////////////////////
35751
35752
35753/**
35754 * Generates a new OpenPGP key pair. Supports RSA and ECC keys. Primary and subkey will be of same type.
35755 * @param  {Array<Object>} userIds   array of user IDs e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }]
35756 * @param  {String} passphrase       (optional) The passphrase used to encrypt the resulting private key
35757 * @param  {Number} numBits          (optional) number of bits for RSA keys: 2048 or 4096.
35758 * @param  {Number} keyExpirationTime (optional) The number of seconds after the key creation time that the key expires
35759 * @param  {String} curve            (optional) elliptic curve for ECC keys:
35760 *                                              curve25519, p256, p384, p521, secp256k1,
35761 *                                              brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1.
35762 * @param  {Date} date               (optional) override the creation date of the key and the key signatures
35763 * @param  {Array<Object>} subkeys   (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
35764 *                                              sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt
35765 * @returns {Promise<Object>}         The generated key object in the form:
35766 *                                     { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String }
35767 * @async
35768 * @static
35769 */
35770
35771function generateKey({ userIds = [], passphrase = "", numBits = 2048, keyExpirationTime = 0, curve = "", date = new Date(), subkeys = [{}] }) {
35772  userIds = toArray(userIds);
35773  const options = { userIds, passphrase, numBits, keyExpirationTime, curve, date, subkeys };
35774  if (_util2.default.getWebCryptoAll() && numBits < 2048) {
35775    throw new Error('numBits should be 2048 or 4096, found: ' + numBits);
35776  }
35777
35778  if (!_util2.default.getWebCryptoAll() && asyncProxy) {
35779    // use web worker if web crypto apis are not supported
35780    return asyncProxy.delegate('generateKey', options);
35781  }
35782
35783  return (0, _key.generate)(options).then(async key => {
35784    const revocationCertificate = await key.getRevocationCertificate();
35785    key.revocationSignatures = [];
35786
35787    return convertStreams({
35788
35789      key: key,
35790      privateKeyArmored: key.armor(),
35791      publicKeyArmored: key.toPublic().armor(),
35792      revocationCertificate: revocationCertificate
35793
35794    });
35795  }).catch(onError.bind(null, 'Error generating keypair'));
35796}
35797
35798/**
35799 * Reformats signature packets for a key and rewraps key object.
35800 * @param  {Key} privateKey          private key to reformat
35801 * @param  {Array<Object>} userIds   array of user IDs e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }]
35802 * @param  {String} passphrase       (optional) The passphrase used to encrypt the resulting private key
35803 * @param  {Number} keyExpirationTime (optional) The number of seconds after the key creation time that the key expires
35804 * @param  {Boolean} revocationCertificate (optional) Whether the returned object should include a revocation certificate to revoke the public key
35805 * @returns {Promise<Object>}         The generated key object in the form:
35806 *                                     { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String }
35807 * @async
35808 * @static
35809 */
35810function reformatKey({ privateKey, userIds = [], passphrase = "", keyExpirationTime = 0, date, revocationCertificate = true }) {
35811  userIds = toArray(userIds);
35812  const options = { privateKey, userIds, passphrase, keyExpirationTime, date, revocationCertificate };
35813  if (asyncProxy) {
35814    return asyncProxy.delegate('reformatKey', options);
35815  }
35816
35817  options.revoked = options.revocationCertificate;
35818
35819  return (0, _key.reformat)(options).then(async key => {
35820    const revocationCertificate = await key.getRevocationCertificate();
35821    key.revocationSignatures = [];
35822
35823    return convertStreams({
35824
35825      key: key,
35826      privateKeyArmored: key.armor(),
35827      publicKeyArmored: key.toPublic().armor(),
35828      revocationCertificate: revocationCertificate
35829
35830    });
35831  }).catch(onError.bind(null, 'Error reformatting keypair'));
35832}
35833
35834/**
35835 * Revokes a key. Requires either a private key or a revocation certificate.
35836 *   If a revocation certificate is passed, the reasonForRevocation parameters will be ignored.
35837 * @param  {Key} key                 (optional) public or private key to revoke
35838 * @param  {String} revocationCertificate (optional) revocation certificate to revoke the key with
35839 * @param  {Object} reasonForRevocation (optional) object indicating the reason for revocation
35840 * @param  {module:enums.reasonForRevocation} reasonForRevocation.flag (optional) flag indicating the reason for revocation
35841 * @param  {String} reasonForRevocation.string (optional) string explaining the reason for revocation
35842 * @returns {Promise<Object>}         The revoked key object in the form:
35843 *                                     { privateKey:Key, privateKeyArmored:String, publicKey:Key, publicKeyArmored:String }
35844 *                                     (if private key is passed) or { publicKey:Key, publicKeyArmored:String } (otherwise)
35845 * @static
35846 */
35847function revokeKey({
35848  key, revocationCertificate, reasonForRevocation
35849} = {}) {
35850  const options = {
35851    key, revocationCertificate, reasonForRevocation
35852  };
35853
35854  if (!_util2.default.getWebCryptoAll() && asyncProxy) {
35855    // use web worker if web crypto apis are not supported
35856    return asyncProxy.delegate('revokeKey', options);
35857  }
35858
35859  return Promise.resolve().then(() => {
35860    if (revocationCertificate) {
35861      return key.applyRevocationCertificate(revocationCertificate);
35862    } else {
35863      return key.revoke(reasonForRevocation);
35864    }
35865  }).then(async key => {
35866    await convertStreams(key);
35867    if (key.isPrivate()) {
35868      const publicKey = key.toPublic();
35869      return {
35870        privateKey: key,
35871        privateKeyArmored: key.armor(),
35872        publicKey: publicKey,
35873        publicKeyArmored: publicKey.armor()
35874      };
35875    }
35876    return {
35877      publicKey: key,
35878      publicKeyArmored: key.armor()
35879    };
35880  }).catch(onError.bind(null, 'Error revoking key'));
35881}
35882
35883/**
35884 * Unlock a private key with your passphrase.
35885 * @param  {Key} privateKey                    the private key that is to be decrypted
35886 * @param  {String|Array<String>} passphrase   the user's passphrase(s) chosen during key generation
35887 * @returns {Promise<Object>}                  the unlocked key object in the form: { key:Key }
35888 * @async
35889 */
35890function decryptKey({ privateKey, passphrase }) {
35891  if (asyncProxy) {
35892    // use web worker if available
35893    return asyncProxy.delegate('decryptKey', { privateKey, passphrase });
35894  }
35895
35896  return Promise.resolve().then(async function () {
35897    await privateKey.decrypt(passphrase);
35898
35899    return {
35900      key: privateKey
35901    };
35902  }).catch(onError.bind(null, 'Error decrypting private key'));
35903}
35904
35905/**
35906 * Lock a private key with your passphrase.
35907 * @param  {Key} privateKey                      the private key that is to be decrypted
35908 * @param  {String|Array<String>} passphrase     the user's passphrase(s) chosen during key generation
35909 * @returns {Promise<Object>}                    the locked key object in the form: { key:Key }
35910 * @async
35911 */
35912function encryptKey({ privateKey, passphrase }) {
35913  if (asyncProxy) {
35914    // use web worker if available
35915    return asyncProxy.delegate('encryptKey', { privateKey, passphrase });
35916  }
35917
35918  return Promise.resolve().then(async function () {
35919    await privateKey.encrypt(passphrase);
35920
35921    return {
35922      key: privateKey
35923    };
35924  }).catch(onError.bind(null, 'Error decrypting private key'));
35925}
35926
35927///////////////////////////////////////////
35928//                                       //
35929//   Message encryption and decryption   //
35930//                                       //
35931///////////////////////////////////////////
35932
35933
35934/**
35935 * Encrypts message text/data with public keys, passwords or both at once. At least either public keys or passwords
35936 *   must be specified. If private keys are specified, those will be used to sign the message.
35937 * @param  {Message} message                      message to be encrypted as created by openpgp.message.fromText or openpgp.message.fromBinary
35938 * @param  {Key|Array<Key>} publicKeys            (optional) array of keys or single key, used to encrypt the message
35939 * @param  {Key|Array<Key>} privateKeys           (optional) private keys for signing. If omitted message will not be signed
35940 * @param  {String|Array<String>} passwords       (optional) array of passwords or a single password to encrypt the message
35941 * @param  {Object} sessionKey                    (optional) session key in the form: { data:Uint8Array, algorithm:String }
35942 * @param  {module:enums.compression} compression (optional) which compression algorithm to compress the message with, defaults to what is specified in config
35943 * @param  {Boolean} armor                        (optional) if the return values should be ascii armored or the message/signature objects
35944 * @param  {'web'|'node'|false} streaming         (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
35945 * @param  {Boolean} detached                     (optional) if the signature should be detached (if true, signature will be added to returned object)
35946 * @param  {Signature} signature                  (optional) a detached signature to add to the encrypted message
35947 * @param  {Boolean} returnSessionKey             (optional) if the unencrypted session key should be added to returned object
35948 * @param  {Boolean} wildcard                     (optional) use a key ID of 0 instead of the public key IDs
35949 * @param  {Date} date                            (optional) override the creation date of the message signature
35950 * @param  {Array} fromUserIds                    (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
35951 * @param  {Array} toUserIds                      (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
35952 * @returns {Promise<Object>}                     Object containing encrypted (and optionally signed) message in the form:
35953 *
35954 *     {
35955 *       data: String|ReadableStream<String>|NodeStream, (if `armor` was true, the default)
35956 *       message: Message, (if `armor` was false)
35957 *       signature: String|ReadableStream<String>|NodeStream, (if `detached` was true and `armor` was true)
35958 *       signature: Signature (if `detached` was true and `armor` was false)
35959 *       sessionKey: { data, algorithm, aeadAlgorithm } (if `returnSessionKey` was true)
35960 *     }
35961 * @async
35962 * @static
35963 */
35964function encrypt({ message, publicKeys, privateKeys, passwords, sessionKey, compression = _config2.default.compression, armor = true, streaming = message && message.fromStream, detached = false, signature = null, returnSessionKey = false, wildcard = false, date = new Date(), fromUserIds = [], toUserIds = [] }) {
35965  checkMessage(message);publicKeys = toArray(publicKeys);privateKeys = toArray(privateKeys);passwords = toArray(passwords);fromUserIds = toArray(fromUserIds);toUserIds = toArray(toUserIds);
35966
35967  if (!nativeAEAD() && asyncProxy) {
35968    // use web worker if web crypto apis are not supported
35969    return asyncProxy.delegate('encrypt', { message, publicKeys, privateKeys, passwords, sessionKey, compression, armor, streaming, detached, signature, returnSessionKey, wildcard, date, fromUserIds, toUserIds });
35970  }
35971  const result = {};
35972  return Promise.resolve().then(async function () {
35973    if (!privateKeys) {
35974      privateKeys = [];
35975    }
35976    if (privateKeys.length || signature) {
35977      // sign the message only if private keys or signature is specified
35978      if (detached) {
35979        const detachedSignature = await message.signDetached(privateKeys, signature, date, fromUserIds);
35980        result.signature = armor ? detachedSignature.armor() : detachedSignature;
35981      } else {
35982        message = await message.sign(privateKeys, signature, date, fromUserIds);
35983      }
35984    }
35985    message = message.compress(compression);
35986    return message.encrypt(publicKeys, passwords, sessionKey, wildcard, date, toUserIds, streaming);
35987  }).then(async encrypted => {
35988    if (armor) {
35989      result.data = encrypted.message.armor();
35990    } else {
35991      result.message = encrypted.message;
35992    }
35993    if (returnSessionKey) {
35994      result.sessionKey = encrypted.sessionKey;
35995    }
35996    return convertStreams(result, streaming, armor ? ['signature', 'data'] : []);
35997  }).catch(onError.bind(null, 'Error encrypting message'));
35998}
35999
36000/**
36001 * Decrypts a message with the user's private key, a session key or a password. Either a private key,
36002 *   a session key or a password must be specified.
36003 * @param  {Message} message                  the message object with the encrypted data
36004 * @param  {Key|Array<Key>} privateKeys       (optional) private keys with decrypted secret key data or session key
36005 * @param  {String|Array<String>} passwords   (optional) passwords to decrypt the message
36006 * @param  {Object|Array<Object>} sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String }
36007 * @param  {Key|Array<Key>} publicKeys        (optional) array of public keys or single key, to verify signatures
36008 * @param  {'utf8'|'binary'} format           (optional) whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.
36009 * @param  {'web'|'node'|false} streaming     (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
36010 * @param  {Signature} signature              (optional) detached signature for verification
36011 * @param  {Date} date                        (optional) use the given date for verification instead of the current time
36012 * @returns {Promise<Object>}                 Object containing decrypted and verified message in the form:
36013 *
36014 *     {
36015 *       data: String|ReadableStream<String>|NodeStream, (if format was 'utf8', the default)
36016 *       data: Uint8Array|ReadableStream<Uint8Array>|NodeStream, (if format was 'binary')
36017 *       filename: String,
36018 *       signatures: [
36019 *         {
36020 *           keyid: module:type/keyid,
36021 *           verified: Promise<Boolean>,
36022 *           valid: Boolean (if streaming was false)
36023 *         }, ...
36024 *       ]
36025 *     }
36026 * @async
36027 * @static
36028 */
36029function decrypt({ message, privateKeys, passwords, sessionKeys, publicKeys, format = 'utf8', streaming = message && message.fromStream, signature = null, date = new Date() }) {
36030  checkMessage(message);publicKeys = toArray(publicKeys);privateKeys = toArray(privateKeys);passwords = toArray(passwords);sessionKeys = toArray(sessionKeys);
36031
36032  if (!nativeAEAD() && asyncProxy) {
36033    // use web worker if web crypto apis are not supported
36034    return asyncProxy.delegate('decrypt', { message, privateKeys, passwords, sessionKeys, publicKeys, format, streaming, signature, date });
36035  }
36036
36037  return message.decrypt(privateKeys, passwords, sessionKeys, streaming).then(async function (decrypted) {
36038    if (!publicKeys) {
36039      publicKeys = [];
36040    }
36041
36042    const result = {};
36043    result.signatures = signature ? await decrypted.verifyDetached(signature, publicKeys, date, streaming) : await decrypted.verify(publicKeys, date, streaming);
36044    result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();
36045    result.filename = decrypted.getFilename();
36046    if (streaming) linkStreams(result, message, decrypted.packets.stream);
36047    result.data = await convertStream(result.data, streaming);
36048    if (!streaming) await prepareSignatures(result.signatures);
36049    return result;
36050  }).catch(onError.bind(null, 'Error decrypting message'));
36051}
36052
36053//////////////////////////////////////////
36054//                                      //
36055//   Message signing and verification   //
36056//                                      //
36057//////////////////////////////////////////
36058
36059
36060/**
36061 * Signs a cleartext message.
36062 * @param  {CleartextMessage|Message} message (cleartext) message to be signed
36063 * @param  {Key|Array<Key>} privateKeys       array of keys or single key with decrypted secret key data to sign cleartext
36064 * @param  {Boolean} armor                    (optional) if the return value should be ascii armored or the message object
36065 * @param  {'web'|'node'|false} streaming     (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
36066 * @param  {Boolean} detached                 (optional) if the return value should contain a detached signature
36067 * @param  {Date} date                        (optional) override the creation date of the signature
36068 * @param  {Array} fromUserIds                (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
36069 * @returns {Promise<Object>}                 Object containing signed message in the form:
36070 *
36071 *     {
36072 *       data: String|ReadableStream<String>|NodeStream, (if `armor` was true, the default)
36073 *       message: Message (if `armor` was false)
36074 *     }
36075 *
36076 * Or, if `detached` was true:
36077 *
36078 *     {
36079 *       signature: String|ReadableStream<String>|NodeStream, (if `armor` was true, the default)
36080 *       signature: Signature (if `armor` was false)
36081 *     }
36082 * @async
36083 * @static
36084 */
36085function sign({ message, privateKeys, armor = true, streaming = message && message.fromStream, detached = false, date = new Date(), fromUserIds = [] }) {
36086  checkCleartextOrMessage(message);
36087  privateKeys = toArray(privateKeys);fromUserIds = toArray(fromUserIds);
36088
36089  if (asyncProxy) {
36090    // use web worker if available
36091    return asyncProxy.delegate('sign', {
36092      message, privateKeys, armor, streaming, detached, date, fromUserIds
36093    });
36094  }
36095
36096  const result = {};
36097  return Promise.resolve().then(async function () {
36098    if (detached) {
36099      const signature = await message.signDetached(privateKeys, undefined, date, fromUserIds);
36100      result.signature = armor ? signature.armor() : signature;
36101      if (message.packets) {
36102        result.signature = _webStreamTools2.default.transformPair(message.packets.write(), async (readable, writable) => {
36103          await Promise.all([_webStreamTools2.default.pipe(result.signature, writable), _webStreamTools2.default.readToEnd(readable).catch(() => {})]);
36104        });
36105      }
36106    } else {
36107      message = await message.sign(privateKeys, undefined, date, fromUserIds);
36108      if (armor) {
36109        result.data = message.armor();
36110      } else {
36111        result.message = message;
36112      }
36113    }
36114    return convertStreams(result, streaming, armor ? ['signature', 'data'] : []);
36115  }).catch(onError.bind(null, 'Error signing cleartext message'));
36116}
36117
36118/**
36119 * Verifies signatures of cleartext signed message
36120 * @param  {Key|Array<Key>} publicKeys         array of publicKeys or single key, to verify signatures
36121 * @param  {CleartextMessage|Message} message  (cleartext) message object with signatures
36122 * @param  {'web'|'node'|false} streaming      (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
36123 * @param  {Signature} signature               (optional) detached signature for verification
36124 * @param  {Date} date                         (optional) use the given date for verification instead of the current time
36125 * @returns {Promise<Object>}                  Object containing verified message in the form:
36126 *
36127 *     {
36128 *       data: String|ReadableStream<String>|NodeStream, (if `message` was a CleartextMessage)
36129 *       data: Uint8Array|ReadableStream<Uint8Array>|NodeStream, (if `message` was a Message)
36130 *       signatures: [
36131 *         {
36132 *           keyid: module:type/keyid,
36133 *           verified: Promise<Boolean>,
36134 *           valid: Boolean (if `streaming` was false)
36135 *         }, ...
36136 *       ]
36137 *     }
36138 * @async
36139 * @static
36140 */
36141function verify({ message, publicKeys, streaming = message && message.fromStream, signature = null, date = new Date() }) {
36142  checkCleartextOrMessage(message);
36143  publicKeys = toArray(publicKeys);
36144
36145  if (asyncProxy) {
36146    // use web worker if available
36147    return asyncProxy.delegate('verify', { message, publicKeys, streaming, signature, date });
36148  }
36149
36150  return Promise.resolve().then(async function () {
36151    const result = {};
36152    result.signatures = signature ? await message.verifyDetached(signature, publicKeys, date, streaming) : await message.verify(publicKeys, date, streaming);
36153    result.data = message instanceof _cleartext.CleartextMessage ? message.getText() : message.getLiteralData();
36154    if (streaming) linkStreams(result, message);
36155    result.data = await convertStream(result.data, streaming);
36156    if (!streaming) await prepareSignatures(result.signatures);
36157    return result;
36158  }).catch(onError.bind(null, 'Error verifying cleartext signed message'));
36159}
36160
36161///////////////////////////////////////////////
36162//                                           //
36163//   Session key encryption and decryption   //
36164//                                           //
36165///////////////////////////////////////////////
36166
36167
36168/**
36169 * Encrypt a symmetric session key with public keys, passwords, or both at once. At least either public keys
36170 *   or passwords must be specified.
36171 * @param  {Uint8Array} data                  the session key to be encrypted e.g. 16 random bytes (for aes128)
36172 * @param  {String} algorithm                 algorithm of the symmetric session key e.g. 'aes128' or 'aes256'
36173 * @param  {String} aeadAlgorithm             (optional) aead algorithm, e.g. 'eax' or 'ocb'
36174 * @param  {Key|Array<Key>} publicKeys        (optional) array of public keys or single key, used to encrypt the key
36175 * @param  {String|Array<String>} passwords   (optional) passwords for the message
36176 * @param  {Boolean} wildcard                 (optional) use a key ID of 0 instead of the public key IDs
36177 * @param  {Date} date                        (optional) override the date
36178 * @param  {Array} toUserIds                  (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }]
36179 * @returns {Promise<Message>}                 the encrypted session key packets contained in a message object
36180 * @async
36181 * @static
36182 */
36183function encryptSessionKey({ data, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard = false, date = new Date(), toUserIds = [] }) {
36184  checkBinary(data);checkString(algorithm, 'algorithm');publicKeys = toArray(publicKeys);passwords = toArray(passwords);toUserIds = toArray(toUserIds);
36185
36186  if (asyncProxy) {
36187    // use web worker if available
36188    return asyncProxy.delegate('encryptSessionKey', { data, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard, date, toUserIds });
36189  }
36190
36191  return Promise.resolve().then(async function () {
36192
36193    return { message: await messageLib.encryptSessionKey(data, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard, date, toUserIds) };
36194  }).catch(onError.bind(null, 'Error encrypting session key'));
36195}
36196
36197/**
36198 * Decrypt symmetric session keys with a private key or password. Either a private key or
36199 *   a password must be specified.
36200 * @param  {Message} message                 a message object containing the encrypted session key packets
36201 * @param  {Key|Array<Key>} privateKeys     (optional) private keys with decrypted secret key data
36202 * @param  {String|Array<String>} passwords (optional) passwords to decrypt the session key
36203 * @returns {Promise<Object|undefined>}    Array of decrypted session key, algorithm pairs in form:
36204 *                                          { data:Uint8Array, algorithm:String }
36205 *                                          or 'undefined' if no key packets found
36206 * @async
36207 * @static
36208 */
36209function decryptSessionKeys({ message, privateKeys, passwords }) {
36210  checkMessage(message);privateKeys = toArray(privateKeys);passwords = toArray(passwords);
36211
36212  if (asyncProxy) {
36213    // use web worker if available
36214    return asyncProxy.delegate('decryptSessionKeys', { message, privateKeys, passwords });
36215  }
36216
36217  return Promise.resolve().then(async function () {
36218
36219    return message.decryptSessionKeys(privateKeys, passwords);
36220  }).catch(onError.bind(null, 'Error decrypting session keys'));
36221}
36222
36223//////////////////////////
36224//                      //
36225//   Helper functions   //
36226//                      //
36227//////////////////////////
36228
36229
36230/**
36231 * Input validation
36232 */
36233function checkString(data, name) {
36234  if (!_util2.default.isString(data)) {
36235    throw new Error('Parameter [' + (name || 'data') + '] must be of type String');
36236  }
36237}
36238function checkBinary(data, name) {
36239  if (!_util2.default.isUint8Array(data)) {
36240    throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');
36241  }
36242}
36243function checkMessage(message) {
36244  if (!(message instanceof messageLib.Message)) {
36245    throw new Error('Parameter [message] needs to be of type Message');
36246  }
36247}
36248function checkCleartextOrMessage(message) {
36249  if (!(message instanceof _cleartext.CleartextMessage) && !(message instanceof messageLib.Message)) {
36250    throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');
36251  }
36252}
36253
36254/**
36255 * Normalize parameter to an array if it is not undefined.
36256 * @param  {Object} param              the parameter to be normalized
36257 * @returns {Array<Object>|undefined}   the resulting array or undefined
36258 */
36259function toArray(param) {
36260  if (param && !_util2.default.isArray(param)) {
36261    param = [param];
36262  }
36263  return param;
36264}
36265
36266/**
36267 * Convert data to or from Stream
36268 * @param  {Object} data                   the data to convert
36269 * @param  {'web'|'node'|false} streaming  (optional) whether to return a ReadableStream
36270 * @returns {Object}                       the data in the respective format
36271 */
36272async function convertStream(data, streaming) {
36273  if (!streaming && _util2.default.isStream(data)) {
36274    return _webStreamTools2.default.readToEnd(data);
36275  }
36276  if (streaming && !_util2.default.isStream(data)) {
36277    data = new ReadableStream({
36278      start(controller) {
36279        controller.enqueue(data);
36280        controller.close();
36281      }
36282    });
36283  }
36284  if (streaming === 'node') {
36285    data = _webStreamTools2.default.webToNode(data);
36286  }
36287  return data;
36288}
36289
36290/**
36291 * Convert object properties from Stream
36292 * @param  {Object} obj                    the data to convert
36293 * @param  {'web'|'node'|false} streaming  (optional) whether to return ReadableStreams
36294 * @param  {Array<String>} keys            (optional) which keys to return as streams, if possible
36295 * @returns {Object}                       the data in the respective format
36296 */
36297async function convertStreams(obj, streaming, keys = []) {
36298  if (Object.prototype.isPrototypeOf(obj) && !Uint8Array.prototype.isPrototypeOf(obj)) {
36299    await Promise.all(Object.entries(obj).map(async ([key, value]) => {
36300      // recursively search all children
36301      if (_util2.default.isStream(value) || keys.includes(key)) {
36302        obj[key] = await convertStream(value, streaming);
36303      } else {
36304        await convertStreams(obj[key], streaming);
36305      }
36306    }));
36307  }
36308  return obj;
36309}
36310
36311/**
36312 * Link result.data to the message stream for cancellation.
36313 * Also, forward errors in the message to result.data.
36314 * @param  {Object} result                  the data to convert
36315 * @param  {Message} message                message object
36316 * @param  {ReadableStream} erroringStream  (optional) stream which either errors or gets closed without data
36317 * @returns {Object}
36318 */
36319function linkStreams(result, message, erroringStream) {
36320  result.data = _webStreamTools2.default.transformPair(message.packets.stream, async (readable, writable) => {
36321    await _webStreamTools2.default.pipe(result.data, writable, {
36322      preventClose: true
36323    });
36324    const writer = _webStreamTools2.default.getWriter(writable);
36325    try {
36326      // Forward errors in erroringStream (defaulting to the message stream) to result.data.
36327      await _webStreamTools2.default.readToEnd(erroringStream || readable, arr => arr);
36328      await writer.close();
36329    } catch (e) {
36330      await writer.abort(e);
36331    }
36332  });
36333}
36334
36335/**
36336 * Wait until signature objects have been verified
36337 * @param  {Object} signatures              list of signatures
36338 */
36339async function prepareSignatures(signatures) {
36340  await Promise.all(signatures.map(async signature => {
36341    signature.signature = await signature.signature;
36342    try {
36343      signature.valid = await signature.verified;
36344    } catch (e) {
36345      signature.valid = null;
36346      signature.error = e;
36347      _util2.default.print_debug_error(e);
36348    }
36349  }));
36350}
36351
36352/**
36353 * Global error handler that logs the stack trace and rethrows a high lvl error message.
36354 * @param {String} message   A human readable high level error Message
36355 * @param {Error} error      The internal error that caused the failure
36356 */
36357function onError(message, error) {
36358  // log the stack trace
36359  _util2.default.print_debug_error(error);
36360
36361  // update error message
36362  try {
36363    error.message = message + ': ' + error.message;
36364  } catch (e) {}
36365
36366  throw error;
36367}
36368
36369/**
36370 * Check for native AEAD support and configuration by the user. Only
36371 * browsers that implement the current WebCrypto specification support
36372 * native GCM. Native EAX is built on CTR and CBC, which current
36373 * browsers support. OCB and CFB are not natively supported.
36374 * @returns {Boolean}   If authenticated encryption should be used
36375 */
36376function nativeAEAD() {
36377  return _config2.default.aead_protect && ((_config2.default.aead_protect_version !== 4 || _config2.default.aead_mode === _enums2.default.aead.experimental_gcm) && _util2.default.getWebCrypto() || _config2.default.aead_protect_version === 4 && _config2.default.aead_mode === _enums2.default.aead.eax && _util2.default.getWebCrypto());
36378}
36379
36380},{"./cleartext":78,"./config/config":79,"./enums":114,"./key":117,"./message":121,"./polyfills":145,"./util":153,"./worker/async_proxy":155,"web-stream-tools":76}],123:[function(require,module,exports){
36381'use strict';
36382
36383Object.defineProperty(exports, "__esModule", {
36384  value: true
36385});
36386exports.Trust = exports.Signature = exports.SecretSubkey = exports.Userid = exports.SecretKey = exports.OnePassSignature = exports.UserAttribute = exports.PublicSubkey = exports.Marker = exports.SymmetricallyEncrypted = exports.PublicKey = exports.Literal = exports.SymEncryptedSessionKey = exports.PublicKeyEncryptedSessionKey = exports.SymEncryptedAEADProtected = exports.SymEncryptedIntegrityProtected = exports.Compressed = undefined;
36387
36388var _compressed = require('./compressed.js');
36389
36390Object.defineProperty(exports, 'Compressed', {
36391  enumerable: true,
36392  get: function get() {
36393    return _interopRequireDefault(_compressed).default;
36394  }
36395});
36396
36397var _sym_encrypted_integrity_protected = require('./sym_encrypted_integrity_protected.js');
36398
36399Object.defineProperty(exports, 'SymEncryptedIntegrityProtected', {
36400  enumerable: true,
36401  get: function get() {
36402    return _interopRequireDefault(_sym_encrypted_integrity_protected).default;
36403  }
36404});
36405
36406var _sym_encrypted_aead_protected = require('./sym_encrypted_aead_protected.js');
36407
36408Object.defineProperty(exports, 'SymEncryptedAEADProtected', {
36409  enumerable: true,
36410  get: function get() {
36411    return _interopRequireDefault(_sym_encrypted_aead_protected).default;
36412  }
36413});
36414
36415var _public_key_encrypted_session_key = require('./public_key_encrypted_session_key.js');
36416
36417Object.defineProperty(exports, 'PublicKeyEncryptedSessionKey', {
36418  enumerable: true,
36419  get: function get() {
36420    return _interopRequireDefault(_public_key_encrypted_session_key).default;
36421  }
36422});
36423
36424var _sym_encrypted_session_key = require('./sym_encrypted_session_key.js');
36425
36426Object.defineProperty(exports, 'SymEncryptedSessionKey', {
36427  enumerable: true,
36428  get: function get() {
36429    return _interopRequireDefault(_sym_encrypted_session_key).default;
36430  }
36431});
36432
36433var _literal = require('./literal.js');
36434
36435Object.defineProperty(exports, 'Literal', {
36436  enumerable: true,
36437  get: function get() {
36438    return _interopRequireDefault(_literal).default;
36439  }
36440});
36441
36442var _public_key = require('./public_key.js');
36443
36444Object.defineProperty(exports, 'PublicKey', {
36445  enumerable: true,
36446  get: function get() {
36447    return _interopRequireDefault(_public_key).default;
36448  }
36449});
36450
36451var _symmetrically_encrypted = require('./symmetrically_encrypted.js');
36452
36453Object.defineProperty(exports, 'SymmetricallyEncrypted', {
36454  enumerable: true,
36455  get: function get() {
36456    return _interopRequireDefault(_symmetrically_encrypted).default;
36457  }
36458});
36459
36460var _marker = require('./marker.js');
36461
36462Object.defineProperty(exports, 'Marker', {
36463  enumerable: true,
36464  get: function get() {
36465    return _interopRequireDefault(_marker).default;
36466  }
36467});
36468
36469var _public_subkey = require('./public_subkey.js');
36470
36471Object.defineProperty(exports, 'PublicSubkey', {
36472  enumerable: true,
36473  get: function get() {
36474    return _interopRequireDefault(_public_subkey).default;
36475  }
36476});
36477
36478var _user_attribute = require('./user_attribute.js');
36479
36480Object.defineProperty(exports, 'UserAttribute', {
36481  enumerable: true,
36482  get: function get() {
36483    return _interopRequireDefault(_user_attribute).default;
36484  }
36485});
36486
36487var _one_pass_signature = require('./one_pass_signature.js');
36488
36489Object.defineProperty(exports, 'OnePassSignature', {
36490  enumerable: true,
36491  get: function get() {
36492    return _interopRequireDefault(_one_pass_signature).default;
36493  }
36494});
36495
36496var _secret_key = require('./secret_key.js');
36497
36498Object.defineProperty(exports, 'SecretKey', {
36499  enumerable: true,
36500  get: function get() {
36501    return _interopRequireDefault(_secret_key).default;
36502  }
36503});
36504
36505var _userid = require('./userid.js');
36506
36507Object.defineProperty(exports, 'Userid', {
36508  enumerable: true,
36509  get: function get() {
36510    return _interopRequireDefault(_userid).default;
36511  }
36512});
36513
36514var _secret_subkey = require('./secret_subkey.js');
36515
36516Object.defineProperty(exports, 'SecretSubkey', {
36517  enumerable: true,
36518  get: function get() {
36519    return _interopRequireDefault(_secret_subkey).default;
36520  }
36521});
36522
36523var _signature = require('./signature.js');
36524
36525Object.defineProperty(exports, 'Signature', {
36526  enumerable: true,
36527  get: function get() {
36528    return _interopRequireDefault(_signature).default;
36529  }
36530});
36531
36532var _trust = require('./trust.js');
36533
36534Object.defineProperty(exports, 'Trust', {
36535  enumerable: true,
36536  get: function get() {
36537    return _interopRequireDefault(_trust).default;
36538  }
36539});
36540exports.newPacketFromTag = newPacketFromTag;
36541exports.fromStructuredClone = fromStructuredClone;
36542
36543var _enums = require('../enums.js');
36544
36545var _enums2 = _interopRequireDefault(_enums);
36546
36547var _all_packets = require('./all_packets.js');
36548
36549var packets = _interopRequireWildcard(_all_packets);
36550
36551function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
36552
36553function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
36554
36555/**
36556 * Allocate a new packet
36557 * @function newPacketFromTag
36558 * @memberof module:packet
36559 * @param {String} tag property name from {@link module:enums.packet}
36560 * @returns {Object} new packet object with type based on tag
36561 */
36562function newPacketFromTag(tag) {
36563  return new packets[packetClassFromTagName(tag)]();
36564}
36565
36566/**
36567 * Allocate a new packet from structured packet clone
36568 * @see {@link https://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data}
36569 * @function fromStructuredClone
36570 * @memberof module:packet
36571 * @param {Object} packetClone packet clone
36572 * @returns {Object} new packet object with data from packet clone
36573 */
36574function fromStructuredClone(packetClone) {
36575  const tagName = _enums2.default.read(_enums2.default.packet, packetClone.tag);
36576  const packet = newPacketFromTag(tagName);
36577  Object.assign(packet, packetClone);
36578  if (packet.postCloneTypeFix) {
36579    packet.postCloneTypeFix();
36580  }
36581  return packet;
36582}
36583
36584/**
36585 * Convert tag name to class name
36586 * @param {String} tag property name from {@link module:enums.packet}
36587 * @returns {String}
36588 * @private
36589 */
36590function packetClassFromTagName(tag) {
36591  return tag.substr(0, 1).toUpperCase() + tag.substr(1);
36592}
36593
36594},{"../enums.js":114,"./all_packets.js":123,"./compressed.js":125,"./literal.js":127,"./marker.js":128,"./one_pass_signature.js":129,"./public_key.js":132,"./public_key_encrypted_session_key.js":133,"./public_subkey.js":134,"./secret_key.js":135,"./secret_subkey.js":136,"./signature.js":137,"./sym_encrypted_aead_protected.js":138,"./sym_encrypted_integrity_protected.js":139,"./sym_encrypted_session_key.js":140,"./symmetrically_encrypted.js":141,"./trust.js":142,"./user_attribute.js":143,"./userid.js":144}],124:[function(require,module,exports){
36595'use strict';
36596
36597Object.defineProperty(exports, "__esModule", {
36598  value: true
36599});
36600exports.clonePackets = clonePackets;
36601exports.parseClonedPackets = parseClonedPackets;
36602
36603var _webStreamTools = require('web-stream-tools');
36604
36605var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
36606
36607var _key = require('../key');
36608
36609var _message = require('../message');
36610
36611var _cleartext = require('../cleartext');
36612
36613var _signature = require('../signature');
36614
36615var _packetlist = require('./packetlist');
36616
36617var _packetlist2 = _interopRequireDefault(_packetlist);
36618
36619var _keyid = require('../type/keyid');
36620
36621var _keyid2 = _interopRequireDefault(_keyid);
36622
36623var _util = require('../util');
36624
36625var _util2 = _interopRequireDefault(_util);
36626
36627function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
36628
36629//////////////////////////////
36630//                          //
36631//   List --> Clone   //
36632//                          //
36633//////////////////////////////
36634
36635
36636/**
36637 * Create a packetlist from the correspoding object types.
36638 * @param  {Object} options   the object passed to and from the web worker
36639 * @returns {Object}           a mutated version of the options optject
36640 */
36641// OpenPGP.js - An OpenPGP implementation in javascript
36642// Copyright (C) 2015 Tankred Hase
36643//
36644// This library is free software; you can redistribute it and/or
36645// modify it under the terms of the GNU Lesser General Public
36646// License as published by the Free Software Foundation; either
36647// version 3.0 of the License, or (at your option) any later version.
36648//
36649// This library is distributed in the hope that it will be useful,
36650// but WITHOUT ANY WARRANTY; without even the implied warranty of
36651// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
36652// Lesser General Public License for more details.
36653//
36654// You should have received a copy of the GNU Lesser General Public
36655// License along with this library; if not, write to the Free Software
36656// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
36657
36658/**
36659 * @fileoverview This module implements packet list cloning required to
36660 * pass certain object types between the web worker and main thread using
36661 * the structured cloning algorithm.
36662 * @module packet/clone
36663 */
36664
36665function clonePackets(options) {
36666  if (options.publicKeys) {
36667    options.publicKeys = options.publicKeys.map(key => key.toPacketlist());
36668  }
36669  if (options.privateKeys) {
36670    options.privateKeys = options.privateKeys.map(key => key.toPacketlist());
36671  }
36672  if (options.privateKey) {
36673    options.privateKey = options.privateKey.toPacketlist();
36674  }
36675  if (options.key) {
36676    options.key = options.key.toPacketlist();
36677  }
36678  if (options.message) {
36679    //could be either a Message or CleartextMessage object
36680    if (options.message instanceof _message.Message) {
36681      options.message = options.message.packets;
36682    } else if (options.message instanceof _cleartext.CleartextMessage) {
36683      options.message = { text: options.message.text, signature: options.message.signature.packets };
36684    }
36685  }
36686  if (options.signature && options.signature instanceof _signature.Signature) {
36687    options.signature = options.signature.packets;
36688  }
36689  if (options.signatures) {
36690    options.signatures.forEach(verificationObjectToClone);
36691  }
36692  return options;
36693}
36694
36695function verificationObjectToClone(verObject) {
36696  const verified = verObject.verified;
36697  verObject.verified = _webStreamTools2.default.fromAsync(() => verified);
36698  if (verObject.signature instanceof Promise) {
36699    const signature = verObject.signature;
36700    verObject.signature = _webStreamTools2.default.fromAsync(async () => {
36701      const packets = (await signature).packets;
36702      try {
36703        await verified;
36704        delete packets[0].signature;
36705      } catch (e) {}
36706      return packets;
36707    });
36708  } else {
36709    verObject.signature = verObject.signature.packets;
36710  }
36711  if (verObject.error) {
36712    verObject.error = verObject.error.message;
36713  }
36714  return verObject;
36715}
36716
36717//////////////////////////////
36718//                          //
36719//   Clone --> List   //
36720//                          //
36721//////////////////////////////
36722
36723
36724/**
36725 * Creates an object with the correct prototype from a corresponding packetlist.
36726 * @param  {Object} options   the object passed to and from the web worker
36727 * @param  {String} method    the public api function name to be delegated to the worker
36728 * @returns {Object}           a mutated version of the options optject
36729 */
36730function parseClonedPackets(options) {
36731  if (options.publicKeys) {
36732    options.publicKeys = options.publicKeys.map(packetlistCloneToKey);
36733  }
36734  if (options.privateKeys) {
36735    options.privateKeys = options.privateKeys.map(packetlistCloneToKey);
36736  }
36737  if (options.privateKey) {
36738    options.privateKey = packetlistCloneToKey(options.privateKey);
36739  }
36740  if (options.key) {
36741    options.key = packetlistCloneToKey(options.key);
36742  }
36743  if (options.message && options.message.signature) {
36744    options.message = packetlistCloneToCleartextMessage(options.message);
36745  } else if (options.message) {
36746    options.message = packetlistCloneToMessage(options.message);
36747  }
36748  if (options.signatures) {
36749    options.signatures = options.signatures.map(packetlistCloneToSignatures);
36750  }
36751  if (options.signature) {
36752    options.signature = packetlistCloneToSignature(options.signature);
36753  }
36754  return options;
36755}
36756
36757function packetlistCloneToKey(clone) {
36758  const packetlist = _packetlist2.default.fromStructuredClone(clone);
36759  return new _key.Key(packetlist);
36760}
36761
36762function packetlistCloneToMessage(clone) {
36763  const packetlist = _packetlist2.default.fromStructuredClone(clone);
36764  return new _message.Message(packetlist);
36765}
36766
36767function packetlistCloneToCleartextMessage(clone) {
36768  const packetlist = _packetlist2.default.fromStructuredClone(clone.signature);
36769  return new _cleartext.CleartextMessage(clone.text, new _signature.Signature(packetlist));
36770}
36771
36772//verification objects
36773function packetlistCloneToSignatures(clone) {
36774  clone.keyid = _keyid2.default.fromClone(clone.keyid);
36775  if (_util2.default.isStream(clone.signature)) {
36776    clone.signature = _webStreamTools2.default.readToEnd(clone.signature, ([signature]) => new _signature.Signature(_packetlist2.default.fromStructuredClone(signature)));
36777    clone.signature.catch(() => {});
36778  } else {
36779    clone.signature = new _signature.Signature(_packetlist2.default.fromStructuredClone(clone.signature));
36780  }
36781  clone.verified = _webStreamTools2.default.readToEnd(clone.verified, ([verified]) => verified);
36782  clone.verified.catch(() => {});
36783  if (clone.error) {
36784    clone.error = new Error(clone.error);
36785  }
36786  return clone;
36787}
36788
36789function packetlistCloneToSignature(clone) {
36790  if (_util2.default.isString(clone) || _util2.default.isStream(clone)) {
36791    //signature is armored
36792    return clone;
36793  }
36794  const packetlist = _packetlist2.default.fromStructuredClone(clone);
36795  return new _signature.Signature(packetlist);
36796}
36797
36798},{"../cleartext":78,"../key":117,"../message":121,"../signature":146,"../type/keyid":149,"../util":153,"./packetlist":131,"web-stream-tools":76}],125:[function(require,module,exports){
36799'use strict';
36800
36801Object.defineProperty(exports, "__esModule", {
36802  value: true
36803});
36804
36805var _pako = require('pako');
36806
36807var _pako2 = _interopRequireDefault(_pako);
36808
36809var _seekBzip = require('seek-bzip');
36810
36811var _seekBzip2 = _interopRequireDefault(_seekBzip);
36812
36813var _webStreamTools = require('web-stream-tools');
36814
36815var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
36816
36817var _config = require('../config');
36818
36819var _config2 = _interopRequireDefault(_config);
36820
36821var _enums = require('../enums');
36822
36823var _enums2 = _interopRequireDefault(_enums);
36824
36825var _util = require('../util');
36826
36827var _util2 = _interopRequireDefault(_util);
36828
36829function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
36830
36831/**
36832 * Implementation of the Compressed Data Packet (Tag 8)
36833 *
36834 * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:
36835 * The Compressed Data packet contains compressed data.  Typically,
36836 * this packet is found as the contents of an encrypted packet, or following
36837 * a Signature or One-Pass Signature packet, and contains a literal data packet.
36838 * @memberof module:packet
36839 * @constructor
36840 */
36841// GPG4Browsers - An OpenPGP implementation in javascript
36842// Copyright (C) 2011 Recurity Labs GmbH
36843//
36844// This library is free software; you can redistribute it and/or
36845// modify it under the terms of the GNU Lesser General Public
36846// License as published by the Free Software Foundation; either
36847// version 3.0 of the License, or (at your option) any later version.
36848//
36849// This library is distributed in the hope that it will be useful,
36850// but WITHOUT ANY WARRANTY; without even the implied warranty of
36851// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
36852// Lesser General Public License for more details.
36853//
36854// You should have received a copy of the GNU Lesser General Public
36855// License along with this library; if not, write to the Free Software
36856// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
36857
36858/**
36859 * @requires web-stream-tools
36860 * @requires pako
36861 * @requires config
36862 * @requires enums
36863 * @requires util
36864 * @requires compression/bzip2
36865 */
36866
36867function Compressed() {
36868  /**
36869   * Packet type
36870   * @type {module:enums.packet}
36871   */
36872  this.tag = _enums2.default.packet.compressed;
36873  /**
36874   * List of packets
36875   * @type {module:packet.List}
36876   */
36877  this.packets = null;
36878  /**
36879   * Compression algorithm
36880   * @type {compression}
36881   */
36882  this.algorithm = 'zip';
36883
36884  /**
36885   * Compressed packet data
36886   * @type {Uint8Array | ReadableStream<Uint8Array>}
36887   */
36888  this.compressed = null;
36889}
36890
36891/**
36892 * Parsing function for the packet.
36893 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes Payload of a tag 8 packet
36894 */
36895Compressed.prototype.read = async function (bytes, streaming) {
36896  await _webStreamTools2.default.parse(bytes, async reader => {
36897
36898    // One octet that gives the algorithm used to compress the packet.
36899    this.algorithm = _enums2.default.read(_enums2.default.compression, (await reader.readByte()));
36900
36901    // Compressed data, which makes up the remainder of the packet.
36902    this.compressed = reader.remainder();
36903
36904    await this.decompress(streaming);
36905  });
36906};
36907
36908/**
36909 * Return the compressed packet.
36910 * @returns {Uint8Array | ReadableStream<Uint8Array>} binary compressed packet
36911 */
36912Compressed.prototype.write = function () {
36913  if (this.compressed === null) {
36914    this.compress();
36915  }
36916
36917  return _util2.default.concat([new Uint8Array([_enums2.default.write(_enums2.default.compression, this.algorithm)]), this.compressed]);
36918};
36919
36920/**
36921 * Decompression method for decompressing the compressed data
36922 * read by read_packet
36923 */
36924Compressed.prototype.decompress = async function (streaming) {
36925
36926  if (!decompress_fns[this.algorithm]) {
36927    throw new Error(this.algorithm + ' decompression not supported');
36928  }
36929
36930  await this.packets.read(decompress_fns[this.algorithm](this.compressed), streaming);
36931};
36932
36933/**
36934 * Compress the packet data (member decompressedData)
36935 */
36936Compressed.prototype.compress = function () {
36937
36938  if (!compress_fns[this.algorithm]) {
36939    throw new Error(this.algorithm + ' compression not supported');
36940  }
36941
36942  this.compressed = compress_fns[this.algorithm](this.packets.write());
36943};
36944
36945exports.default = Compressed;
36946
36947//////////////////////////
36948//                      //
36949//   Helper functions   //
36950//                      //
36951//////////////////////////
36952
36953
36954const nodeZlib = _util2.default.getNodeZlib();
36955
36956function node_zlib(func, options = {}) {
36957  return function (data) {
36958    return _webStreamTools2.default.nodeToWeb(_webStreamTools2.default.webToNode(data).pipe(func(options)));
36959  };
36960}
36961
36962function pako_zlib(constructor, options = {}) {
36963  return function (data) {
36964    const obj = new constructor(options);
36965    return _webStreamTools2.default.transform(data, value => {
36966      if (value.length) {
36967        obj.push(value, _pako2.default.Z_SYNC_FLUSH);
36968        return obj.result;
36969      }
36970    }, () => {
36971      if (constructor === _pako2.default.Deflate) {
36972        obj.push([], _pako2.default.Z_FINISH);
36973        return obj.result;
36974      }
36975    });
36976  };
36977}
36978
36979function bzip2(func) {
36980  return function (data) {
36981    return _webStreamTools2.default.fromAsync(async () => func((await _webStreamTools2.default.readToEnd(data))));
36982  };
36983}
36984
36985let compress_fns;
36986let decompress_fns;
36987if (nodeZlib) {
36988  // Use Node native zlib for DEFLATE compression/decompression
36989  compress_fns = {
36990    zip: node_zlib(nodeZlib.createDeflateRaw, { level: _config2.default.deflate_level }),
36991    zlib: node_zlib(nodeZlib.createDeflate, { level: _config2.default.deflate_level })
36992  };
36993
36994  decompress_fns = {
36995    zip: node_zlib(nodeZlib.createInflateRaw),
36996    zlib: node_zlib(nodeZlib.createInflate),
36997    bzip2: bzip2(_seekBzip2.default.decode)
36998  };
36999} else {
37000  // Use JS fallbacks
37001  compress_fns = {
37002    zip: pako_zlib(_pako2.default.Deflate, { raw: true, level: _config2.default.deflate_level }),
37003    zlib: pako_zlib(_pako2.default.Deflate, { level: _config2.default.deflate_level })
37004  };
37005
37006  decompress_fns = {
37007    zip: pako_zlib(_pako2.default.Inflate, { raw: true }),
37008    zlib: pako_zlib(_pako2.default.Inflate),
37009    bzip2: bzip2(_seekBzip2.default.decode)
37010  };
37011}
37012
37013},{"../config":80,"../enums":114,"../util":153,"pako":51,"seek-bzip":70,"web-stream-tools":76}],126:[function(require,module,exports){
37014'use strict';
37015
37016Object.defineProperty(exports, "__esModule", {
37017  value: true
37018});
37019
37020var _all_packets = require('./all_packets');
37021
37022var packets = _interopRequireWildcard(_all_packets);
37023
37024var _clone = require('./clone');
37025
37026var clone = _interopRequireWildcard(_clone);
37027
37028var _packetlist = require('./packetlist');
37029
37030var _packetlist2 = _interopRequireDefault(_packetlist);
37031
37032function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
37033
37034function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
37035
37036const mod = {
37037  List: _packetlist2.default,
37038  clone
37039}; /**
37040    * @fileoverview OpenPGP packet types
37041    * @see module:packet/all_packets
37042    * @see module:packet/clone
37043    * @see module:packet.List
37044    * @module packet
37045    */
37046
37047Object.assign(mod, packets);
37048
37049exports.default = mod;
37050
37051},{"./all_packets":123,"./clone":124,"./packetlist":131}],127:[function(require,module,exports){
37052'use strict';
37053
37054Object.defineProperty(exports, "__esModule", {
37055  value: true
37056});
37057
37058var _webStreamTools = require('web-stream-tools');
37059
37060var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
37061
37062var _enums = require('../enums');
37063
37064var _enums2 = _interopRequireDefault(_enums);
37065
37066var _util = require('../util');
37067
37068var _util2 = _interopRequireDefault(_util);
37069
37070function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
37071
37072/**
37073 * Implementation of the Literal Data Packet (Tag 11)
37074 *
37075 * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:
37076 * A Literal Data packet contains the body of a message; data that is not to be
37077 * further interpreted.
37078 * @param {Date} date the creation date of the literal package
37079 * @memberof module:packet
37080 * @constructor
37081 */
37082function Literal(date = new Date()) {
37083  this.tag = _enums2.default.packet.literal;
37084  this.format = 'utf8'; // default format for literal data packets
37085  this.date = _util2.default.normalizeDate(date);
37086  this.text = null; // textual data representation
37087  this.data = null; // literal data representation
37088  this.filename = 'msg.txt';
37089}
37090
37091/**
37092 * Set the packet data to a javascript native string, end of line
37093 * will be normalized to \r\n and by default text is converted to UTF8
37094 * @param {String | ReadableStream<String>} text Any native javascript string
37095 * @param {utf8|binary|text|mime} format (optional) The format of the string of bytes
37096 */
37097// GPG4Browsers - An OpenPGP implementation in javascript
37098// Copyright (C) 2011 Recurity Labs GmbH
37099//
37100// This library is free software; you can redistribute it and/or
37101// modify it under the terms of the GNU Lesser General Public
37102// License as published by the Free Software Foundation; either
37103// version 3.0 of the License, or (at your option) any later version.
37104//
37105// This library is distributed in the hope that it will be useful,
37106// but WITHOUT ANY WARRANTY; without even the implied warranty of
37107// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
37108// Lesser General Public License for more details.
37109//
37110// You should have received a copy of the GNU Lesser General Public
37111// License along with this library; if not, write to the Free Software
37112// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
37113
37114/**
37115 * @requires web-stream-tools
37116 * @requires enums
37117 * @requires util
37118 */
37119
37120Literal.prototype.setText = function (text, format = 'utf8') {
37121  this.format = format;
37122  this.text = text;
37123  this.data = null;
37124};
37125
37126/**
37127 * Returns literal data packets as native JavaScript string
37128 * with normalized end of line to \n
37129 * @param {Boolean} clone (optional) Whether to return a clone so that getBytes/getText can be called again
37130 * @returns {String | ReadableStream<String>} literal data as text
37131 */
37132Literal.prototype.getText = function (clone = false) {
37133  if (this.text === null || _util2.default.isStream(this.text)) {
37134    // Assume that this.text has been read
37135    this.text = _util2.default.nativeEOL(_util2.default.decode_utf8(this.getBytes(clone)));
37136  }
37137  return this.text;
37138};
37139
37140/**
37141 * Set the packet data to value represented by the provided string of bytes.
37142 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes The string of bytes
37143 * @param {utf8|binary|text|mime} format The format of the string of bytes
37144 */
37145Literal.prototype.setBytes = function (bytes, format) {
37146  this.format = format;
37147  this.data = bytes;
37148  this.text = null;
37149};
37150
37151/**
37152 * Get the byte sequence representing the literal packet data
37153 * @param {Boolean} clone (optional) Whether to return a clone so that getBytes/getText can be called again
37154 * @returns {Uint8Array | ReadableStream<Uint8Array>} A sequence of bytes
37155 */
37156Literal.prototype.getBytes = function (clone = false) {
37157  if (this.data === null) {
37158    // normalize EOL to \r\n and encode UTF8
37159    this.data = _util2.default.encode_utf8(_util2.default.canonicalizeEOL(this.text));
37160  }
37161  if (clone) {
37162    return _webStreamTools2.default.passiveClone(this.data);
37163  }
37164  return this.data;
37165};
37166
37167/**
37168 * Sets the filename of the literal packet data
37169 * @param {String} filename Any native javascript string
37170 */
37171Literal.prototype.setFilename = function (filename) {
37172  this.filename = filename;
37173};
37174
37175/**
37176 * Get the filename of the literal packet data
37177 * @returns {String} filename
37178 */
37179Literal.prototype.getFilename = function () {
37180  return this.filename;
37181};
37182
37183/**
37184 * Parsing function for a literal data packet (tag 11).
37185 *
37186 * @param {Uint8Array | ReadableStream<Uint8Array>} input Payload of a tag 11 packet
37187 * @returns {module:packet.Literal} object representation
37188 */
37189Literal.prototype.read = async function (bytes) {
37190  await _webStreamTools2.default.parse(bytes, async reader => {
37191    // - A one-octet field that describes how the data is formatted.
37192    const format = _enums2.default.read(_enums2.default.literal, (await reader.readByte()));
37193
37194    const filename_len = await reader.readByte();
37195    this.filename = _util2.default.decode_utf8((await reader.readBytes(filename_len)));
37196
37197    this.date = _util2.default.readDate((await reader.readBytes(4)));
37198
37199    const data = reader.remainder();
37200
37201    this.setBytes(data, format);
37202  });
37203};
37204
37205/**
37206 * Creates a string representation of the packet
37207 *
37208 * @returns {Uint8Array | ReadableStream<Uint8Array>} Uint8Array representation of the packet
37209 */
37210Literal.prototype.write = function () {
37211  const filename = _util2.default.encode_utf8(this.filename);
37212  const filename_length = new Uint8Array([filename.length]);
37213
37214  const format = new Uint8Array([_enums2.default.write(_enums2.default.literal, this.format)]);
37215  const date = _util2.default.writeDate(this.date);
37216  const data = this.getBytes();
37217
37218  return _util2.default.concat([format, filename_length, filename, date, data]);
37219};
37220
37221exports.default = Literal;
37222
37223},{"../enums":114,"../util":153,"web-stream-tools":76}],128:[function(require,module,exports){
37224'use strict';
37225
37226Object.defineProperty(exports, "__esModule", {
37227  value: true
37228});
37229
37230var _enums = require('../enums');
37231
37232var _enums2 = _interopRequireDefault(_enums);
37233
37234function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
37235
37236/**
37237 * Implementation of the strange "Marker packet" (Tag 10)
37238 *
37239 * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:
37240 * An experimental version of PGP used this packet as the Literal
37241 * packet, but no released version of PGP generated Literal packets with this
37242 * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as
37243 * the Marker packet.
37244 *
37245 * Such a packet MUST be ignored when received.
37246 * @memberof module:packet
37247 * @constructor
37248 */
37249function Marker() {
37250  this.tag = _enums2.default.packet.marker;
37251}
37252
37253/**
37254 * Parsing function for a literal data packet (tag 10).
37255 *
37256 * @param {String} input Payload of a tag 10 packet
37257 * @param {Integer} position
37258 *            Position to start reading from the input string
37259 * @param {Integer} len
37260 *            Length of the packet or the remaining length of
37261 *            input at position
37262 * @returns {module:packet.Marker} Object representation
37263 */
37264// GPG4Browsers - An OpenPGP implementation in javascript
37265// Copyright (C) 2011 Recurity Labs GmbH
37266//
37267// This library is free software; you can redistribute it and/or
37268// modify it under the terms of the GNU Lesser General Public
37269// License as published by the Free Software Foundation; either
37270// version 3.0 of the License, or (at your option) any later version.
37271//
37272// This library is distributed in the hope that it will be useful,
37273// but WITHOUT ANY WARRANTY; without even the implied warranty of
37274// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
37275// Lesser General Public License for more details.
37276//
37277// You should have received a copy of the GNU Lesser General Public
37278// License along with this library; if not, write to the Free Software
37279// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
37280
37281/**
37282 * @requires enums
37283 */
37284
37285Marker.prototype.read = function (bytes) {
37286  if (bytes[0] === 0x50 && // P
37287  bytes[1] === 0x47 && // G
37288  bytes[2] === 0x50) {
37289    // P
37290    return true;
37291  }
37292  // marker packet does not contain "PGP"
37293  return false;
37294};
37295
37296exports.default = Marker;
37297
37298},{"../enums":114}],129:[function(require,module,exports){
37299'use strict';
37300
37301Object.defineProperty(exports, "__esModule", {
37302  value: true
37303});
37304
37305var _signature = require('./signature');
37306
37307var _signature2 = _interopRequireDefault(_signature);
37308
37309var _keyid = require('../type/keyid');
37310
37311var _keyid2 = _interopRequireDefault(_keyid);
37312
37313var _enums = require('../enums');
37314
37315var _enums2 = _interopRequireDefault(_enums);
37316
37317var _util = require('../util');
37318
37319var _util2 = _interopRequireDefault(_util);
37320
37321function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
37322
37323/**
37324 * Implementation of the One-Pass Signature Packets (Tag 4)
37325 *
37326 * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:
37327 * The One-Pass Signature packet precedes the signed data and contains
37328 * enough information to allow the receiver to begin calculating any
37329 * hashes needed to verify the signature.  It allows the Signature
37330 * packet to be placed at the end of the message, so that the signer
37331 * can compute the entire signed message in one pass.
37332 * @memberof module:packet
37333 * @constructor
37334 */
37335// GPG4Browsers - An OpenPGP implementation in javascript
37336// Copyright (C) 2011 Recurity Labs GmbH
37337//
37338// This library is free software; you can redistribute it and/or
37339// modify it under the terms of the GNU Lesser General Public
37340// License as published by the Free Software Foundation; either
37341// version 3.0 of the License, or (at your option) any later version.
37342//
37343// This library is distributed in the hope that it will be useful,
37344// but WITHOUT ANY WARRANTY; without even the implied warranty of
37345// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
37346// Lesser General Public License for more details.
37347//
37348// You should have received a copy of the GNU Lesser General Public
37349// License along with this library; if not, write to the Free Software
37350// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
37351
37352/**
37353 * @requires packet/signature
37354 * @requires type/keyid
37355 * @requires enums
37356 * @requires util
37357 */
37358
37359function OnePassSignature() {
37360  /**
37361   * Packet type
37362   * @type {module:enums.packet}
37363   */
37364  this.tag = _enums2.default.packet.onePassSignature;
37365  /** A one-octet version number.  The current version is 3. */
37366  this.version = null;
37367  /**
37368   * A one-octet signature type.
37369   * Signature types are described in
37370   * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.
37371   */
37372  this.signatureType = null;
37373  /**
37374   * A one-octet number describing the hash algorithm used.
37375   * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}
37376   */
37377  this.hashAlgorithm = null;
37378  /**
37379   * A one-octet number describing the public-key algorithm used.
37380   * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}
37381   */
37382  this.publicKeyAlgorithm = null;
37383  /** An eight-octet number holding the Key ID of the signing key. */
37384  this.issuerKeyId = null;
37385  /**
37386   * A one-octet number holding a flag showing whether the signature is nested.
37387   * A zero value indicates that the next packet is another One-Pass Signature packet
37388   * that describes another signature to be applied to the same message data.
37389   */
37390  this.flags = null;
37391}
37392
37393/**
37394 * parsing function for a one-pass signature packet (tag 4).
37395 * @param {Uint8Array} bytes payload of a tag 4 packet
37396 * @returns {module:packet.OnePassSignature} object representation
37397 */
37398OnePassSignature.prototype.read = function (bytes) {
37399  let mypos = 0;
37400  // A one-octet version number.  The current version is 3.
37401  this.version = bytes[mypos++];
37402
37403  // A one-octet signature type.  Signature types are described in
37404  //   Section 5.2.1.
37405  this.signatureType = bytes[mypos++];
37406
37407  // A one-octet number describing the hash algorithm used.
37408  this.hashAlgorithm = bytes[mypos++];
37409
37410  // A one-octet number describing the public-key algorithm used.
37411  this.publicKeyAlgorithm = bytes[mypos++];
37412
37413  // An eight-octet number holding the Key ID of the signing key.
37414  this.issuerKeyId = new _keyid2.default();
37415  this.issuerKeyId.read(bytes.subarray(mypos, mypos + 8));
37416  mypos += 8;
37417
37418  // A one-octet number holding a flag showing whether the signature
37419  //   is nested.  A zero value indicates that the next packet is
37420  //   another One-Pass Signature packet that describes another
37421  //   signature to be applied to the same message data.
37422  this.flags = bytes[mypos++];
37423  return this;
37424};
37425
37426/**
37427 * creates a string representation of a one-pass signature packet
37428 * @returns {Uint8Array} a Uint8Array representation of a one-pass signature packet
37429 */
37430OnePassSignature.prototype.write = function () {
37431  const start = new Uint8Array([3, _enums2.default.write(_enums2.default.signature, this.signatureType), _enums2.default.write(_enums2.default.hash, this.hashAlgorithm), _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm)]);
37432
37433  const end = new Uint8Array([this.flags]);
37434
37435  return _util2.default.concatUint8Array([start, this.issuerKeyId.write(), end]);
37436};
37437
37438/**
37439 * Fix custom types after cloning
37440 */
37441OnePassSignature.prototype.postCloneTypeFix = function () {
37442  this.issuerKeyId = _keyid2.default.fromClone(this.issuerKeyId);
37443};
37444
37445OnePassSignature.prototype.hash = function () {
37446  const version = this.version;
37447  this.version = 4;
37448  try {
37449    return _signature2.default.prototype.hash.apply(this, arguments);
37450  } finally {
37451    this.version = version;
37452  }
37453};
37454OnePassSignature.prototype.toHash = _signature2.default.prototype.toHash;
37455OnePassSignature.prototype.toSign = _signature2.default.prototype.toSign;
37456OnePassSignature.prototype.calculateTrailer = _signature2.default.prototype.calculateTrailer;
37457
37458OnePassSignature.prototype.verify = async function () {
37459  const correspondingSig = await this.correspondingSig;
37460  if (!correspondingSig || correspondingSig.tag !== _enums2.default.packet.signature) {
37461    throw new Error('Corresponding signature packet missing');
37462  }
37463  if (correspondingSig.signatureType !== this.signatureType || correspondingSig.hashAlgorithm !== this.hashAlgorithm || correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm || !correspondingSig.issuerKeyId.equals(this.issuerKeyId)) {
37464    throw new Error('Corresponding signature packet does not match one-pass signature packet');
37465  }
37466  correspondingSig.hashed = this.hashed;
37467  return correspondingSig.verify.apply(correspondingSig, arguments);
37468};
37469
37470exports.default = OnePassSignature;
37471
37472},{"../enums":114,"../type/keyid":149,"../util":153,"./signature":137}],130:[function(require,module,exports){
37473'use strict';
37474
37475Object.defineProperty(exports, "__esModule", {
37476  value: true
37477});
37478
37479var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); // GPG4Browsers - An OpenPGP implementation in javascript
37480// Copyright (C) 2011 Recurity Labs GmbH
37481//
37482// This library is free software; you can redistribute it and/or
37483// modify it under the terms of the GNU Lesser General Public
37484// License as published by the Free Software Foundation; either
37485// version 3.0 of the License, or (at your option) any later version.
37486//
37487// This library is distributed in the hope that it will be useful,
37488// but WITHOUT ANY WARRANTY; without even the implied warranty of
37489// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
37490// Lesser General Public License for more details.
37491//
37492// You should have received a copy of the GNU Lesser General Public
37493// License along with this library; if not, write to the Free Software
37494// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
37495
37496/* eslint-disable callback-return */
37497
37498/**
37499 * @fileoverview Functions for reading and writing packets
37500 * @requires web-stream-tools
37501 * @requires enums
37502 * @requires util
37503 * @module packet/packet
37504 */
37505
37506var _webStreamTools = require('web-stream-tools');
37507
37508var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
37509
37510var _enums = require('../enums');
37511
37512var _enums2 = _interopRequireDefault(_enums);
37513
37514var _util = require('../util');
37515
37516var _util2 = _interopRequireDefault(_util);
37517
37518function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
37519
37520exports.default = {
37521  readSimpleLength: function readSimpleLength(bytes) {
37522    let len = 0;
37523    let offset;
37524    const type = bytes[0];
37525
37526    if (type < 192) {
37527      var _bytes = _slicedToArray(bytes, 1);
37528
37529      len = _bytes[0];
37530
37531      offset = 1;
37532    } else if (type < 255) {
37533      len = (bytes[0] - 192 << 8) + bytes[1] + 192;
37534      offset = 2;
37535    } else if (type === 255) {
37536      len = _util2.default.readNumber(bytes.subarray(1, 1 + 4));
37537      offset = 5;
37538    }
37539
37540    return {
37541      len: len,
37542      offset: offset
37543    };
37544  },
37545
37546  /**
37547   * Encodes a given integer of length to the openpgp length specifier to a
37548   * string
37549   *
37550   * @param {Integer} length The length to encode
37551   * @returns {Uint8Array} String with openpgp length representation
37552   */
37553  writeSimpleLength: function writeSimpleLength(length) {
37554    if (length < 192) {
37555      return new Uint8Array([length]);
37556    } else if (length > 191 && length < 8384) {
37557      /*
37558       * let a = (total data packet length) - 192 let bc = two octet
37559       * representation of a let d = b + 192
37560       */
37561      return new Uint8Array([(length - 192 >> 8) + 192, length - 192 & 0xFF]);
37562    }
37563    return _util2.default.concatUint8Array([new Uint8Array([255]), _util2.default.writeNumber(length, 4)]);
37564  },
37565
37566  writePartialLength: function writePartialLength(power) {
37567    if (power < 0 || power > 30) {
37568      throw new Error('Partial Length power must be between 1 and 30');
37569    }
37570    return new Uint8Array([224 + power]);
37571  },
37572
37573  writeTag: function writeTag(tag_type) {
37574    /* we're only generating v4 packet headers here */
37575    return new Uint8Array([0xC0 | tag_type]);
37576  },
37577
37578  /**
37579   * Writes a packet header version 4 with the given tag_type and length to a
37580   * string
37581   *
37582   * @param {Integer} tag_type Tag type
37583   * @param {Integer} length Length of the payload
37584   * @returns {String} String of the header
37585   */
37586  writeHeader: function writeHeader(tag_type, length) {
37587    /* we're only generating v4 packet headers here */
37588    return _util2.default.concatUint8Array([this.writeTag(tag_type), this.writeSimpleLength(length)]);
37589  },
37590
37591  /**
37592   * Writes a packet header Version 3 with the given tag_type and length to a
37593   * string
37594   *
37595   * @param {Integer} tag_type Tag type
37596   * @param {Integer} length Length of the payload
37597   * @returns {String} String of the header
37598   */
37599  writeOldHeader: function writeOldHeader(tag_type, length) {
37600    if (length < 256) {
37601      return new Uint8Array([0x80 | tag_type << 2, length]);
37602    } else if (length < 65536) {
37603      return _util2.default.concatUint8Array([new Uint8Array([0x80 | tag_type << 2 | 1]), _util2.default.writeNumber(length, 2)]);
37604    }
37605    return _util2.default.concatUint8Array([new Uint8Array([0x80 | tag_type << 2 | 2]), _util2.default.writeNumber(length, 4)]);
37606  },
37607
37608  /**
37609   * Whether the packet type supports partial lengths per RFC4880
37610   * @param {Integer} tag_type Tag type
37611   * @returns {Boolean} String of the header
37612   */
37613  supportsStreaming: function supportsStreaming(tag_type) {
37614    return [_enums2.default.packet.literal, _enums2.default.packet.compressed, _enums2.default.packet.symmetricallyEncrypted, _enums2.default.packet.symEncryptedIntegrityProtected, _enums2.default.packet.symEncryptedAEADProtected].includes(tag_type);
37615  },
37616
37617  /**
37618   * Generic static Packet Parser function
37619   *
37620   * @param {Uint8Array | ReadableStream<Uint8Array>} input Input stream as string
37621   * @param {Function} callback Function to call with the parsed packet
37622   * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.
37623   */
37624  read: async function read(input, streaming, callback) {
37625    const reader = _webStreamTools2.default.getReader(input);
37626    let writer;
37627    try {
37628      const peekedBytes = await reader.peekBytes(2);
37629      // some sanity checks
37630      if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {
37631        throw new Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format.");
37632      }
37633      const headerByte = await reader.readByte();
37634      let tag = -1;
37635      let format = -1;
37636      let packet_length;
37637
37638      format = 0; // 0 = old format; 1 = new format
37639      if ((headerByte & 0x40) !== 0) {
37640        format = 1;
37641      }
37642
37643      let packet_length_type;
37644      if (format) {
37645        // new format header
37646        tag = headerByte & 0x3F; // bit 5-0
37647      } else {
37648        // old format header
37649        tag = (headerByte & 0x3F) >> 2; // bit 5-2
37650        packet_length_type = headerByte & 0x03; // bit 1-0
37651      }
37652
37653      const supportsStreaming = this.supportsStreaming(tag);
37654      let packet = null;
37655      let callbackReturned;
37656      if (streaming && supportsStreaming) {
37657        const transform = new TransformStream();
37658        writer = _webStreamTools2.default.getWriter(transform.writable);
37659        packet = transform.readable;
37660        callbackReturned = callback({ tag, packet });
37661      } else {
37662        packet = [];
37663      }
37664
37665      let wasPartialLength;
37666      do {
37667        if (!format) {
37668          // 4.2.1. Old Format Packet Lengths
37669          switch (packet_length_type) {
37670            case 0:
37671              // The packet has a one-octet length. The header is 2 octets
37672              // long.
37673              packet_length = await reader.readByte();
37674              break;
37675            case 1:
37676              // The packet has a two-octet length. The header is 3 octets
37677              // long.
37678              packet_length = (await reader.readByte()) << 8 | (await reader.readByte());
37679              break;
37680            case 2:
37681              // The packet has a four-octet length. The header is 5
37682              // octets long.
37683              packet_length = (await reader.readByte()) << 24 | (await reader.readByte()) << 16 | (await reader.readByte()) << 8 | (await reader.readByte());
37684              break;
37685            default:
37686              // 3 - The packet is of indeterminate length. The header is 1
37687              // octet long, and the implementation must determine how long
37688              // the packet is. If the packet is in a file, this means that
37689              // the packet extends until the end of the file. In general,
37690              // an implementation SHOULD NOT use indeterminate-length
37691              // packets except where the end of the data will be clear
37692              // from the context, and even then it is better to use a
37693              // definite length, or a new format header. The new format
37694              // headers described below have a mechanism for precisely
37695              // encoding data of indeterminate length.
37696              packet_length = Infinity;
37697              break;
37698          }
37699        } else {
37700          // 4.2.2. New Format Packet Lengths
37701          // 4.2.2.1. One-Octet Lengths
37702          const lengthByte = await reader.readByte();
37703          wasPartialLength = false;
37704          if (lengthByte < 192) {
37705            packet_length = lengthByte;
37706            // 4.2.2.2. Two-Octet Lengths
37707          } else if (lengthByte >= 192 && lengthByte < 224) {
37708            packet_length = (lengthByte - 192 << 8) + (await reader.readByte()) + 192;
37709            // 4.2.2.4. Partial Body Lengths
37710          } else if (lengthByte > 223 && lengthByte < 255) {
37711            packet_length = 1 << (lengthByte & 0x1F);
37712            wasPartialLength = true;
37713            if (!supportsStreaming) {
37714              throw new TypeError('This packet type does not support partial lengths.');
37715            }
37716            // 4.2.2.3. Five-Octet Lengths
37717          } else {
37718            packet_length = (await reader.readByte()) << 24 | (await reader.readByte()) << 16 | (await reader.readByte()) << 8 | (await reader.readByte());
37719          }
37720        }
37721        if (packet_length > 0) {
37722          let bytesRead = 0;
37723          while (true) {
37724            if (writer) await writer.ready;
37725
37726            var _ref = await reader.read();
37727
37728            const done = _ref.done,
37729                  value = _ref.value;
37730
37731            if (done) {
37732              if (packet_length === Infinity) break;
37733              throw new Error('Unexpected end of packet');
37734            }
37735            const chunk = packet_length === Infinity ? value : value.subarray(0, packet_length - bytesRead);
37736            if (writer) await writer.write(chunk);else packet.push(chunk);
37737            bytesRead += value.length;
37738            if (bytesRead >= packet_length) {
37739              reader.unshift(value.subarray(packet_length - bytesRead + value.length));
37740              break;
37741            }
37742          }
37743        }
37744      } while (wasPartialLength);
37745
37746      if (!writer) {
37747        packet = _util2.default.concatUint8Array(packet);
37748        await callback({ tag, packet });
37749      }
37750      const nextPacket = await reader.peekBytes(2);
37751      if (writer) {
37752        await writer.ready;
37753        await writer.close();
37754        await callbackReturned;
37755      }
37756      return !nextPacket || !nextPacket.length;
37757    } catch (e) {
37758      if (writer) {
37759        await writer.abort(e);
37760        return true;
37761      } else {
37762        throw e;
37763      }
37764    } finally {
37765      reader.releaseLock();
37766    }
37767  }
37768};
37769
37770},{"../enums":114,"../util":153,"web-stream-tools":76}],131:[function(require,module,exports){
37771'use strict';
37772
37773Object.defineProperty(exports, "__esModule", {
37774  value: true
37775});
37776
37777var _webStreamTools = require('web-stream-tools');
37778
37779var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
37780
37781var _all_packets = require('./all_packets');
37782
37783var packets = _interopRequireWildcard(_all_packets);
37784
37785var _packet = require('./packet');
37786
37787var _packet2 = _interopRequireDefault(_packet);
37788
37789var _config = require('../config');
37790
37791var _config2 = _interopRequireDefault(_config);
37792
37793var _enums = require('../enums');
37794
37795var _enums2 = _interopRequireDefault(_enums);
37796
37797var _util = require('../util');
37798
37799var _util2 = _interopRequireDefault(_util);
37800
37801function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
37802
37803function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
37804
37805/**
37806 * This class represents a list of openpgp packets.
37807 * Take care when iterating over it - the packets themselves
37808 * are stored as numerical indices.
37809 * @memberof module:packet
37810 * @constructor
37811 * @extends Array
37812 */
37813/* eslint-disable callback-return */
37814/**
37815 * @requires web-stream-tools
37816 * @requires packet/all_packets
37817 * @requires packet/packet
37818 * @requires config
37819 * @requires enums
37820 * @requires util
37821 */
37822
37823function List() {
37824  /**
37825   * The number of packets contained within the list.
37826   * @readonly
37827   * @type {Integer}
37828   */
37829  this.length = 0;
37830}
37831
37832List.prototype = [];
37833
37834/**
37835 * Reads a stream of binary data and interprents it as a list of packets.
37836 * @param {Uint8Array | ReadableStream<Uint8Array>} A Uint8Array of bytes.
37837 */
37838List.prototype.read = async function (bytes, streaming) {
37839  this.stream = _webStreamTools2.default.transformPair(bytes, async (readable, writable) => {
37840    const writer = _webStreamTools2.default.getWriter(writable);
37841    try {
37842      while (true) {
37843        await writer.ready;
37844        const done = await _packet2.default.read(readable, streaming, async parsed => {
37845          try {
37846            const tag = _enums2.default.read(_enums2.default.packet, parsed.tag);
37847            const packet = packets.newPacketFromTag(tag);
37848            packet.packets = new List();
37849            packet.fromStream = _util2.default.isStream(parsed.packet);
37850            await packet.read(parsed.packet, streaming);
37851            await writer.write(packet);
37852          } catch (e) {
37853            if (!_config2.default.tolerant || _packet2.default.supportsStreaming(parsed.tag)) {
37854              // The packets that support streaming are the ones that contain
37855              // message data. Those are also the ones we want to be more strict
37856              // about and throw on parse errors for.
37857              await writer.abort(e);
37858            }
37859            _util2.default.print_debug_error(e);
37860          }
37861        });
37862        if (done) {
37863          await writer.ready;
37864          await writer.close();
37865          return;
37866        }
37867      }
37868    } catch (e) {
37869      await writer.abort(e);
37870    }
37871  });
37872
37873  // Wait until first few packets have been read
37874  const reader = _webStreamTools2.default.getReader(this.stream);
37875  while (true) {
37876    var _ref = await reader.read();
37877
37878    const done = _ref.done,
37879          value = _ref.value;
37880
37881    if (!done) {
37882      this.push(value);
37883    } else {
37884      this.stream = null;
37885    }
37886    if (done || _packet2.default.supportsStreaming(value.tag)) {
37887      break;
37888    }
37889  }
37890  reader.releaseLock();
37891};
37892
37893/**
37894 * Creates a binary representation of openpgp objects contained within the
37895 * class instance.
37896 * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.
37897 */
37898List.prototype.write = function () {
37899  const arr = [];
37900
37901  for (let i = 0; i < this.length; i++) {
37902    const packetbytes = this[i].write();
37903    if (_util2.default.isStream(packetbytes) && _packet2.default.supportsStreaming(this[i].tag)) {
37904      let buffer = [];
37905      let bufferLength = 0;
37906      const minLength = 512;
37907      arr.push(_packet2.default.writeTag(this[i].tag));
37908      arr.push(_webStreamTools2.default.transform(packetbytes, value => {
37909        buffer.push(value);
37910        bufferLength += value.length;
37911        if (bufferLength >= minLength) {
37912          const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);
37913          const chunkSize = 2 ** powerOf2;
37914          const bufferConcat = _util2.default.concat([_packet2.default.writePartialLength(powerOf2)].concat(buffer));
37915          buffer = [bufferConcat.subarray(1 + chunkSize)];
37916          bufferLength = buffer[0].length;
37917          return bufferConcat.subarray(0, 1 + chunkSize);
37918        }
37919      }, () => _util2.default.concat([_packet2.default.writeSimpleLength(bufferLength)].concat(buffer))));
37920    } else {
37921      if (_util2.default.isStream(packetbytes)) {
37922        let length = 0;
37923        arr.push(_webStreamTools2.default.transform(_webStreamTools2.default.clone(packetbytes), value => {
37924          length += value.length;
37925        }, () => _packet2.default.writeHeader(this[i].tag, length)));
37926      } else {
37927        arr.push(_packet2.default.writeHeader(this[i].tag, packetbytes.length));
37928      }
37929      arr.push(packetbytes);
37930    }
37931  }
37932
37933  return _util2.default.concat(arr);
37934};
37935
37936/**
37937 * Adds a packet to the list. This is the only supported method of doing so;
37938 * writing to packetlist[i] directly will result in an error.
37939 * @param {Object} packet Packet to push
37940 */
37941List.prototype.push = function (packet) {
37942  if (!packet) {
37943    return;
37944  }
37945
37946  packet.packets = packet.packets || new List();
37947
37948  this[this.length] = packet;
37949  this.length++;
37950};
37951
37952/**
37953 * Creates a new PacketList with all packets from the given types
37954 */
37955List.prototype.filterByTag = function (...args) {
37956  const filtered = new List();
37957
37958  const handle = tag => packetType => tag === packetType;
37959
37960  for (let i = 0; i < this.length; i++) {
37961    if (args.some(handle(this[i].tag))) {
37962      filtered.push(this[i]);
37963    }
37964  }
37965
37966  return filtered;
37967};
37968
37969/**
37970 * Traverses packet tree and returns first matching packet
37971 * @param  {module:enums.packet} type The packet type
37972 * @returns {module:packet/packet|undefined}
37973 */
37974List.prototype.findPacket = function (type) {
37975  return this.find(packet => packet.tag === type);
37976};
37977
37978/**
37979 * Returns array of found indices by tag
37980 */
37981List.prototype.indexOfTag = function (...args) {
37982  const tagIndex = [];
37983  const that = this;
37984
37985  const handle = tag => packetType => tag === packetType;
37986
37987  for (let i = 0; i < this.length; i++) {
37988    if (args.some(handle(that[i].tag))) {
37989      tagIndex.push(i);
37990    }
37991  }
37992  return tagIndex;
37993};
37994
37995/**
37996 * Concatenates packetlist or array of packets
37997 */
37998List.prototype.concat = function (packetlist) {
37999  if (packetlist) {
38000    for (let i = 0; i < packetlist.length; i++) {
38001      this.push(packetlist[i]);
38002    }
38003  }
38004  return this;
38005};
38006
38007/**
38008 * Allocate a new packetlist from structured packetlist clone
38009 * See {@link https://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data}
38010 * @param {Object} packetClone packetlist clone
38011 * @returns {Object} new packetlist object with data from packetlist clone
38012 */
38013List.fromStructuredClone = function (packetlistClone) {
38014  const packetlist = new List();
38015  for (let i = 0; i < packetlistClone.length; i++) {
38016    const packet = packets.fromStructuredClone(packetlistClone[i]);
38017    packetlist.push(packet);
38018    if (packet.embeddedSignature) {
38019      packet.embeddedSignature = packets.fromStructuredClone(packet.embeddedSignature);
38020    }
38021    if (packet.packets.length !== 0) {
38022      packet.packets = this.fromStructuredClone(packet.packets);
38023    } else {
38024      packet.packets = new List();
38025    }
38026  }
38027  if (packetlistClone.stream) {
38028    packetlist.stream = _webStreamTools2.default.transform(packetlistClone.stream, packet => packets.fromStructuredClone(packet));
38029  }
38030  return packetlist;
38031};
38032
38033exports.default = List;
38034
38035},{"../config":80,"../enums":114,"../util":153,"./all_packets":123,"./packet":130,"web-stream-tools":76}],132:[function(require,module,exports){
38036'use strict';
38037
38038Object.defineProperty(exports, "__esModule", {
38039  value: true
38040});
38041
38042var _sha = require('asmcrypto.js/dist_es5/hash/sha1/sha1');
38043
38044var _sha2 = require('asmcrypto.js/dist_es5/hash/sha256/sha256');
38045
38046var _keyid = require('../type/keyid');
38047
38048var _keyid2 = _interopRequireDefault(_keyid);
38049
38050var _mpi = require('../type/mpi');
38051
38052var _mpi2 = _interopRequireDefault(_mpi);
38053
38054var _config = require('../config');
38055
38056var _config2 = _interopRequireDefault(_config);
38057
38058var _crypto = require('../crypto');
38059
38060var _crypto2 = _interopRequireDefault(_crypto);
38061
38062var _enums = require('../enums');
38063
38064var _enums2 = _interopRequireDefault(_enums);
38065
38066var _util = require('../util');
38067
38068var _util2 = _interopRequireDefault(_util);
38069
38070function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
38071
38072/**
38073 * Implementation of the Key Material Packet (Tag 5,6,7,14)
38074 *
38075 * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:
38076 * A key material packet contains all the information about a public or
38077 * private key.  There are four variants of this packet type, and two
38078 * major versions.
38079 *
38080 * A Public-Key packet starts a series of packets that forms an OpenPGP
38081 * key (sometimes called an OpenPGP certificate).
38082 * @memberof module:packet
38083 * @constructor
38084 */
38085// GPG4Browsers - An OpenPGP implementation in javascript
38086// Copyright (C) 2011 Recurity Labs GmbH
38087//
38088// This library is free software; you can redistribute it and/or
38089// modify it under the terms of the GNU Lesser General Public
38090// License as published by the Free Software Foundation; either
38091// version 3.0 of the License, or (at your option) any later version.
38092//
38093// This library is distributed in the hope that it will be useful,
38094// but WITHOUT ANY WARRANTY; without even the implied warranty of
38095// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
38096// Lesser General Public License for more details.
38097//
38098// You should have received a copy of the GNU Lesser General Public
38099// License along with this library; if not, write to the Free Software
38100// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
38101
38102/**
38103 * @requires type/keyid
38104 * @requires type/mpi
38105 * @requires config
38106 * @requires crypto
38107 * @requires enums
38108 * @requires util
38109 */
38110
38111function PublicKey(date = new Date()) {
38112  /**
38113   * Packet type
38114   * @type {module:enums.packet}
38115   */
38116  this.tag = _enums2.default.packet.publicKey;
38117  /**
38118   * Packet version
38119   * @type {Integer}
38120   */
38121  this.version = _config2.default.aead_protect && _config2.default.aead_protect_version === 4 ? 5 : 4;
38122  /**
38123   * Key creation date.
38124   * @type {Date}
38125   */
38126  this.created = _util2.default.normalizeDate(date);
38127  /**
38128   * Public key algorithm.
38129   * @type {String}
38130   */
38131  this.algorithm = null;
38132  /**
38133   * Algorithm specific params
38134   * @type {Array<Object>}
38135   */
38136  this.params = [];
38137  /**
38138   * Time until expiration in days (V3 only)
38139   * @type {Integer}
38140   */
38141  this.expirationTimeV3 = 0;
38142  /**
38143   * Fingerprint in lowercase hex
38144   * @type {String}
38145   */
38146  this.fingerprint = null;
38147  /**
38148   * Keyid
38149   * @type {module:type/keyid}
38150   */
38151  this.keyid = null;
38152}
38153
38154/**
38155 * 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}
38156 * called by read_tag&lt;num&gt;
38157 * @param {Uint8Array} bytes Input array to read the packet from
38158 * @returns {Object} This object with attributes set by the parser
38159 */
38160PublicKey.prototype.read = function (bytes) {
38161  let pos = 0;
38162  // A one-octet version number (3, 4 or 5).
38163  this.version = bytes[pos++];
38164
38165  if (this.version === 4 || this.version === 5) {
38166    // - A four-octet number denoting the time that the key was created.
38167    this.created = _util2.default.readDate(bytes.subarray(pos, pos + 4));
38168    pos += 4;
38169
38170    // - A one-octet number denoting the public-key algorithm of this key.
38171    this.algorithm = _enums2.default.read(_enums2.default.publicKey, bytes[pos++]);
38172    const algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm);
38173
38174    if (this.version === 5) {
38175      // - A four-octet scalar octet count for the following key material.
38176      pos += 4;
38177    }
38178
38179    // - A series of values comprising the key material.  This is
38180    //   algorithm-specific and described in section XXXX.
38181    const types = _crypto2.default.getPubKeyParamTypes(algo);
38182    this.params = _crypto2.default.constructParams(types);
38183
38184    for (let i = 0; i < types.length && pos < bytes.length; i++) {
38185      pos += this.params[i].read(bytes.subarray(pos, bytes.length));
38186      if (pos > bytes.length) {
38187        throw new Error('Error reading MPI @:' + pos);
38188      }
38189    }
38190
38191    return pos;
38192  }
38193  throw new Error('Version ' + this.version + ' of the key packet is unsupported.');
38194};
38195
38196/**
38197 * Alias of read()
38198 * @see module:packet.PublicKey#read
38199 */
38200PublicKey.prototype.readPublicKey = PublicKey.prototype.read;
38201
38202/**
38203 * Same as write_private_key, but has less information because of
38204 * public key.
38205 * @returns {Uint8Array} OpenPGP packet body contents,
38206 */
38207PublicKey.prototype.write = function () {
38208  const arr = [];
38209  // Version
38210  arr.push(new Uint8Array([this.version]));
38211  arr.push(_util2.default.writeDate(this.created));
38212  // A one-octet number denoting the public-key algorithm of this key
38213  const algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm);
38214  arr.push(new Uint8Array([algo]));
38215
38216  const paramCount = _crypto2.default.getPubKeyParamTypes(algo).length;
38217  const params = _util2.default.concatUint8Array(this.params.slice(0, paramCount).map(param => param.write()));
38218  if (this.version === 5) {
38219    // A four-octet scalar octet count for the following key material
38220    arr.push(_util2.default.writeNumber(params.length, 4));
38221  }
38222  // Algorithm-specific params
38223  arr.push(params);
38224  return _util2.default.concatUint8Array(arr);
38225};
38226
38227/**
38228 * Alias of write()
38229 * @see module:packet.PublicKey#write
38230 */
38231PublicKey.prototype.writePublicKey = PublicKey.prototype.write;
38232
38233/**
38234 * Write an old version packet - it's used by some of the internal routines.
38235 */
38236PublicKey.prototype.writeOld = function () {
38237  const bytes = this.writePublicKey();
38238
38239  return _util2.default.concatUint8Array([new Uint8Array([0x99]), _util2.default.writeNumber(bytes.length, 2), bytes]);
38240};
38241
38242/**
38243 * Check whether secret-key data is available in decrypted form. Returns null for public keys.
38244 * @returns {Boolean|null}
38245 */
38246PublicKey.prototype.isDecrypted = function () {
38247  return null;
38248};
38249
38250/**
38251 * Returns the creation time of the key
38252 * @returns {Date}
38253 */
38254PublicKey.prototype.getCreationTime = function () {
38255  return this.created;
38256};
38257
38258/**
38259 * Calculates the key id of the key
38260 * @returns {String} A 8 byte key id
38261 */
38262PublicKey.prototype.getKeyId = function () {
38263  if (this.keyid) {
38264    return this.keyid;
38265  }
38266  this.keyid = new _keyid2.default();
38267  if (this.version === 5) {
38268    this.keyid.read(_util2.default.hex_to_Uint8Array(this.getFingerprint()).subarray(0, 8));
38269  } else if (this.version === 4) {
38270    this.keyid.read(_util2.default.hex_to_Uint8Array(this.getFingerprint()).subarray(12, 20));
38271  }
38272  return this.keyid;
38273};
38274
38275/**
38276 * Calculates the fingerprint of the key
38277 * @returns {Uint8Array} A Uint8Array containing the fingerprint
38278 */
38279PublicKey.prototype.getFingerprintBytes = function () {
38280  if (this.fingerprint) {
38281    return this.fingerprint;
38282  }
38283  let toHash;
38284  if (this.version === 5) {
38285    const bytes = this.writePublicKey();
38286    toHash = _util2.default.concatUint8Array([new Uint8Array([0x9A]), _util2.default.writeNumber(bytes.length, 4), bytes]);
38287    this.fingerprint = _sha2.Sha256.bytes(toHash);
38288  } else if (this.version === 4) {
38289    toHash = this.writeOld();
38290    this.fingerprint = _sha.Sha1.bytes(toHash);
38291  }
38292  return this.fingerprint;
38293};
38294
38295/**
38296 * Calculates the fingerprint of the key
38297 * @returns {String} A string containing the fingerprint in lowercase hex
38298 */
38299PublicKey.prototype.getFingerprint = function () {
38300  return _util2.default.Uint8Array_to_hex(this.getFingerprintBytes());
38301};
38302
38303/**
38304 * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint
38305 * @returns {Boolean} Whether the two keys have the same version and public key data
38306 */
38307PublicKey.prototype.hasSameFingerprintAs = function (other) {
38308  return this.version === other.version && _util2.default.equalsUint8Array(this.writePublicKey(), other.writePublicKey());
38309};
38310
38311/**
38312 * Returns algorithm information
38313 * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}
38314 */
38315PublicKey.prototype.getAlgorithmInfo = function () {
38316  const result = {};
38317  result.algorithm = this.algorithm;
38318  if (this.params[0] instanceof _mpi2.default) {
38319    result.bits = this.params[0].byteLength() * 8;
38320  } else {
38321    result.curve = this.params[0].getName();
38322  }
38323  return result;
38324};
38325
38326/**
38327 * Fix custom types after cloning
38328 */
38329PublicKey.prototype.postCloneTypeFix = function () {
38330  const algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm);
38331  const types = _crypto2.default.getPubKeyParamTypes(algo);
38332  for (let i = 0; i < types.length; i++) {
38333    const param = this.params[i];
38334    this.params[i] = types[i].fromClone(param);
38335  }
38336  if (this.keyid) {
38337    this.keyid = _keyid2.default.fromClone(this.keyid);
38338  }
38339};
38340
38341exports.default = PublicKey;
38342
38343},{"../config":80,"../crypto":95,"../enums":114,"../type/keyid":149,"../type/mpi":150,"../util":153,"asmcrypto.js/dist_es5/hash/sha1/sha1":12,"asmcrypto.js/dist_es5/hash/sha256/sha256":14}],133:[function(require,module,exports){
38344'use strict';
38345
38346Object.defineProperty(exports, "__esModule", {
38347  value: true
38348});
38349
38350var _keyid = require('../type/keyid');
38351
38352var _keyid2 = _interopRequireDefault(_keyid);
38353
38354var _mpi = require('../type/mpi');
38355
38356var _mpi2 = _interopRequireDefault(_mpi);
38357
38358var _crypto = require('../crypto');
38359
38360var _crypto2 = _interopRequireDefault(_crypto);
38361
38362var _enums = require('../enums');
38363
38364var _enums2 = _interopRequireDefault(_enums);
38365
38366var _util = require('../util');
38367
38368var _util2 = _interopRequireDefault(_util);
38369
38370function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
38371
38372/**
38373 * Public-Key Encrypted Session Key Packets (Tag 1)
38374 *
38375 * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:
38376 * A Public-Key Encrypted Session Key packet holds the session key
38377 * used to encrypt a message. Zero or more Public-Key Encrypted Session Key
38378 * packets and/or Symmetric-Key Encrypted Session Key packets may precede a
38379 * Symmetrically Encrypted Data Packet, which holds an encrypted message. The
38380 * message is encrypted with the session key, and the session key is itself
38381 * encrypted and stored in the Encrypted Session Key packet(s). The
38382 * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted
38383 * Session Key packet for each OpenPGP key to which the message is encrypted.
38384 * The recipient of the message finds a session key that is encrypted to their
38385 * public key, decrypts the session key, and then uses the session key to
38386 * decrypt the message.
38387 * @memberof module:packet
38388 * @constructor
38389 */
38390function PublicKeyEncryptedSessionKey() {
38391  this.tag = _enums2.default.packet.publicKeyEncryptedSessionKey;
38392  this.version = 3;
38393
38394  this.publicKeyId = new _keyid2.default();
38395  this.publicKeyAlgorithm = null;
38396
38397  this.sessionKey = null;
38398  this.sessionKeyAlgorithm = null;
38399
38400  /** @type {Array<module:type/mpi>} */
38401  this.encrypted = [];
38402}
38403
38404/**
38405 * Parsing function for a publickey encrypted session key packet (tag 1).
38406 *
38407 * @param {Uint8Array} input Payload of a tag 1 packet
38408 * @param {Integer} position Position to start reading from the input string
38409 * @param {Integer} len Length of the packet or the remaining length of
38410 *            input at position
38411 * @returns {module:packet.PublicKeyEncryptedSessionKey} Object representation
38412 */
38413// GPG4Browsers - An OpenPGP implementation in javascript
38414// Copyright (C) 2011 Recurity Labs GmbH
38415//
38416// This library is free software; you can redistribute it and/or
38417// modify it under the terms of the GNU Lesser General Public
38418// License as published by the Free Software Foundation; either
38419// version 3.0 of the License, or (at your option) any later version.
38420//
38421// This library is distributed in the hope that it will be useful,
38422// but WITHOUT ANY WARRANTY; without even the implied warranty of
38423// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
38424// Lesser General Public License for more details.
38425//
38426// You should have received a copy of the GNU Lesser General Public
38427// License along with this library; if not, write to the Free Software
38428// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
38429
38430/**
38431 * @requires type/keyid
38432 * @requires type/mpi
38433 * @requires crypto
38434 * @requires enums
38435 * @requires util
38436 */
38437
38438PublicKeyEncryptedSessionKey.prototype.read = function (bytes) {
38439  this.version = bytes[0];
38440  this.publicKeyId.read(bytes.subarray(1, bytes.length));
38441  this.publicKeyAlgorithm = _enums2.default.read(_enums2.default.publicKey, bytes[9]);
38442
38443  let i = 10;
38444
38445  const algo = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm);
38446  const types = _crypto2.default.getEncSessionKeyParamTypes(algo);
38447  this.encrypted = _crypto2.default.constructParams(types);
38448
38449  for (let j = 0; j < types.length; j++) {
38450    i += this.encrypted[j].read(bytes.subarray(i, bytes.length));
38451  }
38452};
38453
38454/**
38455 * Create a string representation of a tag 1 packet
38456 *
38457 * @returns {Uint8Array} The Uint8Array representation
38458 */
38459PublicKeyEncryptedSessionKey.prototype.write = function () {
38460  const arr = [new Uint8Array([this.version]), this.publicKeyId.write(), new Uint8Array([_enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm)])];
38461
38462  for (let i = 0; i < this.encrypted.length; i++) {
38463    arr.push(this.encrypted[i].write());
38464  }
38465
38466  return _util2.default.concatUint8Array(arr);
38467};
38468
38469/**
38470 * Encrypt session key packet
38471 * @param {module:packet.PublicKey} key Public key
38472 * @returns {Promise<Boolean>}
38473 * @async
38474 */
38475PublicKeyEncryptedSessionKey.prototype.encrypt = async function (key) {
38476  let data = String.fromCharCode(_enums2.default.write(_enums2.default.symmetric, this.sessionKeyAlgorithm));
38477
38478  data += _util2.default.Uint8Array_to_str(this.sessionKey);
38479  data += _util2.default.Uint8Array_to_str(_util2.default.write_checksum(this.sessionKey));
38480
38481  let toEncrypt;
38482  const algo = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm);
38483  if (algo === _enums2.default.publicKey.ecdh) {
38484    toEncrypt = new _mpi2.default(_crypto2.default.pkcs5.encode(data));
38485  } else {
38486    toEncrypt = new _mpi2.default((await _crypto2.default.pkcs1.eme.encode(data, key.params[0].byteLength())));
38487  }
38488
38489  this.encrypted = await _crypto2.default.publicKeyEncrypt(algo, key.params, toEncrypt, key.getFingerprintBytes());
38490  return true;
38491};
38492
38493/**
38494 * Decrypts the session key (only for public key encrypted session key
38495 * packets (tag 1)
38496 *
38497 * @param {module:packet.SecretKey} key
38498 *            Private key with secret params unlocked
38499 * @returns {Promise<Boolean>}
38500 * @async
38501 */
38502PublicKeyEncryptedSessionKey.prototype.decrypt = async function (key) {
38503  const algo = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm);
38504  const result = new _mpi2.default((await _crypto2.default.publicKeyDecrypt(algo, key.params, this.encrypted, key.getFingerprintBytes())));
38505
38506  let checksum;
38507  let decoded;
38508  if (algo === _enums2.default.publicKey.ecdh) {
38509    decoded = _crypto2.default.pkcs5.decode(result.toString());
38510    checksum = _util2.default.str_to_Uint8Array(decoded.substr(decoded.length - 2));
38511  } else {
38512    decoded = _crypto2.default.pkcs1.eme.decode(result.toString());
38513    checksum = result.toUint8Array().slice(result.byteLength() - 2);
38514  }
38515
38516  key = _util2.default.str_to_Uint8Array(decoded.substring(1, decoded.length - 2));
38517
38518  if (!_util2.default.equalsUint8Array(checksum, _util2.default.write_checksum(key))) {
38519    throw new Error('Decryption error');
38520  } else {
38521    this.sessionKey = key;
38522    this.sessionKeyAlgorithm = _enums2.default.read(_enums2.default.symmetric, decoded.charCodeAt(0));
38523  }
38524  return true;
38525};
38526
38527/**
38528 * Fix custom types after cloning
38529 */
38530PublicKeyEncryptedSessionKey.prototype.postCloneTypeFix = function () {
38531  this.publicKeyId = _keyid2.default.fromClone(this.publicKeyId);
38532  const algo = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm);
38533  const types = _crypto2.default.getEncSessionKeyParamTypes(algo);
38534  for (let i = 0; i < this.encrypted.length; i++) {
38535    this.encrypted[i] = types[i].fromClone(this.encrypted[i]);
38536  }
38537};
38538
38539exports.default = PublicKeyEncryptedSessionKey;
38540
38541},{"../crypto":95,"../enums":114,"../type/keyid":149,"../type/mpi":150,"../util":153}],134:[function(require,module,exports){
38542'use strict';
38543
38544Object.defineProperty(exports, "__esModule", {
38545  value: true
38546});
38547
38548var _public_key = require('./public_key');
38549
38550var _public_key2 = _interopRequireDefault(_public_key);
38551
38552var _enums = require('../enums');
38553
38554var _enums2 = _interopRequireDefault(_enums);
38555
38556function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
38557
38558/**
38559 * A Public-Subkey packet (tag 14) has exactly the same format as a
38560 * Public-Key packet, but denotes a subkey.  One or more subkeys may be
38561 * associated with a top-level key.  By convention, the top-level key
38562 * provides signature services, and the subkeys provide encryption
38563 * services.
38564 * @memberof module:packet
38565 * @constructor
38566 * @extends module:packet.PublicKey
38567 */
38568// GPG4Browsers - An OpenPGP implementation in javascript
38569// Copyright (C) 2011 Recurity Labs GmbH
38570//
38571// This library is free software; you can redistribute it and/or
38572// modify it under the terms of the GNU Lesser General Public
38573// License as published by the Free Software Foundation; either
38574// version 3.0 of the License, or (at your option) any later version.
38575//
38576// This library is distributed in the hope that it will be useful,
38577// but WITHOUT ANY WARRANTY; without even the implied warranty of
38578// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
38579// Lesser General Public License for more details.
38580//
38581// You should have received a copy of the GNU Lesser General Public
38582// License along with this library; if not, write to the Free Software
38583// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
38584
38585/**
38586 * @requires packet/public_key
38587 * @requires enums
38588 */
38589
38590function PublicSubkey() {
38591  _public_key2.default.call(this);
38592  this.tag = _enums2.default.packet.publicSubkey;
38593}
38594
38595PublicSubkey.prototype = new _public_key2.default();
38596PublicSubkey.prototype.constructor = PublicSubkey;
38597
38598exports.default = PublicSubkey;
38599
38600},{"../enums":114,"./public_key":132}],135:[function(require,module,exports){
38601'use strict';
38602
38603Object.defineProperty(exports, "__esModule", {
38604  value: true
38605});
38606
38607var _public_key = require('./public_key');
38608
38609var _public_key2 = _interopRequireDefault(_public_key);
38610
38611var _keyid = require('../type/keyid.js');
38612
38613var _keyid2 = _interopRequireDefault(_keyid);
38614
38615var _s2k = require('../type/s2k');
38616
38617var _s2k2 = _interopRequireDefault(_s2k);
38618
38619var _crypto = require('../crypto');
38620
38621var _crypto2 = _interopRequireDefault(_crypto);
38622
38623var _enums = require('../enums');
38624
38625var _enums2 = _interopRequireDefault(_enums);
38626
38627var _util = require('../util');
38628
38629var _util2 = _interopRequireDefault(_util);
38630
38631function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
38632
38633/**
38634 * A Secret-Key packet contains all the information that is found in a
38635 * Public-Key packet, including the public-key material, but also
38636 * includes the secret-key material after all the public-key fields.
38637 * @memberof module:packet
38638 * @constructor
38639 * @extends module:packet.PublicKey
38640 */
38641// GPG4Browsers - An OpenPGP implementation in javascript
38642// Copyright (C) 2011 Recurity Labs GmbH
38643//
38644// This library is free software; you can redistribute it and/or
38645// modify it under the terms of the GNU Lesser General Public
38646// License as published by the Free Software Foundation; either
38647// version 3.0 of the License, or (at your option) any later version.
38648//
38649// This library is distributed in the hope that it will be useful,
38650// but WITHOUT ANY WARRANTY; without even the implied warranty of
38651// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
38652// Lesser General Public License for more details.
38653//
38654// You should have received a copy of the GNU Lesser General Public
38655// License along with this library; if not, write to the Free Software
38656// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
38657
38658/**
38659 * @requires packet/public_key
38660 * @requires type/keyid
38661 * @requires type/s2k
38662 * @requires crypto
38663 * @requires enums
38664 * @requires util
38665 */
38666
38667function SecretKey(date = new Date()) {
38668  _public_key2.default.call(this, date);
38669  /**
38670   * Packet type
38671   * @type {module:enums.packet}
38672   */
38673  this.tag = _enums2.default.packet.secretKey;
38674  /**
38675   * Encrypted secret-key data
38676   */
38677  this.encrypted = null;
38678  /**
38679   * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.
38680   */
38681  this.isEncrypted = null;
38682}
38683
38684SecretKey.prototype = new _public_key2.default();
38685SecretKey.prototype.constructor = SecretKey;
38686
38687// Helper function
38688
38689function parse_cleartext_params(cleartext, algorithm) {
38690  const algo = _enums2.default.write(_enums2.default.publicKey, algorithm);
38691  const types = _crypto2.default.getPrivKeyParamTypes(algo);
38692  const params = _crypto2.default.constructParams(types);
38693  let p = 0;
38694
38695  for (let i = 0; i < types.length && p < cleartext.length; i++) {
38696    p += params[i].read(cleartext.subarray(p, cleartext.length));
38697    if (p > cleartext.length) {
38698      throw new Error('Error reading param @:' + p);
38699    }
38700  }
38701
38702  return params;
38703}
38704
38705function write_cleartext_params(params, algorithm) {
38706  const arr = [];
38707  const algo = _enums2.default.write(_enums2.default.publicKey, algorithm);
38708  const numPublicParams = _crypto2.default.getPubKeyParamTypes(algo).length;
38709
38710  for (let i = numPublicParams; i < params.length; i++) {
38711    arr.push(params[i].write());
38712  }
38713
38714  return _util2.default.concatUint8Array(arr);
38715}
38716
38717// 5.5.3.  Secret-Key Packet Formats
38718
38719/**
38720 * Internal parser for private keys as specified in
38721 * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}
38722 * @param {String} bytes Input string to read the packet from
38723 */
38724SecretKey.prototype.read = function (bytes) {
38725  // - A Public-Key or Public-Subkey packet, as described above.
38726  const len = this.readPublicKey(bytes);
38727
38728  bytes = bytes.subarray(len, bytes.length);
38729
38730  // - One octet indicating string-to-key usage conventions.  Zero
38731  //   indicates that the secret-key data is not encrypted.  255 or 254
38732  //   indicates that a string-to-key specifier is being given.  Any
38733  //   other value is a symmetric-key encryption algorithm identifier.
38734  const isEncrypted = bytes[0];
38735
38736  if (isEncrypted) {
38737    this.encrypted = bytes;
38738    this.isEncrypted = true;
38739  } else {
38740    // - Plain or encrypted multiprecision integers comprising the secret
38741    //   key data.  These algorithm-specific fields are as described
38742    //   below.
38743    const cleartext = bytes.subarray(1, -2);
38744    if (!_util2.default.equalsUint8Array(_util2.default.write_checksum(cleartext), bytes.subarray(-2))) {
38745      throw new Error('Key checksum mismatch');
38746    }
38747    const privParams = parse_cleartext_params(cleartext, this.algorithm);
38748    this.params = this.params.concat(privParams);
38749    this.isEncrypted = false;
38750  }
38751};
38752
38753/**
38754 * Creates an OpenPGP key packet for the given key.
38755 * @returns {String} A string of bytes containing the secret key OpenPGP packet
38756 */
38757SecretKey.prototype.write = function () {
38758  const arr = [this.writePublicKey()];
38759
38760  if (!this.encrypted) {
38761    arr.push(new Uint8Array([0]));
38762    const cleartextParams = write_cleartext_params(this.params, this.algorithm);
38763    arr.push(cleartextParams);
38764    arr.push(_util2.default.write_checksum(cleartextParams));
38765  } else {
38766    arr.push(this.encrypted);
38767  }
38768
38769  return _util2.default.concatUint8Array(arr);
38770};
38771
38772/**
38773 * Check whether secret-key data is available in decrypted form. Returns null for public keys.
38774 * @returns {Boolean|null}
38775 */
38776SecretKey.prototype.isDecrypted = function () {
38777  return this.isEncrypted === false;
38778};
38779
38780/**
38781 * Encrypt the payload. By default, we use aes256 and iterated, salted string
38782 * to key specifier. If the key is in a decrypted state (isEncrypted === false)
38783 * and the passphrase is empty or undefined, the key will be set as not encrypted.
38784 * This can be used to remove passphrase protection after calling decrypt().
38785 * @param {String} passphrase
38786 * @returns {Promise<Boolean>}
38787 * @async
38788 */
38789SecretKey.prototype.encrypt = async function (passphrase) {
38790  if (this.isDecrypted() && this.encrypted) {
38791    // gnu-dummy
38792    this.isEncrypted = true;
38793    return false;
38794  }
38795
38796  if (this.isDecrypted() && !passphrase) {
38797    this.encrypted = null;
38798    return false;
38799  } else if (!passphrase) {
38800    throw new Error('The key must be decrypted before removing passphrase protection.');
38801  }
38802
38803  const s2k = new _s2k2.default();
38804  s2k.salt = await _crypto2.default.random.getRandomBytes(8);
38805  const symmetric = 'aes256';
38806  const cleartext = write_cleartext_params(this.params, this.algorithm);
38807  const key = await produceEncryptionKey(s2k, passphrase, symmetric);
38808  const blockLen = _crypto2.default.cipher[symmetric].blockSize;
38809  const iv = await _crypto2.default.random.getRandomBytes(blockLen);
38810
38811  let arr;
38812
38813  if (this.version === 5) {
38814    const aead = 'eax';
38815    const optionalFields = _util2.default.concatUint8Array([new Uint8Array([_enums2.default.write(_enums2.default.symmetric, symmetric), _enums2.default.write(_enums2.default.aead, aead)]), s2k.write(), iv]);
38816    arr = [new Uint8Array([253, optionalFields.length])];
38817    arr.push(optionalFields);
38818    const mode = _crypto2.default[aead];
38819    const modeInstance = await mode(symmetric, key);
38820    const encrypted = await modeInstance.encrypt(cleartext, iv.subarray(0, mode.ivLength), new Uint8Array());
38821    arr.push(_util2.default.writeNumber(encrypted.length, 4));
38822    arr.push(encrypted);
38823  } else {
38824    arr = [new Uint8Array([254, _enums2.default.write(_enums2.default.symmetric, symmetric)])];
38825    arr.push(s2k.write());
38826    arr.push(iv);
38827    arr.push(_crypto2.default.cfb.encrypt(symmetric, key, _util2.default.concatUint8Array([cleartext, await _crypto2.default.hash.sha1(cleartext)]), iv));
38828  }
38829
38830  this.encrypted = _util2.default.concatUint8Array(arr);
38831  return true;
38832};
38833
38834async function produceEncryptionKey(s2k, passphrase, algorithm) {
38835  return s2k.produce_key(passphrase, _crypto2.default.cipher[algorithm].keySize);
38836}
38837
38838/**
38839 * Decrypts the private key params which are needed to use the key.
38840 * {@link module:packet.SecretKey.isDecrypted} should be false, as
38841 * otherwise calls to this function will throw an error.
38842 * @param {String} passphrase The passphrase for this private key as string
38843 * @returns {Promise<Boolean>}
38844 * @async
38845 */
38846SecretKey.prototype.decrypt = async function (passphrase) {
38847  if (this.isDecrypted()) {
38848    throw new Error('Key packet is already decrypted.');
38849  }
38850
38851  let i = 0;
38852  let symmetric;
38853  let aead;
38854  let key;
38855
38856  const s2k_usage = this.encrypted[i++];
38857
38858  // - Only for a version 5 packet, a one-octet scalar octet count of
38859  //   the next 4 optional fields.
38860  if (this.version === 5) {
38861    i++;
38862  }
38863
38864  // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
38865  //   one-octet symmetric encryption algorithm.
38866  if (s2k_usage === 255 || s2k_usage === 254 || s2k_usage === 253) {
38867    symmetric = this.encrypted[i++];
38868    symmetric = _enums2.default.read(_enums2.default.symmetric, symmetric);
38869
38870    // - [Optional] If string-to-key usage octet was 253, a one-octet
38871    //   AEAD algorithm.
38872    if (s2k_usage === 253) {
38873      aead = this.encrypted[i++];
38874      aead = _enums2.default.read(_enums2.default.aead, aead);
38875    }
38876
38877    // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
38878    //   string-to-key specifier.  The length of the string-to-key
38879    //   specifier is implied by its type, as described above.
38880    const s2k = new _s2k2.default();
38881    i += s2k.read(this.encrypted.subarray(i, this.encrypted.length));
38882
38883    if (s2k.type === 'gnu-dummy') {
38884      this.isEncrypted = false;
38885      return false;
38886    }
38887    key = await produceEncryptionKey(s2k, passphrase, symmetric);
38888  } else {
38889    symmetric = s2k_usage;
38890    symmetric = _enums2.default.read(_enums2.default.symmetric, symmetric);
38891    key = await _crypto2.default.hash.md5(passphrase);
38892  }
38893
38894  // - [Optional] If secret data is encrypted (string-to-key usage octet
38895  //   not zero), an Initial Vector (IV) of the same length as the
38896  //   cipher's block size.
38897  const iv = this.encrypted.subarray(i, i + _crypto2.default.cipher[symmetric].blockSize);
38898
38899  i += iv.length;
38900
38901  // - Only for a version 5 packet, a four-octet scalar octet count for
38902  //   the following key material.
38903  if (this.version === 5) {
38904    i += 4;
38905  }
38906
38907  const ciphertext = this.encrypted.subarray(i, this.encrypted.length);
38908  let cleartext;
38909  if (aead) {
38910    const mode = _crypto2.default[aead];
38911    try {
38912      const modeInstance = await mode(symmetric, key);
38913      cleartext = await modeInstance.decrypt(ciphertext, iv.subarray(0, mode.ivLength), new Uint8Array());
38914    } catch (err) {
38915      if (err.message === 'Authentication tag mismatch') {
38916        throw new Error('Incorrect key passphrase: ' + err.message);
38917      }
38918    }
38919  } else {
38920    const cleartextWithHash = await _crypto2.default.cfb.decrypt(symmetric, key, ciphertext, iv);
38921
38922    let hash;
38923    let hashlen;
38924    if (s2k_usage === 255) {
38925      hashlen = 2;
38926      cleartext = cleartextWithHash.subarray(0, -hashlen);
38927      hash = _util2.default.write_checksum(cleartext);
38928    } else {
38929      hashlen = 20;
38930      cleartext = cleartextWithHash.subarray(0, -hashlen);
38931      hash = await _crypto2.default.hash.sha1(cleartext);
38932    }
38933
38934    if (!_util2.default.equalsUint8Array(hash, cleartextWithHash.subarray(-hashlen))) {
38935      throw new Error('Incorrect key passphrase');
38936    }
38937  }
38938
38939  const privParams = parse_cleartext_params(cleartext, this.algorithm);
38940  this.params = this.params.concat(privParams);
38941  this.isEncrypted = false;
38942  this.encrypted = null;
38943
38944  return true;
38945};
38946
38947SecretKey.prototype.generate = async function (bits, curve) {
38948  const algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm);
38949  this.params = await _crypto2.default.generateParams(algo, bits, curve);
38950  this.isEncrypted = false;
38951};
38952
38953/**
38954 * Clear private params, return to initial state
38955 */
38956SecretKey.prototype.clearPrivateParams = function () {
38957  if (!this.encrypted) {
38958    throw new Error('If secret key is not encrypted, clearing private params is irreversible.');
38959  }
38960  const algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm);
38961  this.params = this.params.slice(0, _crypto2.default.getPubKeyParamTypes(algo).length);
38962  this.isEncrypted = true;
38963};
38964
38965/**
38966 * Fix custom types after cloning
38967 */
38968SecretKey.prototype.postCloneTypeFix = function () {
38969  const algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm);
38970  const types = [].concat(_crypto2.default.getPubKeyParamTypes(algo), _crypto2.default.getPrivKeyParamTypes(algo));
38971  for (let i = 0; i < this.params.length; i++) {
38972    const param = this.params[i];
38973    this.params[i] = types[i].fromClone(param);
38974  }
38975  if (this.keyid) {
38976    this.keyid = _keyid2.default.fromClone(this.keyid);
38977  }
38978};
38979
38980exports.default = SecretKey;
38981
38982},{"../crypto":95,"../enums":114,"../type/keyid.js":149,"../type/s2k":152,"../util":153,"./public_key":132}],136:[function(require,module,exports){
38983'use strict';
38984
38985Object.defineProperty(exports, "__esModule", {
38986  value: true
38987});
38988
38989var _secret_key = require('./secret_key');
38990
38991var _secret_key2 = _interopRequireDefault(_secret_key);
38992
38993var _enums = require('../enums');
38994
38995var _enums2 = _interopRequireDefault(_enums);
38996
38997function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
38998
38999/**
39000 * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret
39001 * Key packet and has exactly the same format.
39002 * @memberof module:packet
39003 * @constructor
39004 * @extends module:packet.SecretKey
39005 */
39006// GPG4Browsers - An OpenPGP implementation in javascript
39007// Copyright (C) 2011 Recurity Labs GmbH
39008//
39009// This library is free software; you can redistribute it and/or
39010// modify it under the terms of the GNU Lesser General Public
39011// License as published by the Free Software Foundation; either
39012// version 3.0 of the License, or (at your option) any later version.
39013//
39014// This library is distributed in the hope that it will be useful,
39015// but WITHOUT ANY WARRANTY; without even the implied warranty of
39016// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
39017// Lesser General Public License for more details.
39018//
39019// You should have received a copy of the GNU Lesser General Public
39020// License along with this library; if not, write to the Free Software
39021// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
39022
39023/**
39024 * @requires packet/secret_key
39025 * @requires enums
39026 */
39027
39028function SecretSubkey(date = new Date()) {
39029  _secret_key2.default.call(this, date);
39030  this.tag = _enums2.default.packet.secretSubkey;
39031}
39032
39033SecretSubkey.prototype = new _secret_key2.default();
39034SecretSubkey.prototype.constructor = SecretSubkey;
39035
39036exports.default = SecretSubkey;
39037
39038},{"../enums":114,"./secret_key":135}],137:[function(require,module,exports){
39039'use strict';
39040
39041Object.defineProperty(exports, "__esModule", {
39042  value: true
39043});
39044
39045var _webStreamTools = require('web-stream-tools');
39046
39047var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
39048
39049var _packet = require('./packet');
39050
39051var _packet2 = _interopRequireDefault(_packet);
39052
39053var _keyid = require('../type/keyid.js');
39054
39055var _keyid2 = _interopRequireDefault(_keyid);
39056
39057var _mpi = require('../type/mpi.js');
39058
39059var _mpi2 = _interopRequireDefault(_mpi);
39060
39061var _crypto = require('../crypto');
39062
39063var _crypto2 = _interopRequireDefault(_crypto);
39064
39065var _enums = require('../enums');
39066
39067var _enums2 = _interopRequireDefault(_enums);
39068
39069var _util = require('../util');
39070
39071var _util2 = _interopRequireDefault(_util);
39072
39073function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
39074
39075/**
39076 * Implementation of the Signature Packet (Tag 2)
39077 *
39078 * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:
39079 * A Signature packet describes a binding between some public key and
39080 * some data.  The most common signatures are a signature of a file or a
39081 * block of text, and a signature that is a certification of a User ID.
39082 * @memberof module:packet
39083 * @constructor
39084 * @param {Date} date the creation date of the signature
39085 */
39086function Signature(date = new Date()) {
39087  this.tag = _enums2.default.packet.signature;
39088  this.version = 4;
39089  this.signatureType = null;
39090  this.hashAlgorithm = null;
39091  this.publicKeyAlgorithm = null;
39092
39093  this.signatureData = null;
39094  this.unhashedSubpackets = [];
39095  this.signedHashValue = null;
39096
39097  this.created = _util2.default.normalizeDate(date);
39098  this.signatureExpirationTime = null;
39099  this.signatureNeverExpires = true;
39100  this.exportable = null;
39101  this.trustLevel = null;
39102  this.trustAmount = null;
39103  this.regularExpression = null;
39104  this.revocable = null;
39105  this.keyExpirationTime = null;
39106  this.keyNeverExpires = null;
39107  this.preferredSymmetricAlgorithms = null;
39108  this.revocationKeyClass = null;
39109  this.revocationKeyAlgorithm = null;
39110  this.revocationKeyFingerprint = null;
39111  this.issuerKeyId = new _keyid2.default();
39112  this.notations = [];
39113  this.preferredHashAlgorithms = null;
39114  this.preferredCompressionAlgorithms = null;
39115  this.keyServerPreferences = null;
39116  this.preferredKeyServer = null;
39117  this.isPrimaryUserID = null;
39118  this.policyURI = null;
39119  this.keyFlags = null;
39120  this.signersUserId = null;
39121  this.reasonForRevocationFlag = null;
39122  this.reasonForRevocationString = null;
39123  this.features = null;
39124  this.signatureTargetPublicKeyAlgorithm = null;
39125  this.signatureTargetHashAlgorithm = null;
39126  this.signatureTargetHash = null;
39127  this.embeddedSignature = null;
39128  this.issuerKeyVersion = null;
39129  this.issuerFingerprint = null;
39130  this.preferredAeadAlgorithms = null;
39131
39132  this.verified = null;
39133  this.revoked = null;
39134}
39135
39136/**
39137 * parsing function for a signature packet (tag 2).
39138 * @param {String} bytes payload of a tag 2 packet
39139 * @param {Integer} position position to start reading from the bytes string
39140 * @param {Integer} len length of the packet or the remaining length of bytes at position
39141 * @returns {module:packet.Signature} object representation
39142 */
39143// GPG4Browsers - An OpenPGP implementation in javascript
39144// Copyright (C) 2011 Recurity Labs GmbH
39145//
39146// This library is free software; you can redistribute it and/or
39147// modify it under the terms of the GNU Lesser General Public
39148// License as published by the Free Software Foundation; either
39149// version 3.0 of the License, or (at your option) any later version.
39150//
39151// This library is distributed in the hope that it will be useful,
39152// but WITHOUT ANY WARRANTY; without even the implied warranty of
39153// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
39154// Lesser General Public License for more details.
39155//
39156// You should have received a copy of the GNU Lesser General Public
39157// License along with this library; if not, write to the Free Software
39158// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
39159
39160/**
39161 * @requires web-stream-tools
39162 * @requires packet/packet
39163 * @requires type/keyid
39164 * @requires type/mpi
39165 * @requires crypto
39166 * @requires enums
39167 * @requires util
39168 */
39169
39170Signature.prototype.read = function (bytes) {
39171  let i = 0;
39172  this.version = bytes[i++];
39173
39174  if (this.version !== 4) {
39175    throw new Error('Version ' + this.version + ' of the signature is unsupported.');
39176  }
39177
39178  this.signatureType = bytes[i++];
39179  this.publicKeyAlgorithm = bytes[i++];
39180  this.hashAlgorithm = bytes[i++];
39181
39182  // hashed subpackets
39183  i += this.read_sub_packets(bytes.subarray(i, bytes.length), true);
39184
39185  // A V4 signature hashes the packet body
39186  // starting from its first field, the version number, through the end
39187  // of the hashed subpacket data.  Thus, the fields hashed are the
39188  // signature version, the signature type, the public-key algorithm, the
39189  // hash algorithm, the hashed subpacket length, and the hashed
39190  // subpacket body.
39191  this.signatureData = bytes.subarray(0, i);
39192
39193  // unhashed subpackets
39194  i += this.read_sub_packets(bytes.subarray(i, bytes.length), false);
39195
39196  // Two-octet field holding left 16 bits of signed hash value.
39197  this.signedHashValue = bytes.subarray(i, i + 2);
39198  i += 2;
39199
39200  this.signature = bytes.subarray(i, bytes.length);
39201};
39202
39203Signature.prototype.write = function () {
39204  const arr = [];
39205  arr.push(this.signatureData);
39206  arr.push(this.write_unhashed_sub_packets());
39207  arr.push(this.signedHashValue);
39208  arr.push(_webStreamTools2.default.clone(this.signature));
39209  return _util2.default.concat(arr);
39210};
39211
39212/**
39213 * Signs provided data. This needs to be done prior to serialization.
39214 * @param {module:packet.SecretKey} key private key used to sign the message.
39215 * @param {Object} data Contains packets to be signed.
39216 * @returns {Promise<Boolean>}
39217 * @async
39218 */
39219Signature.prototype.sign = async function (key, data) {
39220  const signatureType = _enums2.default.write(_enums2.default.signature, this.signatureType);
39221  const publicKeyAlgorithm = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm);
39222  const hashAlgorithm = _enums2.default.write(_enums2.default.hash, this.hashAlgorithm);
39223
39224  const arr = [new Uint8Array([4, signatureType, publicKeyAlgorithm, hashAlgorithm])];
39225
39226  if (key.version === 5) {
39227    // We could also generate this subpacket for version 4 keys, but for
39228    // now we don't.
39229    this.issuerKeyVersion = key.version;
39230    this.issuerFingerprint = key.getFingerprintBytes();
39231  }
39232
39233  this.issuerKeyId = key.getKeyId();
39234
39235  // Add hashed subpackets
39236  arr.push(this.write_hashed_sub_packets());
39237
39238  this.signatureData = _util2.default.concat(arr);
39239
39240  const toHash = this.toHash(signatureType, data);
39241  const hash = await this.hash(signatureType, data, toHash);
39242
39243  this.signedHashValue = _webStreamTools2.default.slice(_webStreamTools2.default.clone(hash), 0, 2);
39244
39245  const params = key.params;
39246  this.signature = _webStreamTools2.default.fromAsync(async () => _crypto2.default.signature.sign(publicKeyAlgorithm, hashAlgorithm, params, toHash, (await _webStreamTools2.default.readToEnd(hash))));
39247
39248  // Store the fact that this signature is valid, e.g. for when we call `await
39249  // getLatestValidSignature(this.revocationSignatures, key, data)` later. Note
39250  // that this only holds up if the key and data passed to verify are the same
39251  // as the ones passed to sign.
39252  this.verified = true;
39253  return true;
39254};
39255
39256/**
39257 * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets
39258 * @returns {Uint8Array} subpacket data
39259 */
39260Signature.prototype.write_hashed_sub_packets = function () {
39261  const sub = _enums2.default.signatureSubpacket;
39262  const arr = [];
39263  let bytes;
39264  if (this.created !== null) {
39265    arr.push(write_sub_packet(sub.signature_creation_time, _util2.default.writeDate(this.created)));
39266  }
39267  if (this.signatureExpirationTime !== null) {
39268    arr.push(write_sub_packet(sub.signature_expiration_time, _util2.default.writeNumber(this.signatureExpirationTime, 4)));
39269  }
39270  if (this.exportable !== null) {
39271    arr.push(write_sub_packet(sub.exportable_certification, new Uint8Array([this.exportable ? 1 : 0])));
39272  }
39273  if (this.trustLevel !== null) {
39274    bytes = new Uint8Array([this.trustLevel, this.trustAmount]);
39275    arr.push(write_sub_packet(sub.trust_signature, bytes));
39276  }
39277  if (this.regularExpression !== null) {
39278    arr.push(write_sub_packet(sub.regular_expression, this.regularExpression));
39279  }
39280  if (this.revocable !== null) {
39281    arr.push(write_sub_packet(sub.revocable, new Uint8Array([this.revocable ? 1 : 0])));
39282  }
39283  if (this.keyExpirationTime !== null) {
39284    arr.push(write_sub_packet(sub.key_expiration_time, _util2.default.writeNumber(this.keyExpirationTime, 4)));
39285  }
39286  if (this.preferredSymmetricAlgorithms !== null) {
39287    bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.preferredSymmetricAlgorithms));
39288    arr.push(write_sub_packet(sub.preferred_symmetric_algorithms, bytes));
39289  }
39290  if (this.revocationKeyClass !== null) {
39291    bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);
39292    bytes = _util2.default.concat([bytes, this.revocationKeyFingerprint]);
39293    arr.push(write_sub_packet(sub.revocation_key, bytes));
39294  }
39295  this.notations.forEach(([name, value]) => {
39296    bytes = [new Uint8Array([0x80, 0, 0, 0])];
39297    // 2 octets of name length
39298    bytes.push(_util2.default.writeNumber(name.length, 2));
39299    // 2 octets of value length
39300    bytes.push(_util2.default.writeNumber(value.length, 2));
39301    bytes.push(_util2.default.str_to_Uint8Array(name + value));
39302    bytes = _util2.default.concat(bytes);
39303    arr.push(write_sub_packet(sub.notation_data, bytes));
39304  });
39305  if (this.preferredHashAlgorithms !== null) {
39306    bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.preferredHashAlgorithms));
39307    arr.push(write_sub_packet(sub.preferred_hash_algorithms, bytes));
39308  }
39309  if (this.preferredCompressionAlgorithms !== null) {
39310    bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.preferredCompressionAlgorithms));
39311    arr.push(write_sub_packet(sub.preferred_compression_algorithms, bytes));
39312  }
39313  if (this.keyServerPreferences !== null) {
39314    bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.keyServerPreferences));
39315    arr.push(write_sub_packet(sub.key_server_preferences, bytes));
39316  }
39317  if (this.preferredKeyServer !== null) {
39318    arr.push(write_sub_packet(sub.preferred_key_server, _util2.default.str_to_Uint8Array(this.preferredKeyServer)));
39319  }
39320  if (this.isPrimaryUserID !== null) {
39321    arr.push(write_sub_packet(sub.primary_user_id, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));
39322  }
39323  if (this.policyURI !== null) {
39324    arr.push(write_sub_packet(sub.policy_uri, _util2.default.str_to_Uint8Array(this.policyURI)));
39325  }
39326  if (this.keyFlags !== null) {
39327    bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.keyFlags));
39328    arr.push(write_sub_packet(sub.key_flags, bytes));
39329  }
39330  if (this.signersUserId !== null) {
39331    arr.push(write_sub_packet(sub.signers_user_id, _util2.default.str_to_Uint8Array(this.signersUserId)));
39332  }
39333  if (this.reasonForRevocationFlag !== null) {
39334    bytes = _util2.default.str_to_Uint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);
39335    arr.push(write_sub_packet(sub.reason_for_revocation, bytes));
39336  }
39337  if (this.features !== null) {
39338    bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.features));
39339    arr.push(write_sub_packet(sub.features, bytes));
39340  }
39341  if (this.signatureTargetPublicKeyAlgorithm !== null) {
39342    bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];
39343    bytes.push(_util2.default.str_to_Uint8Array(this.signatureTargetHash));
39344    bytes = _util2.default.concat(bytes);
39345    arr.push(write_sub_packet(sub.signature_target, bytes));
39346  }
39347  if (this.preferredAeadAlgorithms !== null) {
39348    bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.preferredAeadAlgorithms));
39349    arr.push(write_sub_packet(sub.preferred_aead_algorithms, bytes));
39350  }
39351
39352  const result = _util2.default.concat(arr);
39353  const length = _util2.default.writeNumber(result.length, 2);
39354
39355  return _util2.default.concat([length, result]);
39356};
39357
39358/**
39359 * Creates Uint8Array of bytes of Issuer and Embedded Signature subpackets
39360 * @returns {Uint8Array} subpacket data
39361 */
39362Signature.prototype.write_unhashed_sub_packets = function () {
39363  const sub = _enums2.default.signatureSubpacket;
39364  const arr = [];
39365  let bytes;
39366  if (!this.issuerKeyId.isNull() && this.issuerKeyVersion !== 5) {
39367    // If the version of [the] key is greater than 4, this subpacket
39368    // MUST NOT be included in the signature.
39369    arr.push(write_sub_packet(sub.issuer, this.issuerKeyId.write()));
39370  }
39371  if (this.embeddedSignature !== null) {
39372    arr.push(write_sub_packet(sub.embedded_signature, this.embeddedSignature.write()));
39373  }
39374  if (this.issuerFingerprint !== null) {
39375    bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];
39376    bytes = _util2.default.concat(bytes);
39377    arr.push(write_sub_packet(sub.issuer_fingerprint, bytes));
39378  }
39379  this.unhashedSubpackets.forEach(data => {
39380    arr.push(_packet2.default.writeSimpleLength(data.length));
39381    arr.push(data);
39382  });
39383
39384  const result = _util2.default.concat(arr);
39385  const length = _util2.default.writeNumber(result.length, 2);
39386
39387  return _util2.default.concat([length, result]);
39388};
39389
39390/**
39391 * Creates a string representation of a sub signature packet
39392 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}
39393 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}
39394 * @param {Integer} type subpacket signature type.
39395 * @param {String} data data to be included
39396 * @returns {String} a string-representation of a sub signature packet
39397 * @private
39398 */
39399function write_sub_packet(type, data) {
39400  const arr = [];
39401  arr.push(_packet2.default.writeSimpleLength(data.length + 1));
39402  arr.push(new Uint8Array([type]));
39403  arr.push(data);
39404  return _util2.default.concat(arr);
39405}
39406
39407// V4 signature sub packets
39408
39409Signature.prototype.read_sub_packet = function (bytes, trusted = true) {
39410  let mypos = 0;
39411
39412  const read_array = (prop, bytes) => {
39413    this[prop] = [];
39414
39415    for (let i = 0; i < bytes.length; i++) {
39416      this[prop].push(bytes[i]);
39417    }
39418  };
39419
39420  // The leftmost bit denotes a "critical" packet
39421  const critical = bytes[mypos] & 0x80;
39422  const type = bytes[mypos] & 0x7F;
39423
39424  // GPG puts the Issuer and Signature subpackets in the unhashed area.
39425  // Tampering with those invalidates the signature, so we can trust them.
39426  // Ignore all other unhashed subpackets.
39427  if (!trusted && ![_enums2.default.signatureSubpacket.issuer, _enums2.default.signatureSubpacket.issuer_fingerprint, _enums2.default.signatureSubpacket.embedded_signature].includes(type)) {
39428    this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length));
39429    return;
39430  }
39431
39432  mypos++;
39433
39434  // subpacket type
39435  switch (type) {
39436    case 2:
39437      // Signature Creation Time
39438      this.created = _util2.default.readDate(bytes.subarray(mypos, bytes.length));
39439      break;
39440    case 3:
39441      {
39442        // Signature Expiration Time in seconds
39443        const seconds = _util2.default.readNumber(bytes.subarray(mypos, bytes.length));
39444
39445        this.signatureNeverExpires = seconds === 0;
39446        this.signatureExpirationTime = seconds;
39447
39448        break;
39449      }
39450    case 4:
39451      // Exportable Certification
39452      this.exportable = bytes[mypos++] === 1;
39453      break;
39454    case 5:
39455      // Trust Signature
39456      this.trustLevel = bytes[mypos++];
39457      this.trustAmount = bytes[mypos++];
39458      break;
39459    case 6:
39460      // Regular Expression
39461      this.regularExpression = bytes[mypos];
39462      break;
39463    case 7:
39464      // Revocable
39465      this.revocable = bytes[mypos++] === 1;
39466      break;
39467    case 9:
39468      {
39469        // Key Expiration Time in seconds
39470        const seconds = _util2.default.readNumber(bytes.subarray(mypos, bytes.length));
39471
39472        this.keyExpirationTime = seconds;
39473        this.keyNeverExpires = seconds === 0;
39474
39475        break;
39476      }
39477    case 11:
39478      // Preferred Symmetric Algorithms
39479      read_array('preferredSymmetricAlgorithms', bytes.subarray(mypos, bytes.length));
39480      break;
39481    case 12:
39482      // Revocation Key
39483      // (1 octet of class, 1 octet of public-key algorithm ID, 20
39484      // octets of
39485      // fingerprint)
39486      this.revocationKeyClass = bytes[mypos++];
39487      this.revocationKeyAlgorithm = bytes[mypos++];
39488      this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);
39489      break;
39490
39491    case 16:
39492      // Issuer
39493      this.issuerKeyId.read(bytes.subarray(mypos, bytes.length));
39494      break;
39495
39496    case 20:
39497      // Notation Data
39498      // We don't know how to handle anything but a text flagged data.
39499      if (bytes[mypos] === 0x80) {
39500        // We extract key/value tuple from the byte stream.
39501        mypos += 4;
39502        const m = _util2.default.readNumber(bytes.subarray(mypos, mypos + 2));
39503        mypos += 2;
39504        const n = _util2.default.readNumber(bytes.subarray(mypos, mypos + 2));
39505        mypos += 2;
39506
39507        const name = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, mypos + m));
39508        const value = _util2.default.Uint8Array_to_str(bytes.subarray(mypos + m, mypos + m + n));
39509
39510        this.notations.push([name, value]);
39511      } else {
39512        _util2.default.print_debug("Unsupported notation flag " + bytes[mypos]);
39513      }
39514      break;
39515    case 21:
39516      // Preferred Hash Algorithms
39517      read_array('preferredHashAlgorithms', bytes.subarray(mypos, bytes.length));
39518      break;
39519    case 22:
39520      // Preferred Compression Algorithms
39521      read_array('preferredCompressionAlgorithms', bytes.subarray(mypos, bytes.length));
39522      break;
39523    case 23:
39524      // Key Server Preferences
39525      read_array('keyServerPreferences', bytes.subarray(mypos, bytes.length));
39526      break;
39527    case 24:
39528      // Preferred Key Server
39529      this.preferredKeyServer = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, bytes.length));
39530      break;
39531    case 25:
39532      // Primary User ID
39533      this.isPrimaryUserID = bytes[mypos++] !== 0;
39534      break;
39535    case 26:
39536      // Policy URI
39537      this.policyURI = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, bytes.length));
39538      break;
39539    case 27:
39540      // Key Flags
39541      read_array('keyFlags', bytes.subarray(mypos, bytes.length));
39542      break;
39543    case 28:
39544      // Signer's User ID
39545      this.signersUserId = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, bytes.length));
39546      break;
39547    case 29:
39548      // Reason for Revocation
39549      this.reasonForRevocationFlag = bytes[mypos++];
39550      this.reasonForRevocationString = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, bytes.length));
39551      break;
39552    case 30:
39553      // Features
39554      read_array('features', bytes.subarray(mypos, bytes.length));
39555      break;
39556    case 31:
39557      {
39558        // Signature Target
39559        // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)
39560        this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];
39561        this.signatureTargetHashAlgorithm = bytes[mypos++];
39562
39563        const len = _crypto2.default.getHashByteLength(this.signatureTargetHashAlgorithm);
39564
39565        this.signatureTargetHash = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, mypos + len));
39566        break;
39567      }
39568    case 32:
39569      // Embedded Signature
39570      this.embeddedSignature = new Signature();
39571      this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));
39572      break;
39573    case 33:
39574      // Issuer Fingerprint
39575      this.issuerKeyVersion = bytes[mypos++];
39576      this.issuerFingerprint = bytes.subarray(mypos, bytes.length);
39577      if (this.issuerKeyVersion === 5) {
39578        this.issuerKeyId.read(this.issuerFingerprint);
39579      } else {
39580        this.issuerKeyId.read(this.issuerFingerprint.subarray(-8));
39581      }
39582      break;
39583    case 34:
39584      // Preferred AEAD Algorithms
39585      read_array.call(this, 'preferredAeadAlgorithms', bytes.subarray(mypos, bytes.length));
39586      break;
39587    default:
39588      {
39589        const err = new Error("Unknown signature subpacket type " + type + " @:" + mypos);
39590        if (critical) {
39591          throw err;
39592        } else {
39593          _util2.default.print_debug(err);
39594        }
39595      }
39596  }
39597};
39598
39599Signature.prototype.read_sub_packets = function (bytes, trusted = true) {
39600  // Two-octet scalar octet count for following subpacket data.
39601  const subpacket_length = _util2.default.readNumber(bytes.subarray(0, 2));
39602
39603  let i = 2;
39604
39605  // subpacket data set (zero or more subpackets)
39606  while (i < 2 + subpacket_length) {
39607    const len = _packet2.default.readSimpleLength(bytes.subarray(i, bytes.length));
39608    i += len.offset;
39609
39610    this.read_sub_packet(bytes.subarray(i, i + len.len), trusted);
39611
39612    i += len.len;
39613  }
39614
39615  return i;
39616};
39617
39618// Produces data to produce signature on
39619Signature.prototype.toSign = function (type, data) {
39620  const t = _enums2.default.signature;
39621
39622  switch (type) {
39623    case t.binary:
39624      if (data.text !== null) {
39625        return _util2.default.str_to_Uint8Array(data.getText(true));
39626      }
39627      return data.getBytes(true);
39628
39629    case t.text:
39630      {
39631        let text = data.getText(true);
39632        // normalize EOL to \r\n
39633        text = _util2.default.canonicalizeEOL(text);
39634        // encode UTF8
39635        return _util2.default.encode_utf8(text);
39636      }
39637    case t.standalone:
39638      return new Uint8Array(0);
39639
39640    case t.cert_generic:
39641    case t.cert_persona:
39642    case t.cert_casual:
39643    case t.cert_positive:
39644    case t.cert_revocation:
39645      {
39646        let packet;
39647        let tag;
39648
39649        if (data.userId) {
39650          tag = 0xB4;
39651          packet = data.userId;
39652        } else if (data.userAttribute) {
39653          tag = 0xD1;
39654          packet = data.userAttribute;
39655        } else {
39656          throw new Error('Either a userId or userAttribute packet needs to be ' + 'supplied for certification.');
39657        }
39658
39659        const bytes = packet.write();
39660
39661        return _util2.default.concat([this.toSign(t.key, data), new Uint8Array([tag]), _util2.default.writeNumber(bytes.length, 4), bytes]);
39662      }
39663    case t.subkey_binding:
39664    case t.subkey_revocation:
39665    case t.key_binding:
39666      return _util2.default.concat([this.toSign(t.key, data), this.toSign(t.key, {
39667        key: data.bind
39668      })]);
39669
39670    case t.key:
39671      if (data.key === undefined) {
39672        throw new Error('Key packet is required for this signature.');
39673      }
39674      return data.key.writeOld();
39675
39676    case t.key_revocation:
39677      return this.toSign(t.key, data);
39678    case t.timestamp:
39679      return new Uint8Array(0);
39680    case t.third_party:
39681      throw new Error('Not implemented');
39682    default:
39683      throw new Error('Unknown signature type.');
39684  }
39685};
39686
39687Signature.prototype.calculateTrailer = function () {
39688  let length = 0;
39689  return _webStreamTools2.default.transform(_webStreamTools2.default.clone(this.signatureData), value => {
39690    length += value.length;
39691  }, () => {
39692    const first = new Uint8Array([4, 0xFF]); //Version, ?
39693    return _util2.default.concat([first, _util2.default.writeNumber(length, 4)]);
39694  });
39695};
39696
39697Signature.prototype.toHash = function (signatureType, data) {
39698  const bytes = this.toSign(signatureType, data);
39699
39700  return _util2.default.concat([bytes, this.signatureData, this.calculateTrailer()]);
39701};
39702
39703Signature.prototype.hash = async function (signatureType, data, toHash, streaming = true) {
39704  const hashAlgorithm = _enums2.default.write(_enums2.default.hash, this.hashAlgorithm);
39705  if (!toHash) toHash = this.toHash(signatureType, data);
39706  if (!streaming && _util2.default.isStream(toHash)) {
39707    return _webStreamTools2.default.fromAsync(async () => this.hash(signatureType, data, (await _webStreamTools2.default.readToEnd(toHash))));
39708  }
39709  return _crypto2.default.hash.digest(hashAlgorithm, toHash);
39710};
39711
39712/**
39713 * verifys the signature packet. Note: not signature types are implemented
39714 * @param {module:packet.PublicSubkey|module:packet.PublicKey|
39715 *         module:packet.SecretSubkey|module:packet.SecretKey} key the public key to verify the signature
39716 * @param {module:enums.signature} signatureType expected signature type
39717 * @param {String|Object} data data which on the signature applies
39718 * @returns {Promise<Boolean>} True if message is verified, else false.
39719 * @async
39720 */
39721Signature.prototype.verify = async function (key, signatureType, data) {
39722  const publicKeyAlgorithm = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm);
39723  const hashAlgorithm = _enums2.default.write(_enums2.default.hash, this.hashAlgorithm);
39724
39725  if (publicKeyAlgorithm !== _enums2.default.write(_enums2.default.publicKey, key.algorithm)) {
39726    throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');
39727  }
39728
39729  let toHash;
39730  let hash;
39731  if (this.hashed) {
39732    hash = this.hashed;
39733  } else {
39734    toHash = this.toHash(signatureType, data);
39735    hash = await this.hash(signatureType, data, toHash);
39736  }
39737  hash = await _webStreamTools2.default.readToEnd(hash);
39738
39739  if (this.signedHashValue[0] !== hash[0] || this.signedHashValue[1] !== hash[1]) {
39740    this.verified = false;
39741  } else {
39742    let mpicount = 0;
39743    // Algorithm-Specific Fields for RSA signatures:
39744    //      - multiprecision number (MPI) of RSA signature value m**d mod n.
39745    if (publicKeyAlgorithm > 0 && publicKeyAlgorithm < 4) {
39746      mpicount = 1;
39747
39748      //    Algorithm-Specific Fields for DSA, ECDSA, and EdDSA signatures:
39749      //      - MPI of DSA value r.
39750      //      - MPI of DSA value s.
39751    } else if (publicKeyAlgorithm === _enums2.default.publicKey.dsa || publicKeyAlgorithm === _enums2.default.publicKey.ecdsa || publicKeyAlgorithm === _enums2.default.publicKey.eddsa) {
39752      mpicount = 2;
39753    }
39754
39755    // EdDSA signature parameters are encoded in little-endian format
39756    // https://tools.ietf.org/html/rfc8032#section-5.1.2
39757    const endian = publicKeyAlgorithm === _enums2.default.publicKey.eddsa ? 'le' : 'be';
39758    const mpi = [];
39759    let i = 0;
39760    this.signature = await _webStreamTools2.default.readToEnd(this.signature);
39761    for (let j = 0; j < mpicount; j++) {
39762      mpi[j] = new _mpi2.default();
39763      i += mpi[j].read(this.signature.subarray(i, this.signature.length), endian);
39764    }
39765
39766    this.verified = await _crypto2.default.signature.verify(publicKeyAlgorithm, hashAlgorithm, mpi, key.params, toHash, hash);
39767  }
39768  return this.verified;
39769};
39770
39771/**
39772 * Verifies signature expiration date
39773 * @param {Date} date (optional) use the given date for verification instead of the current time
39774 * @returns {Boolean} true if expired
39775 */
39776Signature.prototype.isExpired = function (date = new Date()) {
39777  const normDate = _util2.default.normalizeDate(date);
39778  if (normDate !== null) {
39779    const expirationTime = this.getExpirationTime();
39780    return !(this.created <= normDate && normDate <= expirationTime);
39781  }
39782  return false;
39783};
39784
39785/**
39786 * Returns the expiration time of the signature or Infinity if signature does not expire
39787 * @returns {Date} expiration time
39788 */
39789Signature.prototype.getExpirationTime = function () {
39790  return !this.signatureNeverExpires ? new Date(this.created.getTime() + this.signatureExpirationTime * 1000) : Infinity;
39791};
39792
39793/**
39794 * Fix custom types after cloning
39795 */
39796Signature.prototype.postCloneTypeFix = function () {
39797  this.issuerKeyId = _keyid2.default.fromClone(this.issuerKeyId);
39798};
39799
39800exports.default = Signature;
39801
39802},{"../crypto":95,"../enums":114,"../type/keyid.js":149,"../type/mpi.js":150,"../util":153,"./packet":130,"web-stream-tools":76}],138:[function(require,module,exports){
39803'use strict';
39804
39805Object.defineProperty(exports, "__esModule", {
39806  value: true
39807});
39808
39809var _webStreamTools = require('web-stream-tools');
39810
39811var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
39812
39813var _config = require('../config');
39814
39815var _config2 = _interopRequireDefault(_config);
39816
39817var _crypto = require('../crypto');
39818
39819var _crypto2 = _interopRequireDefault(_crypto);
39820
39821var _enums = require('../enums');
39822
39823var _enums2 = _interopRequireDefault(_enums);
39824
39825var _util = require('../util');
39826
39827var _util2 = _interopRequireDefault(_util);
39828
39829function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
39830
39831const VERSION = 1; // A one-octet version number of the data packet.
39832
39833/**
39834 * Implementation of the Symmetrically Encrypted Authenticated Encryption with
39835 * Additional Data (AEAD) Protected Data Packet
39836 *
39837 * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:
39838 * AEAD Protected Data Packet
39839 * @memberof module:packet
39840 * @constructor
39841 */
39842// OpenPGP.js - An OpenPGP implementation in javascript
39843// Copyright (C) 2016 Tankred Hase
39844//
39845// This library is free software; you can redistribute it and/or
39846// modify it under the terms of the GNU Lesser General Public
39847// License as published by the Free Software Foundation; either
39848// version 3.0 of the License, or (at your option) any later version.
39849//
39850// This library is distributed in the hope that it will be useful,
39851// but WITHOUT ANY WARRANTY; without even the implied warranty of
39852// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
39853// Lesser General Public License for more details.
39854//
39855// You should have received a copy of the GNU Lesser General Public
39856// License along with this library; if not, write to the Free Software
39857// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
39858
39859/**
39860 * @requires web-stream-tools
39861 * @requires config
39862 * @requires crypto
39863 * @requires enums
39864 * @requires util
39865 */
39866
39867function SymEncryptedAEADProtected() {
39868  this.tag = _enums2.default.packet.symEncryptedAEADProtected;
39869  this.version = VERSION;
39870  this.cipherAlgo = null;
39871  this.aeadAlgorithm = 'eax';
39872  this.aeadAlgo = null;
39873  this.chunkSizeByte = null;
39874  this.iv = null;
39875  this.encrypted = null;
39876  this.packets = null;
39877}
39878
39879exports.default = SymEncryptedAEADProtected;
39880
39881/**
39882 * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
39883 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes
39884 */
39885
39886SymEncryptedAEADProtected.prototype.read = async function (bytes) {
39887  await _webStreamTools2.default.parse(bytes, async reader => {
39888    if ((await reader.readByte()) !== VERSION) {
39889      // The only currently defined value is 1.
39890      throw new Error('Invalid packet version.');
39891    }
39892    if (_config2.default.aead_protect_version === 4) {
39893      this.cipherAlgo = await reader.readByte();
39894      this.aeadAlgo = await reader.readByte();
39895      this.chunkSizeByte = await reader.readByte();
39896    } else {
39897      this.aeadAlgo = _enums2.default.aead.experimental_gcm;
39898    }
39899    const mode = _crypto2.default[_enums2.default.read(_enums2.default.aead, this.aeadAlgo)];
39900    this.iv = await reader.readBytes(mode.ivLength);
39901    this.encrypted = reader.remainder();
39902  });
39903};
39904
39905/**
39906 * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
39907 * @returns {Uint8Array | ReadableStream<Uint8Array>} The encrypted payload
39908 */
39909SymEncryptedAEADProtected.prototype.write = function () {
39910  if (_config2.default.aead_protect_version === 4) {
39911    return _util2.default.concat([new Uint8Array([this.version, this.cipherAlgo, this.aeadAlgo, this.chunkSizeByte]), this.iv, this.encrypted]);
39912  }
39913  return _util2.default.concat([new Uint8Array([this.version]), this.iv, this.encrypted]);
39914};
39915
39916/**
39917 * Decrypt the encrypted payload.
39918 * @param  {String} sessionKeyAlgorithm   The session key's cipher algorithm e.g. 'aes128'
39919 * @param  {Uint8Array} key               The session key used to encrypt the payload
39920 * @param  {Boolean} streaming            Whether the top-level function will return a stream
39921 * @returns {Boolean}
39922 * @async
39923 */
39924SymEncryptedAEADProtected.prototype.decrypt = async function (sessionKeyAlgorithm, key, streaming) {
39925  if (_config2.default.aead_protect_version !== 4) {
39926    this.cipherAlgo = _enums2.default.write(_enums2.default.symmetric, sessionKeyAlgorithm);
39927  }
39928  await this.packets.read((await this.crypt('decrypt', key, _webStreamTools2.default.clone(this.encrypted), streaming)), streaming);
39929  return true;
39930};
39931
39932/**
39933 * Encrypt the packet list payload.
39934 * @param  {String} sessionKeyAlgorithm   The session key's cipher algorithm e.g. 'aes128'
39935 * @param  {Uint8Array} key               The session key used to encrypt the payload
39936 * @param  {Boolean} streaming            Whether the top-level function will return a stream
39937 * @async
39938 */
39939SymEncryptedAEADProtected.prototype.encrypt = async function (sessionKeyAlgorithm, key, streaming) {
39940  this.cipherAlgo = _enums2.default.write(_enums2.default.symmetric, sessionKeyAlgorithm);
39941  this.aeadAlgo = _config2.default.aead_protect_version === 4 ? _enums2.default.write(_enums2.default.aead, this.aeadAlgorithm) : _enums2.default.aead.experimental_gcm;
39942  const mode = _crypto2.default[_enums2.default.read(_enums2.default.aead, this.aeadAlgo)];
39943  this.iv = await _crypto2.default.random.getRandomBytes(mode.ivLength); // generate new random IV
39944  this.chunkSizeByte = _config2.default.aead_chunk_size_byte;
39945  const data = this.packets.write();
39946  this.encrypted = await this.crypt('encrypt', key, data, streaming);
39947};
39948
39949/**
39950 * En/decrypt the payload.
39951 * @param  {encrypt|decrypt} fn      Whether to encrypt or decrypt
39952 * @param  {Uint8Array} key          The session key used to en/decrypt the payload
39953 * @param  {Uint8Array | ReadableStream<Uint8Array>} data         The data to en/decrypt
39954 * @param  {Boolean} streaming        Whether the top-level function will return a stream
39955 * @returns {Uint8Array | ReadableStream<Uint8Array>}
39956 * @async
39957 */
39958SymEncryptedAEADProtected.prototype.crypt = async function (fn, key, data, streaming) {
39959  const cipher = _enums2.default.read(_enums2.default.symmetric, this.cipherAlgo);
39960  const mode = _crypto2.default[_enums2.default.read(_enums2.default.aead, this.aeadAlgo)];
39961  const modeInstance = await mode(cipher, key);
39962  if (_config2.default.aead_protect_version === 4) {
39963    const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;
39964    const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))
39965    const adataBuffer = new ArrayBuffer(21);
39966    const adataArray = new Uint8Array(adataBuffer, 0, 13);
39967    const adataTagArray = new Uint8Array(adataBuffer);
39968    const adataView = new DataView(adataBuffer);
39969    const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);
39970    adataArray.set([0xC0 | this.tag, this.version, this.cipherAlgo, this.aeadAlgo, this.chunkSizeByte], 0);
39971    let chunkIndex = 0;
39972    let latestPromise = Promise.resolve();
39973    let cryptedBytes = 0;
39974    let queuedBytes = 0;
39975    const iv = this.iv;
39976    return _webStreamTools2.default.transformPair(data, async (readable, writable) => {
39977      const reader = _webStreamTools2.default.getReader(readable);
39978      const buffer = new TransformStream({}, {
39979        highWaterMark: streaming ? _util2.default.getHardwareConcurrency() * 2 ** (_config2.default.aead_chunk_size_byte + 6) : Infinity,
39980        size: array => array.length
39981      });
39982      _webStreamTools2.default.pipe(buffer.readable, writable);
39983      const writer = _webStreamTools2.default.getWriter(buffer.writable);
39984      try {
39985        while (true) {
39986          let chunk = (await reader.readBytes(chunkSize + tagLengthIfDecrypting)) || new Uint8Array();
39987          const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);
39988          chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);
39989          let cryptedPromise;
39990          let done;
39991          if (!chunkIndex || chunk.length) {
39992            reader.unshift(finalChunk);
39993            cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray);
39994          } else {
39995            // After the last chunk, we either encrypt a final, empty
39996            // data chunk to get the final authentication tag or
39997            // validate that final authentication tag.
39998            adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...)
39999            cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray);
40000            done = true;
40001          }
40002          cryptedBytes += chunk.length - tagLengthIfDecrypting;
40003          queuedBytes += chunk.length - tagLengthIfDecrypting;
40004          // eslint-disable-next-line no-loop-func
40005          latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {
40006            await writer.ready;
40007            await writer.write(crypted);
40008            queuedBytes -= chunk.length;
40009          }).catch(err => writer.abort(err));
40010          if (done || queuedBytes > writer.desiredSize) {
40011            await latestPromise; // Respect backpressure
40012          }
40013          if (!done) {
40014            adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)
40015          } else {
40016            await writer.close();
40017            break;
40018          }
40019        }
40020      } catch (e) {
40021        await writer.abort(e);
40022      }
40023    });
40024  } else {
40025    return modeInstance[fn]((await _webStreamTools2.default.readToEnd(data)), this.iv);
40026  }
40027};
40028
40029},{"../config":80,"../crypto":95,"../enums":114,"../util":153,"web-stream-tools":76}],139:[function(require,module,exports){
40030'use strict';
40031
40032Object.defineProperty(exports, "__esModule", {
40033  value: true
40034});
40035
40036var _webStreamTools = require('web-stream-tools');
40037
40038var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
40039
40040var _config = require('../config');
40041
40042var _config2 = _interopRequireDefault(_config);
40043
40044var _crypto = require('../crypto');
40045
40046var _crypto2 = _interopRequireDefault(_crypto);
40047
40048var _enums = require('../enums');
40049
40050var _enums2 = _interopRequireDefault(_enums);
40051
40052var _util = require('../util');
40053
40054var _util2 = _interopRequireDefault(_util);
40055
40056function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
40057
40058const VERSION = 1; // A one-octet version number of the data packet.
40059
40060/**
40061 * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)
40062 *
40063 * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:
40064 * The Symmetrically Encrypted Integrity Protected Data packet is
40065 * a variant of the Symmetrically Encrypted Data packet. It is a new feature
40066 * created for OpenPGP that addresses the problem of detecting a modification to
40067 * encrypted data. It is used in combination with a Modification Detection Code
40068 * packet.
40069 * @memberof module:packet
40070 * @constructor
40071 */
40072// GPG4Browsers - An OpenPGP implementation in javascript
40073// Copyright (C) 2011 Recurity Labs GmbH
40074//
40075// This library is free software; you can redistribute it and/or
40076// modify it under the terms of the GNU Lesser General Public
40077// License as published by the Free Software Foundation; either
40078// version 3.0 of the License, or (at your option) any later version.
40079//
40080// This library is distributed in the hope that it will be useful,
40081// but WITHOUT ANY WARRANTY; without even the implied warranty of
40082// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
40083// Lesser General Public License for more details.
40084//
40085// You should have received a copy of the GNU Lesser General Public
40086// License along with this library; if not, write to the Free Software
40087// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
40088
40089/**
40090 * @requires asmcrypto.js
40091 * @requires web-stream-tools
40092 * @requires config
40093 * @requires crypto
40094 * @requires enums
40095 * @requires util
40096 */
40097
40098function SymEncryptedIntegrityProtected() {
40099  this.tag = _enums2.default.packet.symEncryptedIntegrityProtected;
40100  this.version = VERSION;
40101  /** The encrypted payload. */
40102  this.encrypted = null; // string
40103  /**
40104   * If after decrypting the packet this is set to true,
40105   * a modification has been detected and thus the contents
40106   * should be discarded.
40107   * @type {Boolean}
40108   */
40109  this.modification = false;
40110  this.packets = null;
40111}
40112
40113SymEncryptedIntegrityProtected.prototype.read = async function (bytes) {
40114  await _webStreamTools2.default.parse(bytes, async reader => {
40115
40116    // - A one-octet version number. The only currently defined value is 1.
40117    if ((await reader.readByte()) !== VERSION) {
40118      throw new Error('Invalid packet version.');
40119    }
40120
40121    // - Encrypted data, the output of the selected symmetric-key cipher
40122    //   operating in Cipher Feedback mode with shift amount equal to the
40123    //   block size of the cipher (CFB-n where n is the block size).
40124    this.encrypted = reader.remainder();
40125  });
40126};
40127
40128SymEncryptedIntegrityProtected.prototype.write = function () {
40129  return _util2.default.concat([new Uint8Array([VERSION]), this.encrypted]);
40130};
40131
40132/**
40133 * Encrypt the payload in the packet.
40134 * @param  {String} sessionKeyAlgorithm   The selected symmetric encryption algorithm to be used e.g. 'aes128'
40135 * @param  {Uint8Array} key               The key of cipher blocksize length to be used
40136 * @param  {Boolean} streaming            Whether to set this.encrypted to a stream
40137 * @returns {Promise<Boolean>}
40138 * @async
40139 */
40140SymEncryptedIntegrityProtected.prototype.encrypt = async function (sessionKeyAlgorithm, key, streaming) {
40141  let bytes = this.packets.write();
40142  if (!streaming) bytes = await _webStreamTools2.default.readToEnd(bytes);
40143  const prefix = await _crypto2.default.getPrefixRandom(sessionKeyAlgorithm);
40144  const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet
40145
40146  const tohash = _util2.default.concat([prefix, bytes, mdc]);
40147  const hash = await _crypto2.default.hash.sha1(_webStreamTools2.default.passiveClone(tohash));
40148  const plaintext = _util2.default.concat([tohash, hash]);
40149
40150  this.encrypted = await _crypto2.default.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(_crypto2.default.cipher[sessionKeyAlgorithm].blockSize));
40151  return true;
40152};
40153
40154/**
40155 * Decrypts the encrypted data contained in the packet.
40156 * @param  {String} sessionKeyAlgorithm   The selected symmetric encryption algorithm to be used e.g. 'aes128'
40157 * @param  {Uint8Array} key               The key of cipher blocksize length to be used
40158 * @param  {Boolean} streaming            Whether to read this.encrypted as a stream
40159 * @returns {Promise<Boolean>}
40160 * @async
40161 */
40162SymEncryptedIntegrityProtected.prototype.decrypt = async function (sessionKeyAlgorithm, key, streaming) {
40163  if (!streaming) this.encrypted = await _webStreamTools2.default.readToEnd(this.encrypted);
40164  const encrypted = _webStreamTools2.default.clone(this.encrypted);
40165  const decrypted = await _crypto2.default.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(_crypto2.default.cipher[sessionKeyAlgorithm].blockSize));
40166
40167  // there must be a modification detection code packet as the
40168  // last packet and everything gets hashed except the hash itself
40169  const realHash = _webStreamTools2.default.slice(_webStreamTools2.default.passiveClone(decrypted), -20);
40170  const tohash = _webStreamTools2.default.slice(decrypted, 0, -20);
40171  const verifyHash = Promise.all([_webStreamTools2.default.readToEnd((await _crypto2.default.hash.sha1(_webStreamTools2.default.passiveClone(tohash)))), _webStreamTools2.default.readToEnd(realHash)]).then(([hash, mdc]) => {
40172    if (!_util2.default.equalsUint8Array(hash, mdc)) {
40173      throw new Error('Modification detected.');
40174    }
40175    return new Uint8Array();
40176  });
40177  const bytes = _webStreamTools2.default.slice(tohash, _crypto2.default.cipher[sessionKeyAlgorithm].blockSize + 2); // Remove random prefix
40178  let packetbytes = _webStreamTools2.default.slice(bytes, 0, -2); // Remove MDC packet
40179  packetbytes = _webStreamTools2.default.concat([packetbytes, _webStreamTools2.default.fromAsync(() => verifyHash)]);
40180  if (!_util2.default.isStream(encrypted) || !_config2.default.allow_unauthenticated_stream) {
40181    packetbytes = await _webStreamTools2.default.readToEnd(packetbytes);
40182  }
40183  await this.packets.read(packetbytes, streaming);
40184  return true;
40185};
40186
40187exports.default = SymEncryptedIntegrityProtected;
40188
40189},{"../config":80,"../crypto":95,"../enums":114,"../util":153,"web-stream-tools":76}],140:[function(require,module,exports){
40190'use strict';
40191
40192Object.defineProperty(exports, "__esModule", {
40193  value: true
40194});
40195
40196var _s2k = require('../type/s2k');
40197
40198var _s2k2 = _interopRequireDefault(_s2k);
40199
40200var _config = require('../config');
40201
40202var _config2 = _interopRequireDefault(_config);
40203
40204var _crypto = require('../crypto');
40205
40206var _crypto2 = _interopRequireDefault(_crypto);
40207
40208var _enums = require('../enums');
40209
40210var _enums2 = _interopRequireDefault(_enums);
40211
40212var _util = require('../util');
40213
40214var _util2 = _interopRequireDefault(_util);
40215
40216function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
40217
40218/**
40219 * Public-Key Encrypted Session Key Packets (Tag 1)
40220 *
40221 * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:
40222 * A Public-Key Encrypted Session Key packet holds the session key
40223 * used to encrypt a message. Zero or more Public-Key Encrypted Session Key
40224 * packets and/or Symmetric-Key Encrypted Session Key packets may precede a
40225 * Symmetrically Encrypted Data Packet, which holds an encrypted message. The
40226 * message is encrypted with the session key, and the session key is itself
40227 * encrypted and stored in the Encrypted Session Key packet(s). The
40228 * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted
40229 * Session Key packet for each OpenPGP key to which the message is encrypted.
40230 * The recipient of the message finds a session key that is encrypted to their
40231 * public key, decrypts the session key, and then uses the session key to
40232 * decrypt the message.
40233 * @memberof module:packet
40234 * @constructor
40235 */
40236function SymEncryptedSessionKey() {
40237  this.tag = _enums2.default.packet.symEncryptedSessionKey;
40238  this.version = _config2.default.aead_protect && _config2.default.aead_protect_version === 4 ? 5 : 4;
40239  this.sessionKey = null;
40240  this.sessionKeyEncryptionAlgorithm = null;
40241  this.sessionKeyAlgorithm = 'aes256';
40242  this.aeadAlgorithm = _enums2.default.read(_enums2.default.aead, _config2.default.aead_mode);
40243  this.encrypted = null;
40244  this.s2k = null;
40245  this.iv = null;
40246}
40247
40248/**
40249 * Parsing function for a symmetric encrypted session key packet (tag 3).
40250 *
40251 * @param {Uint8Array} input Payload of a tag 1 packet
40252 * @param {Integer} position Position to start reading from the input string
40253 * @param {Integer} len
40254 *            Length of the packet or the remaining length of
40255 *            input at position
40256 * @returns {module:packet.SymEncryptedSessionKey} Object representation
40257 */
40258// GPG4Browsers - An OpenPGP implementation in javascript
40259// Copyright (C) 2011 Recurity Labs GmbH
40260//
40261// This library is free software; you can redistribute it and/or
40262// modify it under the terms of the GNU Lesser General Public
40263// License as published by the Free Software Foundation; either
40264// version 3.0 of the License, or (at your option) any later version.
40265//
40266// This library is distributed in the hope that it will be useful,
40267// but WITHOUT ANY WARRANTY; without even the implied warranty of
40268// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
40269// Lesser General Public License for more details.
40270//
40271// You should have received a copy of the GNU Lesser General Public
40272// License along with this library; if not, write to the Free Software
40273// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
40274
40275/**
40276 * @requires type/s2k
40277 * @requires config
40278 * @requires crypto
40279 * @requires enums
40280 * @requires util
40281 */
40282
40283SymEncryptedSessionKey.prototype.read = function (bytes) {
40284  let offset = 0;
40285
40286  // A one-octet version number. The only currently defined version is 4.
40287  this.version = bytes[offset++];
40288
40289  // A one-octet number describing the symmetric algorithm used.
40290  const algo = _enums2.default.read(_enums2.default.symmetric, bytes[offset++]);
40291
40292  if (this.version === 5) {
40293    // A one-octet AEAD algorithm.
40294    this.aeadAlgorithm = _enums2.default.read(_enums2.default.aead, bytes[offset++]);
40295  }
40296
40297  // A string-to-key (S2K) specifier, length as defined above.
40298  this.s2k = new _s2k2.default();
40299  offset += this.s2k.read(bytes.subarray(offset, bytes.length));
40300
40301  if (this.version === 5) {
40302    const mode = _crypto2.default[this.aeadAlgorithm];
40303
40304    // A starting initialization vector of size specified by the AEAD
40305    // algorithm.
40306    this.iv = bytes.subarray(offset, offset += mode.ivLength);
40307  }
40308
40309  // The encrypted session key itself, which is decrypted with the
40310  // string-to-key object. This is optional in version 4.
40311  if (this.version === 5 || offset < bytes.length) {
40312    this.encrypted = bytes.subarray(offset, bytes.length);
40313    this.sessionKeyEncryptionAlgorithm = algo;
40314  } else {
40315    this.sessionKeyAlgorithm = algo;
40316  }
40317};
40318
40319SymEncryptedSessionKey.prototype.write = function () {
40320  const algo = this.encrypted === null ? this.sessionKeyAlgorithm : this.sessionKeyEncryptionAlgorithm;
40321
40322  let bytes;
40323
40324  if (this.version === 5) {
40325    bytes = _util2.default.concatUint8Array([new Uint8Array([this.version, _enums2.default.write(_enums2.default.symmetric, algo), _enums2.default.write(_enums2.default.aead, this.aeadAlgorithm)]), this.s2k.write(), this.iv, this.encrypted]);
40326  } else {
40327    bytes = _util2.default.concatUint8Array([new Uint8Array([this.version, _enums2.default.write(_enums2.default.symmetric, algo)]), this.s2k.write()]);
40328
40329    if (this.encrypted !== null) {
40330      bytes = _util2.default.concatUint8Array([bytes, this.encrypted]);
40331    }
40332  }
40333
40334  return bytes;
40335};
40336
40337/**
40338 * Decrypts the session key
40339 * @param {String} passphrase The passphrase in string form
40340 * @returns {Promise<Boolean>}
40341 * @async
40342 */
40343SymEncryptedSessionKey.prototype.decrypt = async function (passphrase) {
40344  const algo = this.sessionKeyEncryptionAlgorithm !== null ? this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm;
40345
40346  const length = _crypto2.default.cipher[algo].keySize;
40347  const key = await this.s2k.produce_key(passphrase, length);
40348
40349  if (this.version === 5) {
40350    const mode = _crypto2.default[this.aeadAlgorithm];
40351    const adata = new Uint8Array([0xC0 | this.tag, this.version, _enums2.default.write(_enums2.default.symmetric, this.sessionKeyEncryptionAlgorithm), _enums2.default.write(_enums2.default.aead, this.aeadAlgorithm)]);
40352    const modeInstance = await mode(algo, key);
40353    this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);
40354  } else if (this.encrypted !== null) {
40355    const decrypted = await _crypto2.default.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(_crypto2.default.cipher[algo].blockSize));
40356
40357    this.sessionKeyAlgorithm = _enums2.default.read(_enums2.default.symmetric, decrypted[0]);
40358    this.sessionKey = decrypted.subarray(1, decrypted.length);
40359  } else {
40360    this.sessionKey = key;
40361  }
40362
40363  return true;
40364};
40365
40366/**
40367 * Encrypts the session key
40368 * @param {String} passphrase The passphrase in string form
40369 * @returns {Promise<Boolean>}
40370 * @async
40371 */
40372SymEncryptedSessionKey.prototype.encrypt = async function (passphrase) {
40373  const algo = this.sessionKeyEncryptionAlgorithm !== null ? this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm;
40374
40375  this.sessionKeyEncryptionAlgorithm = algo;
40376
40377  this.s2k = new _s2k2.default();
40378  this.s2k.salt = await _crypto2.default.random.getRandomBytes(8);
40379
40380  const length = _crypto2.default.cipher[algo].keySize;
40381  const key = await this.s2k.produce_key(passphrase, length);
40382
40383  if (this.sessionKey === null) {
40384    this.sessionKey = await _crypto2.default.generateSessionKey(this.sessionKeyAlgorithm);
40385  }
40386
40387  if (this.version === 5) {
40388    const mode = _crypto2.default[this.aeadAlgorithm];
40389    this.iv = await _crypto2.default.random.getRandomBytes(mode.ivLength); // generate new random IV
40390    const adata = new Uint8Array([0xC0 | this.tag, this.version, _enums2.default.write(_enums2.default.symmetric, this.sessionKeyEncryptionAlgorithm), _enums2.default.write(_enums2.default.aead, this.aeadAlgorithm)]);
40391    const modeInstance = await mode(algo, key);
40392    this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata);
40393  } else {
40394    const algo_enum = new Uint8Array([_enums2.default.write(_enums2.default.symmetric, this.sessionKeyAlgorithm)]);
40395    const private_key = _util2.default.concatUint8Array([algo_enum, this.sessionKey]);
40396    this.encrypted = await _crypto2.default.cfb.encrypt(algo, key, private_key, new Uint8Array(_crypto2.default.cipher[algo].blockSize));
40397  }
40398
40399  return true;
40400};
40401
40402/**
40403 * Fix custom types after cloning
40404 */
40405SymEncryptedSessionKey.prototype.postCloneTypeFix = function () {
40406  this.s2k = _s2k2.default.fromClone(this.s2k);
40407};
40408
40409exports.default = SymEncryptedSessionKey;
40410
40411},{"../config":80,"../crypto":95,"../enums":114,"../type/s2k":152,"../util":153}],141:[function(require,module,exports){
40412'use strict';
40413
40414Object.defineProperty(exports, "__esModule", {
40415  value: true
40416});
40417
40418var _webStreamTools = require('web-stream-tools');
40419
40420var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
40421
40422var _config = require('../config');
40423
40424var _config2 = _interopRequireDefault(_config);
40425
40426var _crypto = require('../crypto');
40427
40428var _crypto2 = _interopRequireDefault(_crypto);
40429
40430var _enums = require('../enums');
40431
40432var _enums2 = _interopRequireDefault(_enums);
40433
40434var _util = require('../util');
40435
40436var _util2 = _interopRequireDefault(_util);
40437
40438function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
40439
40440/**
40441 * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)
40442 *
40443 * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:
40444 * The Symmetrically Encrypted Data packet contains data encrypted with a
40445 * symmetric-key algorithm. When it has been decrypted, it contains other
40446 * packets (usually a literal data packet or compressed data packet, but in
40447 * theory other Symmetrically Encrypted Data packets or sequences of packets
40448 * that form whole OpenPGP messages).
40449 * @memberof module:packet
40450 * @constructor
40451 */
40452function SymmetricallyEncrypted() {
40453  /**
40454   * Packet type
40455   * @type {module:enums.packet}
40456   */
40457  this.tag = _enums2.default.packet.symmetricallyEncrypted;
40458  /**
40459   * Encrypted secret-key data
40460   */
40461  this.encrypted = null;
40462  /**
40463   * Decrypted packets contained within.
40464   * @type {module:packet.List}
40465   */
40466  this.packets = null;
40467  /**
40468   * When true, decrypt fails if message is not integrity protected
40469   * @see module:config.ignore_mdc_error
40470   */
40471  this.ignore_mdc_error = _config2.default.ignore_mdc_error;
40472} // GPG4Browsers - An OpenPGP implementation in javascript
40473// Copyright (C) 2011 Recurity Labs GmbH
40474//
40475// This library is free software; you can redistribute it and/or
40476// modify it under the terms of the GNU Lesser General Public
40477// License as published by the Free Software Foundation; either
40478// version 3.0 of the License, or (at your option) any later version.
40479//
40480// This library is distributed in the hope that it will be useful,
40481// but WITHOUT ANY WARRANTY; without even the implied warranty of
40482// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
40483// Lesser General Public License for more details.
40484//
40485// You should have received a copy of the GNU Lesser General Public
40486// License along with this library; if not, write to the Free Software
40487// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
40488
40489/**
40490 * @requires web-stream-tools
40491 * @requires config
40492 * @requires crypto
40493 * @requires enums
40494 * @requires util
40495 */
40496
40497SymmetricallyEncrypted.prototype.read = function (bytes) {
40498  this.encrypted = bytes;
40499};
40500
40501SymmetricallyEncrypted.prototype.write = function () {
40502  return this.encrypted;
40503};
40504
40505/**
40506 * Decrypt the symmetrically-encrypted packet data
40507 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
40508 * @param {module:enums.symmetric} sessionKeyAlgorithm Symmetric key algorithm to use
40509 * @param {Uint8Array} key    The key of cipher blocksize length to be used
40510 * @returns {Promise<Boolean>}
40511 * @async
40512 */
40513SymmetricallyEncrypted.prototype.decrypt = async function (sessionKeyAlgorithm, key) {
40514  // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error
40515  if (!this.ignore_mdc_error) {
40516    throw new Error('Decryption failed due to missing MDC.');
40517  }
40518
40519  this.encrypted = await _webStreamTools2.default.readToEnd(this.encrypted);
40520  const decrypted = await _crypto2.default.cfb.decrypt(sessionKeyAlgorithm, key, this.encrypted.subarray(_crypto2.default.cipher[sessionKeyAlgorithm].blockSize + 2), this.encrypted.subarray(2, _crypto2.default.cipher[sessionKeyAlgorithm].blockSize + 2));
40521
40522  await this.packets.read(decrypted);
40523
40524  return true;
40525};
40526
40527/**
40528 * Encrypt the symmetrically-encrypted packet data
40529 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
40530 * @param {module:enums.symmetric} sessionKeyAlgorithm Symmetric key algorithm to use
40531 * @param {Uint8Array} key    The key of cipher blocksize length to be used
40532 * @returns {Promise<Boolean>}
40533 * @async
40534 */
40535SymmetricallyEncrypted.prototype.encrypt = async function (algo, key) {
40536  const data = this.packets.write();
40537
40538  const prefix = await _crypto2.default.getPrefixRandom(algo);
40539  const FRE = await _crypto2.default.cfb.encrypt(algo, key, prefix, new Uint8Array(_crypto2.default.cipher[algo].blockSize));
40540  const ciphertext = await _crypto2.default.cfb.encrypt(algo, key, data, FRE.subarray(2));
40541  this.encrypted = _util2.default.concat([FRE, ciphertext]);
40542
40543  return true;
40544};
40545
40546exports.default = SymmetricallyEncrypted;
40547
40548},{"../config":80,"../crypto":95,"../enums":114,"../util":153,"web-stream-tools":76}],142:[function(require,module,exports){
40549'use strict';
40550
40551Object.defineProperty(exports, "__esModule", {
40552  value: true
40553});
40554
40555var _enums = require('../enums');
40556
40557var _enums2 = _interopRequireDefault(_enums);
40558
40559function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
40560
40561/**
40562 * Implementation of the Trust Packet (Tag 12)
40563 *
40564 * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:
40565 * The Trust packet is used only within keyrings and is not normally
40566 * exported.  Trust packets contain data that record the user's
40567 * specifications of which key holders are trustworthy introducers,
40568 * along with other information that implementing software uses for
40569 * trust information.  The format of Trust packets is defined by a given
40570 * implementation.
40571 *
40572 * Trust packets SHOULD NOT be emitted to output streams that are
40573 * transferred to other users, and they SHOULD be ignored on any input
40574 * other than local keyring files.
40575 * @memberof module:packet
40576 * @constructor
40577 */
40578function Trust() {
40579  this.tag = _enums2.default.packet.trust;
40580}
40581
40582/**
40583 * Parsing function for a trust packet (tag 12).
40584 * Currently not implemented as we ignore trust packets
40585 * @param {String} byptes payload of a tag 12 packet
40586 */
40587/**
40588 * @requires enums
40589 */
40590
40591Trust.prototype.read = function () {}; // TODO
40592
40593exports.default = Trust;
40594
40595},{"../enums":114}],143:[function(require,module,exports){
40596'use strict';
40597
40598Object.defineProperty(exports, "__esModule", {
40599  value: true
40600});
40601
40602var _packet = require('./packet');
40603
40604var _packet2 = _interopRequireDefault(_packet);
40605
40606var _enums = require('../enums');
40607
40608var _enums2 = _interopRequireDefault(_enums);
40609
40610var _util = require('../util');
40611
40612var _util2 = _interopRequireDefault(_util);
40613
40614function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
40615
40616/**
40617 * Implementation of the User Attribute Packet (Tag 17)
40618 *
40619 * The User Attribute packet is a variation of the User ID packet.  It
40620 * is capable of storing more types of data than the User ID packet,
40621 * which is limited to text.  Like the User ID packet, a User Attribute
40622 * packet may be certified by the key owner ("self-signed") or any other
40623 * key owner who cares to certify it.  Except as noted, a User Attribute
40624 * packet may be used anywhere that a User ID packet may be used.
40625 *
40626 * While User Attribute packets are not a required part of the OpenPGP
40627 * standard, implementations SHOULD provide at least enough
40628 * compatibility to properly handle a certification signature on the
40629 * User Attribute packet.  A simple way to do this is by treating the
40630 * User Attribute packet as a User ID packet with opaque contents, but
40631 * an implementation may use any method desired.
40632 * @memberof module:packet
40633 * @constructor
40634 */
40635function UserAttribute() {
40636  this.tag = _enums2.default.packet.userAttribute;
40637  this.attributes = [];
40638}
40639
40640/**
40641 * parsing function for a user attribute packet (tag 17).
40642 * @param {Uint8Array} input payload of a tag 17 packet
40643 */
40644// GPG4Browsers - An OpenPGP implementation in javascript
40645// Copyright (C) 2011 Recurity Labs GmbH
40646//
40647// This library is free software; you can redistribute it and/or
40648// modify it under the terms of the GNU Lesser General Public
40649// License as published by the Free Software Foundation; either
40650// version 3.0 of the License, or (at your option) any later version.
40651//
40652// This library is distributed in the hope that it will be useful,
40653// but WITHOUT ANY WARRANTY; without even the implied warranty of
40654// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
40655// Lesser General Public License for more details.
40656//
40657// You should have received a copy of the GNU Lesser General Public
40658// License along with this library; if not, write to the Free Software
40659// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
40660
40661/**
40662 * @requires packet
40663 * @requires enums
40664 * @requires util
40665 */
40666
40667UserAttribute.prototype.read = function (bytes) {
40668  let i = 0;
40669  while (i < bytes.length) {
40670    const len = _packet2.default.readSimpleLength(bytes.subarray(i, bytes.length));
40671    i += len.offset;
40672
40673    this.attributes.push(_util2.default.Uint8Array_to_str(bytes.subarray(i, i + len.len)));
40674    i += len.len;
40675  }
40676};
40677
40678/**
40679 * Creates a binary representation of the user attribute packet
40680 * @returns {Uint8Array} string representation
40681 */
40682UserAttribute.prototype.write = function () {
40683  const arr = [];
40684  for (let i = 0; i < this.attributes.length; i++) {
40685    arr.push(_packet2.default.writeSimpleLength(this.attributes[i].length));
40686    arr.push(_util2.default.str_to_Uint8Array(this.attributes[i]));
40687  }
40688  return _util2.default.concatUint8Array(arr);
40689};
40690
40691/**
40692 * Compare for equality
40693 * @param  {module:packet.UserAttribute} usrAttr
40694 * @returns {Boolean}         true if equal
40695 */
40696UserAttribute.prototype.equals = function (usrAttr) {
40697  if (!usrAttr || !(usrAttr instanceof UserAttribute)) {
40698    return false;
40699  }
40700  return this.attributes.every(function (attr, index) {
40701    return attr === usrAttr.attributes[index];
40702  });
40703};
40704
40705exports.default = UserAttribute;
40706
40707},{"../enums":114,"../util":153,"./packet":130}],144:[function(require,module,exports){
40708'use strict';
40709
40710Object.defineProperty(exports, "__esModule", {
40711  value: true
40712});
40713
40714var _enums = require('../enums');
40715
40716var _enums2 = _interopRequireDefault(_enums);
40717
40718var _util = require('../util');
40719
40720var _util2 = _interopRequireDefault(_util);
40721
40722function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
40723
40724/**
40725 * Implementation of the User ID Packet (Tag 13)
40726 *
40727 * A User ID packet consists of UTF-8 text that is intended to represent
40728 * the name and email address of the key holder.  By convention, it
40729 * includes an RFC 2822 [RFC2822] mail name-addr, but there are no
40730 * restrictions on its content.  The packet length in the header
40731 * specifies the length of the User ID.
40732 * @memberof module:packet
40733 * @constructor
40734 */
40735// GPG4Browsers - An OpenPGP implementation in javascript
40736// Copyright (C) 2011 Recurity Labs GmbH
40737//
40738// This library is free software; you can redistribute it and/or
40739// modify it under the terms of the GNU Lesser General Public
40740// License as published by the Free Software Foundation; either
40741// version 3.0 of the License, or (at your option) any later version.
40742//
40743// This library is distributed in the hope that it will be useful,
40744// but WITHOUT ANY WARRANTY; without even the implied warranty of
40745// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
40746// Lesser General Public License for more details.
40747//
40748// You should have received a copy of the GNU Lesser General Public
40749// License along with this library; if not, write to the Free Software
40750// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
40751
40752/**
40753 * @requires enums
40754 * @requires util
40755 */
40756
40757function Userid() {
40758  this.tag = _enums2.default.packet.userid;
40759  /** A string containing the user id. Usually in the form
40760   * John Doe <john@example.com>
40761   * @type {String}
40762   */
40763  this.userid = '';
40764
40765  this.name = '';
40766  this.email = '';
40767  this.comment = '';
40768}
40769
40770/**
40771 * Parsing function for a user id packet (tag 13).
40772 * @param {Uint8Array} input payload of a tag 13 packet
40773 */
40774Userid.prototype.read = function (bytes) {
40775  this.parse(_util2.default.decode_utf8(bytes));
40776};
40777
40778/**
40779 * Parse userid string, e.g. 'John Doe <john@example.com>'
40780 */
40781Userid.prototype.parse = function (userid) {
40782  try {
40783    Object.assign(this, _util2.default.parseUserId(userid));
40784  } catch (e) {}
40785  this.userid = userid;
40786};
40787
40788/**
40789 * Creates a binary representation of the user id packet
40790 * @returns {Uint8Array} binary representation
40791 */
40792Userid.prototype.write = function () {
40793  return _util2.default.encode_utf8(this.userid);
40794};
40795
40796/**
40797 * Set userid string from object, e.g. { name:'Phil Zimmermann', email:'phil@openpgp.org' }
40798 */
40799Userid.prototype.format = function (userid) {
40800  if (_util2.default.isString(userid)) {
40801    userid = _util2.default.parseUserId(userid);
40802  }
40803  Object.assign(this, userid);
40804  this.userid = _util2.default.formatUserId(userid);
40805};
40806
40807exports.default = Userid;
40808
40809},{"../enums":114,"../util":153}],145:[function(require,module,exports){
40810(function (global){
40811'use strict';
40812
40813var _util = require('./util');
40814
40815var _util2 = _interopRequireDefault(_util);
40816
40817function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
40818
40819if (typeof window !== 'undefined') {
40820  /********************************************************************
40821   * NOTE: This list is duplicated in Gruntfile.js,                   *
40822   * so that these polyfills are only included in the compat bundle.  *
40823   ********************************************************************/
40824
40825  try {
40826    if (typeof window.fetch === 'undefined') {
40827      require('whatwg-fetch');
40828    }
40829    if (typeof Array.prototype.fill === 'undefined') {
40830      require('core-js/fn/array/fill');
40831    }
40832    if (typeof Array.prototype.find === 'undefined') {
40833      require('core-js/fn/array/find');
40834    }
40835    if (typeof Array.prototype.includes === 'undefined') {
40836      require('core-js/fn/array/includes');
40837    }
40838    if (typeof Array.from === 'undefined') {
40839      require('core-js/fn/array/from');
40840    }
40841
40842    // No if-statement on Promise because of IE11. Otherwise Promise is undefined in the service worker.
40843    require('core-js/fn/promise');
40844
40845    if (typeof Uint8Array.from === 'undefined') {
40846      require('core-js/fn/typed/uint8-array');
40847    }
40848    if (typeof String.prototype.repeat === 'undefined') {
40849      require('core-js/fn/string/repeat');
40850    }
40851    if (typeof Symbol === 'undefined') {
40852      require('core-js/fn/symbol');
40853    }
40854    if (typeof Object.assign === 'undefined') {
40855      require('core-js/fn/object/assign');
40856    }
40857  } catch (e) {}
40858} /**
40859   * @fileoverview Old browser polyfills
40860   * All are listed as dev dependencies because Node does not need them
40861   * and for browser babel will take care of it
40862   * @requires util
40863   * @module polyfills
40864   */
40865
40866if (typeof TransformStream === 'undefined') {
40867  require('@mattiasbuelens/web-streams-polyfill/es6');
40868}
40869if (typeof TextEncoder === 'undefined') {
40870  const nodeUtil = _util2.default.nodeRequire('util') || {};
40871  global.TextEncoder = nodeUtil.TextEncoder;
40872  global.TextDecoder = nodeUtil.TextDecoder;
40873}
40874if (typeof TextEncoder === 'undefined') {
40875  const textEncoding = require('text-encoding-utf-8');
40876  global.TextEncoder = textEncoding.TextEncoder;
40877  global.TextDecoder = textEncoding.TextDecoder;
40878}
40879
40880}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
40881},{"./util":153,"@mattiasbuelens/web-streams-polyfill/es6":1,"core-js/fn/array/fill":"core-js/fn/array/fill","core-js/fn/array/find":"core-js/fn/array/find","core-js/fn/array/from":"core-js/fn/array/from","core-js/fn/array/includes":"core-js/fn/array/includes","core-js/fn/object/assign":"core-js/fn/object/assign","core-js/fn/promise":"core-js/fn/promise","core-js/fn/string/repeat":"core-js/fn/string/repeat","core-js/fn/symbol":"core-js/fn/symbol","core-js/fn/typed/uint8-array":"core-js/fn/typed/uint8-array","text-encoding-utf-8":72,"whatwg-fetch":"whatwg-fetch"}],146:[function(require,module,exports){
40882'use strict';
40883
40884Object.defineProperty(exports, "__esModule", {
40885  value: true
40886});
40887exports.Signature = Signature;
40888exports.readArmored = readArmored;
40889exports.read = read;
40890
40891var _armor = require('./encoding/armor');
40892
40893var _armor2 = _interopRequireDefault(_armor);
40894
40895var _packet = require('./packet');
40896
40897var _packet2 = _interopRequireDefault(_packet);
40898
40899var _enums = require('./enums');
40900
40901var _enums2 = _interopRequireDefault(_enums);
40902
40903function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
40904
40905/**
40906 * @class
40907 * @classdesc Class that represents an OpenPGP signature.
40908 * @param  {module:packet.List} packetlist The signature packets
40909 */
40910function Signature(packetlist) {
40911  if (!(this instanceof Signature)) {
40912    return new Signature(packetlist);
40913  }
40914  this.packets = packetlist || new _packet2.default.List();
40915}
40916
40917/**
40918 * Returns ASCII armored text of signature
40919 * @returns {ReadableStream<String>} ASCII armor
40920 */
40921// GPG4Browsers - An OpenPGP implementation in javascript
40922// Copyright (C) 2011 Recurity Labs GmbH
40923//
40924// This library is free software; you can redistribute it and/or
40925// modify it under the terms of the GNU Lesser General Public
40926// License as published by the Free Software Foundation; either
40927// version 3.0 of the License, or (at your option) any later version.
40928//
40929// This library is distributed in the hope that it will be useful,
40930// but WITHOUT ANY WARRANTY; without even the implied warranty of
40931// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
40932// Lesser General Public License for more details.
40933//
40934// You should have received a copy of the GNU Lesser General Public
40935// License along with this library; if not, write to the Free Software
40936// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
40937
40938/**
40939 * @requires encoding/armor
40940 * @requires packet
40941 * @requires enums
40942 * @module signature
40943 */
40944
40945Signature.prototype.armor = function () {
40946  return _armor2.default.encode(_enums2.default.armor.signature, this.packets.write());
40947};
40948
40949/**
40950 * reads an OpenPGP armored signature and returns a signature object
40951 * @param {String | ReadableStream<String>} armoredText text to be parsed
40952 * @returns {Signature} new signature object
40953 * @async
40954 * @static
40955 */
40956async function readArmored(armoredText) {
40957  const input = await _armor2.default.decode(armoredText);
40958  return read(input.data);
40959}
40960
40961/**
40962 * reads an OpenPGP signature as byte array and returns a signature object
40963 * @param {Uint8Array | ReadableStream<Uint8Array>} input   binary signature
40964 * @returns {Signature}         new signature object
40965 * @async
40966 * @static
40967 */
40968async function read(input) {
40969  const packetlist = new _packet2.default.List();
40970  await packetlist.read(input);
40971  return new Signature(packetlist);
40972}
40973
40974},{"./encoding/armor":112,"./enums":114,"./packet":126}],147:[function(require,module,exports){
40975'use strict';
40976
40977Object.defineProperty(exports, "__esModule", {
40978  value: true
40979});
40980
40981var _util = require('../util');
40982
40983var _util2 = _interopRequireDefault(_util);
40984
40985function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
40986
40987/**
40988 * @constructor
40989 */
40990function ECDHSymmetricKey(data) {
40991  if (typeof data === 'undefined') {
40992    data = new Uint8Array([]);
40993  } else if (_util2.default.isString(data)) {
40994    data = _util2.default.str_to_Uint8Array(data);
40995  } else {
40996    data = new Uint8Array(data);
40997  }
40998  this.data = data;
40999}
41000
41001/**
41002 * Read an ECDHSymmetricKey from an Uint8Array
41003 * @param  {Uint8Array}  input  Where to read the encoded symmetric key from
41004 * @returns {Number}             Number of read bytes
41005 */
41006// OpenPGP.js - An OpenPGP implementation in javascript
41007// Copyright (C) 2015-2016 Decentral
41008//
41009// This library is free software; you can redistribute it and/or
41010// modify it under the terms of the GNU Lesser General Public
41011// License as published by the Free Software Foundation; either
41012// version 3.0 of the License, or (at your option) any later version.
41013//
41014// This library is distributed in the hope that it will be useful,
41015// but WITHOUT ANY WARRANTY; without even the implied warranty of
41016// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
41017// Lesser General Public License for more details.
41018//
41019// You should have received a copy of the GNU Lesser General Public
41020// License along with this library; if not, write to the Free Software
41021// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
41022
41023/**
41024 * Encoded symmetric key for ECDH
41025 *
41026 * @requires util
41027 * @module type/ecdh_symkey
41028 */
41029
41030ECDHSymmetricKey.prototype.read = function (input) {
41031  if (input.length >= 1) {
41032    const length = input[0];
41033    if (input.length >= 1 + length) {
41034      this.data = input.subarray(1, 1 + length);
41035      return 1 + this.data.length;
41036    }
41037  }
41038  throw new Error('Invalid symmetric key');
41039};
41040
41041/**
41042 * Write an ECDHSymmetricKey as an Uint8Array
41043 * @returns  {Uint8Array}  An array containing the value
41044 */
41045ECDHSymmetricKey.prototype.write = function () {
41046  return _util2.default.concatUint8Array([new Uint8Array([this.data.length]), this.data]);
41047};
41048
41049ECDHSymmetricKey.fromClone = function (clone) {
41050  return new ECDHSymmetricKey(clone.data);
41051};
41052
41053exports.default = ECDHSymmetricKey;
41054
41055},{"../util":153}],148:[function(require,module,exports){
41056'use strict';
41057
41058Object.defineProperty(exports, "__esModule", {
41059  value: true
41060});
41061
41062var _enums = require('../enums.js');
41063
41064var _enums2 = _interopRequireDefault(_enums);
41065
41066function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
41067
41068/**
41069 * @constructor
41070 * @param  {enums.hash}       hash    Hash algorithm
41071 * @param  {enums.symmetric}  cipher  Symmetric algorithm
41072 */
41073function KDFParams(data) {
41074  if (data && data.length === 2) {
41075    this.hash = data[0];
41076    this.cipher = data[1];
41077  } else {
41078    this.hash = _enums2.default.hash.sha1;
41079    this.cipher = _enums2.default.symmetric.aes128;
41080  }
41081}
41082
41083/**
41084 * Read KDFParams from an Uint8Array
41085 * @param  {Uint8Array}  input  Where to read the KDFParams from
41086 * @returns {Number}             Number of read bytes
41087 */
41088// OpenPGP.js - An OpenPGP implementation in javascript
41089// Copyright (C) 2015-2016 Decentral
41090//
41091// This library is free software; you can redistribute it and/or
41092// modify it under the terms of the GNU Lesser General Public
41093// License as published by the Free Software Foundation; either
41094// version 3.0 of the License, or (at your option) any later version.
41095//
41096// This library is distributed in the hope that it will be useful,
41097// but WITHOUT ANY WARRANTY; without even the implied warranty of
41098// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
41099// Lesser General Public License for more details.
41100//
41101// You should have received a copy of the GNU Lesser General Public
41102// License along with this library; if not, write to the Free Software
41103// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
41104
41105/**
41106 * Implementation of type KDF parameters
41107 *
41108 * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:
41109 * A key derivation function (KDF) is necessary to implement the EC
41110 * encryption.  The Concatenation Key Derivation Function (Approved
41111 * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is
41112 * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.
41113 * @requires enums
41114 * @module type/kdf_params
41115 */
41116
41117KDFParams.prototype.read = function (input) {
41118  if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {
41119    throw new Error('Cannot read KDFParams');
41120  }
41121  this.hash = input[2];
41122  this.cipher = input[3];
41123  return 4;
41124};
41125
41126/**
41127 * Write KDFParams to an Uint8Array
41128 * @returns  {Uint8Array}  Array with the KDFParams value
41129 */
41130KDFParams.prototype.write = function () {
41131  return new Uint8Array([3, 1, this.hash, this.cipher]);
41132};
41133
41134KDFParams.fromClone = function (clone) {
41135  return new KDFParams([clone.hash, clone.cipher]);
41136};
41137
41138exports.default = KDFParams;
41139
41140},{"../enums.js":114}],149:[function(require,module,exports){
41141'use strict';
41142
41143Object.defineProperty(exports, "__esModule", {
41144  value: true
41145});
41146
41147var _util = require('../util.js');
41148
41149var _util2 = _interopRequireDefault(_util);
41150
41151function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
41152
41153/**
41154 * @constructor
41155 */
41156function Keyid() {
41157  this.bytes = '';
41158}
41159
41160/**
41161 * Parsing method for a key id
41162 * @param {Uint8Array} input Input to read the key id from
41163 */
41164// GPG4Browsers - An OpenPGP implementation in javascript
41165// Copyright (C) 2011 Recurity Labs GmbH
41166//
41167// This library is free software; you can redistribute it and/or
41168// modify it under the terms of the GNU Lesser General Public
41169// License as published by the Free Software Foundation; either
41170// version 3.0 of the License, or (at your option) any later version.
41171//
41172// This library is distributed in the hope that it will be useful,
41173// but WITHOUT ANY WARRANTY; without even the implied warranty of
41174// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
41175// Lesser General Public License for more details.
41176//
41177// You should have received a copy of the GNU Lesser General Public
41178// License along with this library; if not, write to the Free Software
41179// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
41180
41181/**
41182 * Implementation of type key id
41183 *
41184 * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:
41185 * A Key ID is an eight-octet scalar that identifies a key.
41186 * Implementations SHOULD NOT assume that Key IDs are unique.  The
41187 * section "Enhanced Key Formats" below describes how Key IDs are
41188 * formed.
41189 * @requires util
41190 * @module type/keyid
41191 */
41192
41193Keyid.prototype.read = function (bytes) {
41194  this.bytes = _util2.default.Uint8Array_to_str(bytes.subarray(0, 8));
41195};
41196
41197Keyid.prototype.write = function () {
41198  return _util2.default.str_to_Uint8Array(this.bytes);
41199};
41200
41201Keyid.prototype.toHex = function () {
41202  return _util2.default.str_to_hex(this.bytes);
41203};
41204
41205/**
41206 * Checks equality of Key ID's
41207 * @param {Keyid} keyid
41208 * @param {Boolean} matchWildcard Indicates whether to check if either keyid is a wildcard
41209 */
41210Keyid.prototype.equals = function (keyid, matchWildcard = false) {
41211  return matchWildcard && (keyid.isWildcard() || this.isWildcard()) || this.bytes === keyid.bytes;
41212};
41213
41214Keyid.prototype.isNull = function () {
41215  return this.bytes === '';
41216};
41217
41218Keyid.prototype.isWildcard = function () {
41219  return (/^0+$/.test(this.toHex())
41220  );
41221};
41222
41223Keyid.mapToHex = function (keyId) {
41224  return keyId.toHex();
41225};
41226
41227Keyid.fromClone = function (clone) {
41228  const keyid = new Keyid();
41229  keyid.bytes = clone.bytes;
41230  return keyid;
41231};
41232
41233Keyid.fromId = function (hex) {
41234  const keyid = new Keyid();
41235  keyid.read(_util2.default.hex_to_Uint8Array(hex));
41236  return keyid;
41237};
41238
41239Keyid.wildcard = function () {
41240  const keyid = new Keyid();
41241  keyid.read(new Uint8Array(8));
41242  return keyid;
41243};
41244
41245exports.default = Keyid;
41246
41247},{"../util.js":153}],150:[function(require,module,exports){
41248'use strict';
41249
41250Object.defineProperty(exports, "__esModule", {
41251  value: true
41252});
41253
41254var _bn = require('bn.js');
41255
41256var _bn2 = _interopRequireDefault(_bn);
41257
41258var _util = require('../util');
41259
41260var _util2 = _interopRequireDefault(_util);
41261
41262function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
41263
41264/**
41265 * @constructor
41266 */
41267// GPG4Browsers - An OpenPGP implementation in javascript
41268// Copyright (C) 2011 Recurity Labs GmbH
41269//
41270// This library is free software; you can redistribute it and/or
41271// modify it under the terms of the GNU Lesser General Public
41272// License as published by the Free Software Foundation; either
41273// version 3.0 of the License, or (at your option) any later version.
41274//
41275// This library is distributed in the hope that it will be useful,
41276// but WITHOUT ANY WARRANTY; without even the implied warranty of
41277// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
41278// Lesser General Public License for more details.
41279//
41280// You should have received a copy of the GNU Lesser General Public
41281// License along with this library; if not, write to the Free Software
41282// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
41283
41284// Hint: We hold our MPIs as an array of octets in big endian format preceding a two
41285// octet scalar: MPI: [a,b,c,d,e,f]
41286// - MPI size: (a << 8) | b
41287// - MPI = c | d << 8 | e << ((MPI.length -2)*8) | f ((MPI.length -2)*8)
41288
41289/**
41290 * Implementation of type MPI ({@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2})
41291 * Multiprecision integers (also called MPIs) are unsigned integers used
41292 * to hold large integers such as the ones used in cryptographic
41293 * calculations.
41294 * An MPI consists of two pieces: a two-octet scalar that is the length
41295 * of the MPI in bits followed by a string of octets that contain the
41296 * actual integer.
41297 * @requires bn.js
41298 * @requires util
41299 * @module type/mpi
41300 */
41301
41302function MPI(data) {
41303  /** An implementation dependent integer */
41304  if (data instanceof MPI) {
41305    this.data = data.data;
41306  } else if (_bn2.default.isBN(data)) {
41307    this.fromBN(data);
41308  } else if (_util2.default.isUint8Array(data)) {
41309    this.fromUint8Array(data);
41310  } else if (_util2.default.isString(data)) {
41311    this.fromString(data);
41312  } else {
41313    this.data = null;
41314  }
41315}
41316
41317/**
41318 * Parsing function for a MPI ({@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC 4880 3.2}).
41319 * @param {Uint8Array} input  Payload of MPI data
41320 * @param {String}     endian Endianness of the data; 'be' for big-endian or 'le' for little-endian
41321 * @returns {Integer}          Length of data read
41322 */
41323MPI.prototype.read = function (bytes, endian = 'be') {
41324  if (_util2.default.isString(bytes)) {
41325    bytes = _util2.default.str_to_Uint8Array(bytes);
41326  }
41327
41328  const bits = bytes[0] << 8 | bytes[1];
41329  const bytelen = bits + 7 >>> 3;
41330  const payload = bytes.subarray(2, 2 + bytelen);
41331
41332  this.fromUint8Array(payload, endian);
41333
41334  return 2 + bytelen;
41335};
41336
41337/**
41338 * Converts the mpi object to a bytes as specified in
41339 * {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2}
41340 * @param {String} endian Endianness of the payload; 'be' for big-endian or 'le' for little-endian
41341 * @param {Integer} length Length of the data part of the MPI
41342 * @returns {Uint8Aray} mpi Byte representation
41343 */
41344MPI.prototype.write = function (endian, length) {
41345  return _util2.default.Uint8Array_to_MPI(this.toUint8Array(endian, length));
41346};
41347
41348MPI.prototype.bitLength = function () {
41349  return (this.data.length - 1) * 8 + _util2.default.nbits(this.data[0]);
41350};
41351
41352MPI.prototype.byteLength = function () {
41353  return this.data.length;
41354};
41355
41356MPI.prototype.toUint8Array = function (endian, length) {
41357  endian = endian || 'be';
41358  length = length || this.data.length;
41359
41360  const payload = new Uint8Array(length);
41361  const start = length - this.data.length;
41362  if (start < 0) {
41363    throw new Error('Payload is too large.');
41364  }
41365
41366  payload.set(this.data, start);
41367  if (endian === 'le') {
41368    payload.reverse();
41369  }
41370
41371  return payload;
41372};
41373
41374MPI.prototype.fromUint8Array = function (bytes, endian = 'be') {
41375  this.data = new Uint8Array(bytes.length);
41376  this.data.set(bytes);
41377
41378  if (endian === 'le') {
41379    this.data.reverse();
41380  }
41381};
41382
41383MPI.prototype.toString = function () {
41384  return _util2.default.Uint8Array_to_str(this.toUint8Array());
41385};
41386
41387MPI.prototype.fromString = function (str, endian = 'be') {
41388  this.fromUint8Array(_util2.default.str_to_Uint8Array(str), endian);
41389};
41390
41391MPI.prototype.toBN = function () {
41392  return new _bn2.default(this.toUint8Array());
41393};
41394
41395MPI.prototype.fromBN = function (bn) {
41396  this.data = bn.toArrayLike(Uint8Array);
41397};
41398
41399MPI.fromClone = function (clone) {
41400  return new MPI(clone.data);
41401};
41402
41403exports.default = MPI;
41404
41405},{"../util":153,"bn.js":17}],151:[function(require,module,exports){
41406'use strict';
41407
41408Object.defineProperty(exports, "__esModule", {
41409  value: true
41410});
41411
41412var _util = require('../util');
41413
41414var _util2 = _interopRequireDefault(_util);
41415
41416var _enums = require('../enums');
41417
41418var _enums2 = _interopRequireDefault(_enums);
41419
41420function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
41421
41422/**
41423 * @constructor
41424 */
41425// OpenPGP.js - An OpenPGP implementation in javascript
41426// Copyright (C) 2015-2016 Decentral
41427//
41428// This library is free software; you can redistribute it and/or
41429// modify it under the terms of the GNU Lesser General Public
41430// License as published by the Free Software Foundation; either
41431// version 3.0 of the License, or (at your option) any later version.
41432//
41433// This library is distributed in the hope that it will be useful,
41434// but WITHOUT ANY WARRANTY; without even the implied warranty of
41435// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
41436// Lesser General Public License for more details.
41437//
41438// You should have received a copy of the GNU Lesser General Public
41439// License along with this library; if not, write to the Free Software
41440// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
41441
41442/**
41443 * Wrapper to an OID value
41444 *
41445 * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}:
41446 * The sequence of octets in the third column is the result of applying
41447 * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier
41448 * with subsequent truncation.  The truncation removes the two fields of
41449 * encoded Object Identifier.  The first omitted field is one octet
41450 * representing the Object Identifier tag, and the second omitted field
41451 * is the length of the Object Identifier body.  For example, the
41452 * complete ASN.1 DER encoding for the NIST P-256 curve OID is "06 08 2A
41453 * 86 48 CE 3D 03 01 07", from which the first entry in the table above
41454 * is constructed by omitting the first two octets.  Only the truncated
41455 * sequence of octets is the valid representation of a curve OID.
41456 * @requires util
41457 * @requires enums
41458 * @module type/oid
41459 */
41460
41461function OID(oid) {
41462  if (oid instanceof OID) {
41463    this.oid = oid.oid;
41464  } else if (_util2.default.isArray(oid) || _util2.default.isUint8Array(oid)) {
41465    oid = new Uint8Array(oid);
41466    if (oid[0] === 0x06) {
41467      // DER encoded oid byte array
41468      if (oid[1] !== oid.length - 2) {
41469        throw new Error('Length mismatch in DER encoded oid');
41470      }
41471      oid = oid.subarray(2);
41472    }
41473    this.oid = oid;
41474  } else {
41475    this.oid = '';
41476  }
41477}
41478
41479/**
41480 * Method to read an OID object
41481 * @param  {Uint8Array}  input  Where to read the OID from
41482 * @returns {Number}             Number of read bytes
41483 */
41484OID.prototype.read = function (input) {
41485  if (input.length >= 1) {
41486    const length = input[0];
41487    if (input.length >= 1 + length) {
41488      this.oid = input.subarray(1, 1 + length);
41489      return 1 + this.oid.length;
41490    }
41491  }
41492  throw new Error('Invalid oid');
41493};
41494
41495/**
41496 * Serialize an OID object
41497 * @returns {Uint8Array} Array with the serialized value the OID
41498 */
41499OID.prototype.write = function () {
41500  return _util2.default.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);
41501};
41502
41503/**
41504 * Serialize an OID object as a hex string
41505 * @returns {string} String with the hex value of the OID
41506 */
41507OID.prototype.toHex = function () {
41508  return _util2.default.Uint8Array_to_hex(this.oid);
41509};
41510
41511/**
41512 * If a known curve object identifier, return the canonical name of the curve
41513 * @returns {string} String with the canonical name of the curve
41514 */
41515OID.prototype.getName = function () {
41516  const hex = this.toHex();
41517  if (_enums2.default.curve[hex]) {
41518    return _enums2.default.write(_enums2.default.curve, hex);
41519  } else {
41520    throw new Error('Unknown curve object identifier.');
41521  }
41522};
41523
41524OID.fromClone = function (clone) {
41525  return new OID(clone.oid);
41526};
41527
41528exports.default = OID;
41529
41530},{"../enums":114,"../util":153}],152:[function(require,module,exports){
41531'use strict';
41532
41533Object.defineProperty(exports, "__esModule", {
41534  value: true
41535});
41536
41537var _config = require('../config');
41538
41539var _config2 = _interopRequireDefault(_config);
41540
41541var _crypto = require('../crypto');
41542
41543var _crypto2 = _interopRequireDefault(_crypto);
41544
41545var _enums = require('../enums.js');
41546
41547var _enums2 = _interopRequireDefault(_enums);
41548
41549var _util = require('../util.js');
41550
41551var _util2 = _interopRequireDefault(_util);
41552
41553function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
41554
41555/**
41556 * @constructor
41557 */
41558// GPG4Browsers - An OpenPGP implementation in javascript
41559// Copyright (C) 2011 Recurity Labs GmbH
41560//
41561// This library is free software; you can redistribute it and/or
41562// modify it under the terms of the GNU Lesser General Public
41563// License as published by the Free Software Foundation; either
41564// version 3.0 of the License, or (at your option) any later version.
41565//
41566// This library is distributed in the hope that it will be useful,
41567// but WITHOUT ANY WARRANTY; without even the implied warranty of
41568// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
41569// Lesser General Public License for more details.
41570//
41571// You should have received a copy of the GNU Lesser General Public
41572// License along with this library; if not, write to the Free Software
41573// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
41574
41575/**
41576 * Implementation of the String-to-key specifier
41577 *
41578 * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}:
41579 * String-to-key (S2K) specifiers are used to convert passphrase strings
41580 * into symmetric-key encryption/decryption keys.  They are used in two
41581 * places, currently: to encrypt the secret part of private keys in the
41582 * private keyring, and to convert passphrases to encryption keys for
41583 * symmetrically encrypted messages.
41584 * @requires config
41585 * @requires crypto
41586 * @requires enums
41587 * @requires util
41588 * @module type/s2k
41589 */
41590
41591function S2K() {
41592  /** @type {module:enums.hash} */
41593  this.algorithm = 'sha256';
41594  /** @type {module:enums.s2k} */
41595  this.type = 'iterated';
41596  /** @type {Integer} */
41597  this.c = _config2.default.s2k_iteration_count_byte;
41598  /** Eight bytes of salt in a binary string.
41599   * @type {String}
41600   */
41601  this.salt = null;
41602}
41603
41604S2K.prototype.get_count = function () {
41605  // Exponent bias, defined in RFC4880
41606  const expbias = 6;
41607
41608  return 16 + (this.c & 15) << (this.c >> 4) + expbias;
41609};
41610
41611/**
41612 * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).
41613 * @param {String} input Payload of string-to-key specifier
41614 * @returns {Integer} Actual length of the object
41615 */
41616S2K.prototype.read = function (bytes) {
41617  let i = 0;
41618  this.type = _enums2.default.read(_enums2.default.s2k, bytes[i++]);
41619  this.algorithm = bytes[i++];
41620  if (this.type !== 'gnu') {
41621    this.algorithm = _enums2.default.read(_enums2.default.hash, this.algorithm);
41622  }
41623
41624  switch (this.type) {
41625    case 'simple':
41626      break;
41627
41628    case 'salted':
41629      this.salt = bytes.subarray(i, i + 8);
41630      i += 8;
41631      break;
41632
41633    case 'iterated':
41634      this.salt = bytes.subarray(i, i + 8);
41635      i += 8;
41636
41637      // Octet 10: count, a one-octet, coded value
41638      this.c = bytes[i++];
41639      break;
41640
41641    case 'gnu':
41642      if (_util2.default.Uint8Array_to_str(bytes.subarray(i, i + 3)) === "GNU") {
41643        i += 3; // GNU
41644        const gnuExtType = 1000 + bytes[i++];
41645        if (gnuExtType === 1001) {
41646          this.type = 'gnu-dummy';
41647          // GnuPG extension mode 1001 -- don't write secret key at all
41648        } else {
41649          throw new Error("Unknown s2k gnu protection mode.");
41650        }
41651      } else {
41652        throw new Error("Unknown s2k type.");
41653      }
41654      break;
41655
41656    default:
41657      throw new Error("Unknown s2k type.");
41658  }
41659
41660  return i;
41661};
41662
41663/**
41664 * Serializes s2k information
41665 * @returns {Uint8Array} binary representation of s2k
41666 */
41667S2K.prototype.write = function () {
41668  const arr = [new Uint8Array([_enums2.default.write(_enums2.default.s2k, this.type), _enums2.default.write(_enums2.default.hash, this.algorithm)])];
41669
41670  switch (this.type) {
41671    case 'simple':
41672      break;
41673    case 'salted':
41674      arr.push(this.salt);
41675      break;
41676    case 'iterated':
41677      arr.push(this.salt);
41678      arr.push(new Uint8Array([this.c]));
41679      break;
41680    case 'gnu':
41681      throw new Error("GNU s2k type not supported.");
41682    default:
41683      throw new Error("Unknown s2k type.");
41684  }
41685
41686  return _util2.default.concatUint8Array(arr);
41687};
41688
41689/**
41690 * Produces a key using the specified passphrase and the defined
41691 * hashAlgorithm
41692 * @param {String} passphrase Passphrase containing user input
41693 * @returns {Uint8Array} Produced key with a length corresponding to
41694 * hashAlgorithm hash length
41695 */
41696S2K.prototype.produce_key = async function (passphrase, numBytes) {
41697  passphrase = _util2.default.encode_utf8(passphrase);
41698
41699  async function round(prefix, s2k) {
41700    const algorithm = _enums2.default.write(_enums2.default.hash, s2k.algorithm);
41701
41702    switch (s2k.type) {
41703      case 'simple':
41704        return _crypto2.default.hash.digest(algorithm, _util2.default.concatUint8Array([prefix, passphrase]));
41705
41706      case 'salted':
41707        return _crypto2.default.hash.digest(algorithm, _util2.default.concatUint8Array([prefix, s2k.salt, passphrase]));
41708
41709      case 'iterated':
41710        {
41711          const count = s2k.get_count();
41712          const data = _util2.default.concatUint8Array([s2k.salt, passphrase]);
41713          const datalen = data.length;
41714          const isp = new Uint8Array(prefix.length + count + datalen);
41715          isp.set(prefix);
41716          for (let pos = prefix.length; pos < count; pos += datalen) {
41717            isp.set(data, pos);
41718          }
41719          return _crypto2.default.hash.digest(algorithm, isp.subarray(0, prefix.length + count));
41720        }
41721      case 'gnu':
41722        throw new Error("GNU s2k type not supported.");
41723
41724      default:
41725        throw new Error("Unknown s2k type.");
41726    }
41727  }
41728
41729  const arr = [];
41730  let rlength = 0;
41731  const prefix = new Uint8Array(numBytes);
41732
41733  for (let i = 0; i < numBytes; i++) {
41734    prefix[i] = 0;
41735  }
41736
41737  let i = 0;
41738  while (rlength < numBytes) {
41739    const result = await round(prefix.subarray(0, i), this);
41740    arr.push(result);
41741    rlength += result.length;
41742    i++;
41743  }
41744
41745  return _util2.default.concatUint8Array(arr).subarray(0, numBytes);
41746};
41747
41748S2K.fromClone = function (clone) {
41749  const s2k = new S2K();
41750  s2k.algorithm = clone.algorithm;
41751  s2k.type = clone.type;
41752  s2k.c = clone.c;
41753  s2k.salt = clone.salt;
41754  return s2k;
41755};
41756
41757exports.default = S2K;
41758
41759},{"../config":80,"../crypto":95,"../enums.js":114,"../util.js":153}],153:[function(require,module,exports){
41760'use strict';
41761
41762Object.defineProperty(exports, "__esModule", {
41763  value: true
41764});
41765
41766var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); // GPG4Browsers - An OpenPGP implementation in javascript
41767// Copyright (C) 2011 Recurity Labs GmbH
41768//
41769// This library is free software; you can redistribute it and/or
41770// modify it under the terms of the GNU Lesser General Public
41771// License as published by the Free Software Foundation; either
41772// version 3.0 of the License, or (at your option) any later version.
41773//
41774// This library is distributed in the hope that it will be useful,
41775// but WITHOUT ANY WARRANTY; without even the implied warranty of
41776// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
41777// Lesser General Public License for more details.
41778//
41779// You should have received a copy of the GNU Lesser General Public
41780// License along with this library; if not, write to the Free Software
41781// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
41782
41783/* eslint-disable no-console */
41784
41785/**
41786 * This object contains utility functions
41787 * @requires address-rfc2822
41788 * @requires web-stream-tools
41789 * @requires config
41790 * @requires encoding/base64
41791 * @module util
41792 */
41793
41794// re-import module to access util functions
41795
41796
41797var _addressRfc = require('address-rfc2822');
41798
41799var _addressRfc2 = _interopRequireDefault(_addressRfc);
41800
41801var _webStreamTools = require('web-stream-tools');
41802
41803var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
41804
41805var _config = require('./config');
41806
41807var _config2 = _interopRequireDefault(_config);
41808
41809var _util = require('./util');
41810
41811var _util2 = _interopRequireDefault(_util);
41812
41813var _base = require('./encoding/base64');
41814
41815var _base2 = _interopRequireDefault(_base);
41816
41817function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
41818
41819exports.default = {
41820  isString: function isString(data) {
41821    return typeof data === 'string' || String.prototype.isPrototypeOf(data);
41822  },
41823
41824  isArray: function isArray(data) {
41825    return Array.prototype.isPrototypeOf(data);
41826  },
41827
41828  isUint8Array: _webStreamTools2.default.isUint8Array,
41829
41830  isStream: _webStreamTools2.default.isStream,
41831
41832  /**
41833   * Get transferable objects to pass buffers with zero copy (similar to "pass by reference" in C++)
41834   *   See: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage
41835   * Also, convert ReadableStreams to MessagePorts
41836   * @param  {Object} obj           the options object to be passed to the web worker
41837   * @returns {Array<ArrayBuffer>}   an array of binary data to be passed
41838   */
41839  getTransferables: function getTransferables(obj, zero_copy) {
41840    const transferables = [];
41841    _util2.default.collectTransferables(obj, transferables, zero_copy);
41842    return transferables.length ? transferables : undefined;
41843  },
41844
41845  collectTransferables: function collectTransferables(obj, collection, zero_copy) {
41846    if (!obj) {
41847      return;
41848    }
41849
41850    if (_util2.default.isUint8Array(obj)) {
41851      if (zero_copy && collection.indexOf(obj.buffer) === -1 && !(navigator.userAgent.indexOf('Version/11.1') !== -1 || // Safari 11.1
41852      (navigator.userAgent.match(/Chrome\/(\d+)/) || [])[1] < 56 && navigator.userAgent.indexOf('Edge') === -1 // Chrome < 56
41853      )) {
41854        collection.push(obj.buffer);
41855      }
41856      return;
41857    }
41858    if (Object.prototype.isPrototypeOf(obj)) {
41859      Object.entries(obj).forEach(([key, value]) => {
41860        // recursively search all children
41861        if (_util2.default.isStream(value)) {
41862          if (value.locked) {
41863            obj[key] = null;
41864          } else {
41865            const transformed = _webStreamTools2.default.transformPair(value, async readable => {
41866              const reader = _webStreamTools2.default.getReader(readable);
41867
41868              var _ref = new MessageChannel();
41869
41870              const port1 = _ref.port1,
41871                    port2 = _ref.port2;
41872
41873              port1.onmessage = async function ({ data: { action } }) {
41874                if (action === 'read') {
41875                  try {
41876                    const result = await reader.read();
41877                    port1.postMessage(result, _util2.default.getTransferables(result));
41878                  } catch (e) {
41879                    port1.postMessage({ error: e.message });
41880                  }
41881                } else if (action === 'cancel') {
41882                  await transformed.cancel();
41883                  port1.postMessage();
41884                }
41885              };
41886              obj[key] = port2;
41887              collection.push(port2);
41888            });
41889          }
41890          return;
41891        }
41892        if (Object.prototype.toString.call(value) === '[object MessagePort]') {
41893          throw new Error("Can't transfer the same stream twice.");
41894        }
41895        _util2.default.collectTransferables(value, collection, zero_copy);
41896      });
41897    }
41898  },
41899
41900  /**
41901   * Convert MessagePorts back to ReadableStreams
41902   * @param  {Object} obj
41903   * @returns {Object}
41904   */
41905  restoreStreams: function restoreStreams(obj) {
41906    if (Object.prototype.isPrototypeOf(obj) && !Uint8Array.prototype.isPrototypeOf(obj)) {
41907      Object.entries(obj).forEach(([key, value]) => {
41908        // recursively search all children
41909        if (Object.prototype.toString.call(value) === '[object MessagePort]') {
41910          obj[key] = new ReadableStream({
41911            pull(controller) {
41912              return new Promise(resolve => {
41913                value.onmessage = evt => {
41914                  var _evt$data = evt.data;
41915                  const done = _evt$data.done,
41916                        value = _evt$data.value,
41917                        error = _evt$data.error;
41918
41919                  if (error) {
41920                    controller.error(new Error(error));
41921                  } else if (!done) {
41922                    controller.enqueue(value);
41923                  } else {
41924                    controller.close();
41925                  }
41926                  resolve();
41927                };
41928                value.postMessage({ action: 'read' });
41929              });
41930            },
41931            cancel() {
41932              return new Promise(resolve => {
41933                value.onmessage = resolve;
41934                value.postMessage({ action: 'cancel' });
41935              });
41936            }
41937          }, { highWaterMark: 0 });
41938          return;
41939        }
41940        _util2.default.restoreStreams(value);
41941      });
41942    }
41943    return obj;
41944  },
41945
41946  readNumber: function readNumber(bytes) {
41947    let n = 0;
41948    for (let i = 0; i < bytes.length; i++) {
41949      n += 256 ** i * bytes[bytes.length - 1 - i];
41950    }
41951    return n;
41952  },
41953
41954  writeNumber: function writeNumber(n, bytes) {
41955    const b = new Uint8Array(bytes);
41956    for (let i = 0; i < bytes; i++) {
41957      b[i] = n >> 8 * (bytes - i - 1) & 0xFF;
41958    }
41959
41960    return b;
41961  },
41962
41963  readDate: function readDate(bytes) {
41964    const n = _util2.default.readNumber(bytes);
41965    const d = new Date(n * 1000);
41966    return d;
41967  },
41968
41969  writeDate: function writeDate(time) {
41970    const numeric = Math.floor(time.getTime() / 1000);
41971
41972    return _util2.default.writeNumber(numeric, 4);
41973  },
41974
41975  normalizeDate: function normalizeDate(time = Date.now()) {
41976    return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);
41977  },
41978
41979  /**
41980   * Create hex string from a binary
41981   * @param {String} str String to convert
41982   * @returns {String} String containing the hexadecimal values
41983   */
41984  str_to_hex: function str_to_hex(str) {
41985    if (str === null) {
41986      return "";
41987    }
41988    const r = [];
41989    const e = str.length;
41990    let c = 0;
41991    let h;
41992    while (c < e) {
41993      h = str.charCodeAt(c++).toString(16);
41994      while (h.length < 2) {
41995        h = "0" + h;
41996      }
41997      r.push("" + h);
41998    }
41999    return r.join('');
42000  },
42001
42002  /**
42003   * Create binary string from a hex encoded string
42004   * @param {String} str Hex string to convert
42005   * @returns {String}
42006   */
42007  hex_to_str: function hex_to_str(hex) {
42008    let str = '';
42009    for (let i = 0; i < hex.length; i += 2) {
42010      str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
42011    }
42012    return str;
42013  },
42014
42015  /**
42016   * Convert a Uint8Array to an MPI-formatted Uint8Array.
42017   * Note: the output is **not** an MPI object.
42018   * @see {@link module:type/mpi/MPI.fromUint8Array}
42019   * @see {@link module:type/mpi/MPI.toUint8Array}
42020   * @param {Uint8Array} bin An array of 8-bit integers to convert
42021   * @returns {Uint8Array} MPI-formatted Uint8Array
42022   */
42023  Uint8Array_to_MPI: function Uint8Array_to_MPI(bin) {
42024    const size = (bin.length - 1) * 8 + _util2.default.nbits(bin[0]);
42025    const prefix = Uint8Array.from([(size & 0xFF00) >> 8, size & 0xFF]);
42026    return _util2.default.concatUint8Array([prefix, bin]);
42027  },
42028
42029  /**
42030   * Convert a Base-64 encoded string an array of 8-bit integer
42031   *
42032   * Note: accepts both Radix-64 and URL-safe strings
42033   * @param {String} base64 Base-64 encoded string to convert
42034   * @returns {Uint8Array} An array of 8-bit integers
42035   */
42036  b64_to_Uint8Array: function b64_to_Uint8Array(base64) {
42037    return _base2.default.decode(base64.replace(/-/g, '+').replace(/_/g, '/'));
42038  },
42039
42040  /**
42041   * Convert an array of 8-bit integer to a Base-64 encoded string
42042   * @param {Uint8Array} bytes An array of 8-bit integers to convert
42043   * @param {bool}       url   If true, output is URL-safe
42044   * @returns {String}          Base-64 encoded string
42045   */
42046  Uint8Array_to_b64: function Uint8Array_to_b64(bytes, url) {
42047    return _base2.default.encode(bytes, url).replace(/(\n)/g, '');
42048  },
42049
42050  /**
42051   * Convert a hex string to an array of 8-bit integers
42052   * @param {String} hex  A hex string to convert
42053   * @returns {Uint8Array} An array of 8-bit integers
42054   */
42055  hex_to_Uint8Array: function hex_to_Uint8Array(hex) {
42056    const result = new Uint8Array(hex.length >> 1);
42057    for (let k = 0; k < hex.length >> 1; k++) {
42058      result[k] = parseInt(hex.substr(k << 1, 2), 16);
42059    }
42060    return result;
42061  },
42062
42063  /**
42064   * Convert an array of 8-bit integers to a hex string
42065   * @param {Uint8Array} bytes Array of 8-bit integers to convert
42066   * @returns {String} Hexadecimal representation of the array
42067   */
42068  Uint8Array_to_hex: function Uint8Array_to_hex(bytes) {
42069    const r = [];
42070    const e = bytes.length;
42071    let c = 0;
42072    let h;
42073    while (c < e) {
42074      h = bytes[c++].toString(16);
42075      while (h.length < 2) {
42076        h = "0" + h;
42077      }
42078      r.push("" + h);
42079    }
42080    return r.join('');
42081  },
42082
42083  /**
42084   * Convert a string to an array of 8-bit integers
42085   * @param {String} str String to convert
42086   * @returns {Uint8Array} An array of 8-bit integers
42087   */
42088  str_to_Uint8Array: function str_to_Uint8Array(str) {
42089    return _webStreamTools2.default.transform(str, str => {
42090      if (!_util2.default.isString(str)) {
42091        throw new Error('str_to_Uint8Array: Data must be in the form of a string');
42092      }
42093
42094      const result = new Uint8Array(str.length);
42095      for (let i = 0; i < str.length; i++) {
42096        result[i] = str.charCodeAt(i);
42097      }
42098      return result;
42099    });
42100  },
42101
42102  /**
42103   * Convert an array of 8-bit integers to a string
42104   * @param {Uint8Array} bytes An array of 8-bit integers to convert
42105   * @returns {String} String representation of the array
42106   */
42107  Uint8Array_to_str: function Uint8Array_to_str(bytes) {
42108    bytes = new Uint8Array(bytes);
42109    const result = [];
42110    const bs = 1 << 14;
42111    const j = bytes.length;
42112
42113    for (let i = 0; i < j; i += bs) {
42114      result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));
42115    }
42116    return result.join('');
42117  },
42118
42119  /**
42120   * Convert a native javascript string to a Uint8Array of utf8 bytes
42121   * @param {String|ReadableStream} str The string to convert
42122   * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes
42123   */
42124  encode_utf8: function encode_utf8(str) {
42125    const encoder = new TextEncoder('utf-8');
42126    // eslint-disable-next-line no-inner-declarations
42127    function process(value, lastChunk = false) {
42128      return encoder.encode(value, { stream: !lastChunk });
42129    }
42130    return _webStreamTools2.default.transform(str, process, () => process('', true));
42131  },
42132
42133  /**
42134   * Convert a Uint8Array of utf8 bytes to a native javascript string
42135   * @param {Uint8Array|ReadableStream} utf8 A valid squence of utf8 bytes
42136   * @returns {String|ReadableStream} A native javascript string
42137   */
42138  decode_utf8: function decode_utf8(utf8) {
42139    const decoder = new TextDecoder('utf-8');
42140    // eslint-disable-next-line no-inner-declarations
42141    function process(value, lastChunk = false) {
42142      return decoder.decode(value, { stream: !lastChunk });
42143    }
42144    return _webStreamTools2.default.transform(utf8, process, () => process(new Uint8Array(), true));
42145  },
42146
42147  /**
42148   * Concat a list of Uint8Arrays, Strings or Streams
42149   * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
42150   * @param {Array<Uint8Array|String|ReadableStream>} Array of Uint8Arrays/Strings/Streams to concatenate
42151   * @returns {Uint8Array|String|ReadableStream} Concatenated array
42152   */
42153  concat: _webStreamTools2.default.concat,
42154
42155  /**
42156   * Concat Uint8Arrays
42157   * @param {Array<Uint8Array>} Array of Uint8Arrays to concatenate
42158   * @returns {Uint8Array} Concatenated array
42159   */
42160  concatUint8Array: _webStreamTools2.default.concatUint8Array,
42161
42162  /**
42163   * Check Uint8Array equality
42164   * @param {Uint8Array} first array
42165   * @param {Uint8Array} second array
42166   * @returns {Boolean} equality
42167   */
42168  equalsUint8Array: function equalsUint8Array(array1, array2) {
42169    if (!_util2.default.isUint8Array(array1) || !_util2.default.isUint8Array(array2)) {
42170      throw new Error('Data must be in the form of a Uint8Array');
42171    }
42172
42173    if (array1.length !== array2.length) {
42174      return false;
42175    }
42176
42177    for (let i = 0; i < array1.length; i++) {
42178      if (array1[i] !== array2[i]) {
42179        return false;
42180      }
42181    }
42182    return true;
42183  },
42184
42185  /**
42186   * Calculates a 16bit sum of a Uint8Array by adding each character
42187   * codes modulus 65535
42188   * @param {Uint8Array} Uint8Array to create a sum of
42189   * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535
42190   */
42191  write_checksum: function write_checksum(text) {
42192    let s = 0;
42193    for (let i = 0; i < text.length; i++) {
42194      s = s + text[i] & 0xFFFF;
42195    }
42196    return _util2.default.writeNumber(s, 2);
42197  },
42198
42199  /**
42200   * Helper function to print a debug message. Debug
42201   * messages are only printed if
42202   * @link module:config/config.debug is set to true.
42203   * @param {String} str String of the debug message
42204   */
42205  print_debug: function print_debug(str) {
42206    if (_config2.default.debug) {
42207      console.log(str);
42208    }
42209  },
42210
42211  /**
42212   * Helper function to print a debug message. Debug
42213   * messages are only printed if
42214   * @link module:config/config.debug is set to true.
42215   * Different than print_debug because will call Uint8Array_to_hex iff necessary.
42216   * @param {String} str String of the debug message
42217   */
42218  print_debug_hexarray_dump: function print_debug_hexarray_dump(str, arrToHex) {
42219    if (_config2.default.debug) {
42220      str += ': ' + _util2.default.Uint8Array_to_hex(arrToHex);
42221      console.log(str);
42222    }
42223  },
42224
42225  /**
42226   * Helper function to print a debug message. Debug
42227   * messages are only printed if
42228   * @link module:config/config.debug is set to true.
42229   * Different than print_debug because will call str_to_hex iff necessary.
42230   * @param {String} str String of the debug message
42231   */
42232  print_debug_hexstr_dump: function print_debug_hexstr_dump(str, strToHex) {
42233    if (_config2.default.debug) {
42234      str += _util2.default.str_to_hex(strToHex);
42235      console.log(str);
42236    }
42237  },
42238
42239  /**
42240   * Helper function to print a debug error. Debug
42241   * messages are only printed if
42242   * @link module:config/config.debug is set to true.
42243   * @param {String} str String of the debug message
42244   */
42245  print_debug_error: function print_debug_error(error) {
42246    if (_config2.default.debug) {
42247      console.error(error);
42248    }
42249  },
42250
42251  /**
42252   * Read a stream to the end and print it to the console when it's closed.
42253   * @param {String} str String of the debug message
42254   * @param {ReadableStream|Uint8array|String} input Stream to print
42255   * @param {Function} concat Function to concatenate chunks of the stream (defaults to util.concat).
42256   */
42257  print_entire_stream: function print_entire_stream(str, input, concat) {
42258    _webStreamTools2.default.readToEnd(_webStreamTools2.default.clone(input), concat).then(result => {
42259      console.log(str + ': ', result);
42260    });
42261  },
42262
42263  getLeftNBits: function getLeftNBits(array, bitcount) {
42264    const rest = bitcount % 8;
42265    if (rest === 0) {
42266      return array.subarray(0, bitcount / 8);
42267    }
42268    const bytes = (bitcount - rest) / 8 + 1;
42269    const result = array.subarray(0, bytes);
42270    return _util2.default.shiftRight(result, 8 - rest); // +String.fromCharCode(string.charCodeAt(bytes -1) << (8-rest) & 0xFF);
42271  },
42272
42273  // returns bit length of the integer x
42274  nbits: function nbits(x) {
42275    let r = 1;
42276    let t = x >>> 16;
42277    if (t !== 0) {
42278      x = t;
42279      r += 16;
42280    }
42281    t = x >> 8;
42282    if (t !== 0) {
42283      x = t;
42284      r += 8;
42285    }
42286    t = x >> 4;
42287    if (t !== 0) {
42288      x = t;
42289      r += 4;
42290    }
42291    t = x >> 2;
42292    if (t !== 0) {
42293      x = t;
42294      r += 2;
42295    }
42296    t = x >> 1;
42297    if (t !== 0) {
42298      x = t;
42299      r += 1;
42300    }
42301    return r;
42302  },
42303
42304  /**
42305   * If S[1] == 0, then double(S) == (S[2..128] || 0);
42306   * otherwise, double(S) == (S[2..128] || 0) xor
42307   * (zeros(120) || 10000111).
42308   *
42309   * Both OCB and EAX (through CMAC) require this function to be constant-time.
42310   *
42311   * @param {Uint8Array} data
42312   */
42313  double: function double(data) {
42314    const double_var = new Uint8Array(data.length);
42315    const last = data.length - 1;
42316    for (let i = 0; i < last; i++) {
42317      double_var[i] = data[i] << 1 ^ data[i + 1] >> 7;
42318    }
42319    double_var[last] = data[last] << 1 ^ (data[0] >> 7) * 0x87;
42320    return double_var;
42321  },
42322
42323  /**
42324   * Shift a Uint8Array to the right by n bits
42325   * @param {Uint8Array} array The array to shift
42326   * @param {Integer} bits Amount of bits to shift (MUST be smaller
42327   * than 8)
42328   * @returns {String} Resulting array.
42329   */
42330  shiftRight: function shiftRight(array, bits) {
42331    if (bits) {
42332      for (let i = array.length - 1; i >= 0; i--) {
42333        array[i] >>= bits;
42334        if (i > 0) {
42335          array[i] |= array[i - 1] << 8 - bits;
42336        }
42337      }
42338    }
42339    return array;
42340  },
42341
42342  /**
42343   * Get native Web Cryptography api, only the current version of the spec.
42344   * The default configuration is to use the api when available. But it can
42345   * be deactivated with config.use_native
42346   * @returns {Object}   The SubtleCrypto api or 'undefined'
42347   */
42348  getWebCrypto: function getWebCrypto() {
42349    if (!_config2.default.use_native) {
42350      return;
42351    }
42352
42353    return typeof window !== 'undefined' && window.crypto && window.crypto.subtle;
42354  },
42355
42356  /**
42357   * Get native Web Cryptography api for all browsers, including legacy
42358   * implementations of the spec e.g IE11 and Safari 8/9. The default
42359   * configuration is to use the api when available. But it can be deactivated
42360   * with config.use_native
42361   * @returns {Object}   The SubtleCrypto api or 'undefined'
42362   */
42363  getWebCryptoAll: function getWebCryptoAll() {
42364    if (!_config2.default.use_native) {
42365      return;
42366    }
42367
42368    if (typeof window !== 'undefined') {
42369      if (window.crypto) {
42370        return window.crypto.subtle || window.crypto.webkitSubtle;
42371      }
42372      if (window.msCrypto) {
42373        return window.msCrypto.subtle;
42374      }
42375    }
42376  },
42377
42378  /**
42379   * Detect Node.js runtime.
42380   */
42381  detectNode: function detectNode() {
42382    return typeof window === 'undefined';
42383  },
42384
42385  /**
42386   * Get native Node.js module
42387   * @param {String}     The module to require
42388   * @returns {Object}   The required module or 'undefined'
42389   */
42390  nodeRequire: function nodeRequire(module) {
42391    if (!_util2.default.detectNode()) {
42392      return;
42393    }
42394
42395    // Requiring the module dynamically allows us to access the native node module.
42396    // otherwise, it gets replaced with the browserified version
42397    // eslint-disable-next-line import/no-dynamic-require
42398    return require(module);
42399  },
42400
42401  /**
42402   * Get native Node.js crypto api. The default configuration is to use
42403   * the api when available. But it can also be deactivated with config.use_native
42404   * @returns {Object}   The crypto module or 'undefined'
42405   */
42406  getNodeCrypto: function getNodeCrypto() {
42407    if (!_config2.default.use_native) {
42408      return;
42409    }
42410
42411    return _util2.default.nodeRequire('crypto');
42412  },
42413
42414  getNodeZlib: function getNodeZlib() {
42415    if (!_config2.default.use_native) {
42416      return;
42417    }
42418
42419    return _util2.default.nodeRequire('zlib');
42420  },
42421
42422  /**
42423   * Get native Node.js Buffer constructor. This should be used since
42424   * Buffer is not available under browserify.
42425   * @returns {Function}   The Buffer constructor or 'undefined'
42426   */
42427  getNodeBuffer: function getNodeBuffer() {
42428    return (_util2.default.nodeRequire('buffer') || {}).Buffer;
42429  },
42430
42431  getNodeStream: function getNodeStream() {
42432    return (_util2.default.nodeRequire('stream') || {}).Readable;
42433  },
42434
42435  getHardwareConcurrency: function getHardwareConcurrency() {
42436    if (_util2.default.detectNode()) {
42437      const os = _util2.default.nodeRequire('os');
42438      return os.cpus().length;
42439    }
42440
42441    return navigator.hardwareConcurrency || 1;
42442  },
42443
42444  isEmailAddress: function isEmailAddress(data) {
42445    if (!_util2.default.isString(data)) {
42446      return false;
42447    }
42448    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,}|xn--[a-zA-Z\-0-9]+)))$/;
42449    return re.test(data);
42450  },
42451
42452  /**
42453   * Format user id for internal use.
42454   */
42455  formatUserId: function formatUserId(id) {
42456    // name, email address and comment can be empty but must be of the correct type
42457    if (id.name && !_util2.default.isString(id.name) || id.email && !_util2.default.isEmailAddress(id.email) || id.comment && !_util2.default.isString(id.comment)) {
42458      throw new Error('Invalid user id format');
42459    }
42460    const components = [];
42461    if (id.name) {
42462      components.push(id.name);
42463    }
42464    if (id.comment) {
42465      components.push(`(${id.comment})`);
42466    }
42467    if (id.email) {
42468      components.push(`<${id.email}>`);
42469    }
42470    return components.join(' ');
42471  },
42472
42473  /**
42474   * Parse user id.
42475   */
42476  parseUserId: function parseUserId(userid) {
42477    if (userid.length > _config2.default.max_userid_length) {
42478      throw new Error('User id string is too long');
42479    }
42480    try {
42481      var _rfc2822$parse = _addressRfc2.default.parse(userid),
42482          _rfc2822$parse2 = _slicedToArray(_rfc2822$parse, 1),
42483          _rfc2822$parse2$ = _rfc2822$parse2[0];
42484
42485      const name = _rfc2822$parse2$.phrase,
42486            email = _rfc2822$parse2$.address,
42487            comment = _rfc2822$parse2$.comment;
42488
42489      return { name, email, comment: comment.replace(/^\(|\)$/g, '') };
42490    } catch (e) {
42491      throw new Error('Invalid user id format');
42492    }
42493  },
42494
42495  /**
42496   * Normalize line endings to \r\n
42497   */
42498  canonicalizeEOL: function canonicalizeEOL(text) {
42499    return _webStreamTools2.default.transform(_util2.default.nativeEOL(text), value => value.replace(/\r/g, "\n").replace(/\n/g, "\r\n"));
42500  },
42501
42502  /**
42503   * Convert line endings from canonicalized \r\n to native \n
42504   */
42505  nativeEOL: function nativeEOL(text) {
42506    let lastChar = '';
42507    return _webStreamTools2.default.transform(text, value => {
42508      value = lastChar + value;
42509      if (value[value.length - 1] === '\r') {
42510        lastChar = '\r';
42511        value = value.slice(0, -1);
42512      } else {
42513        lastChar = '';
42514      }
42515      return value.replace(/\r\n/g, '\n');
42516    }, () => lastChar);
42517  },
42518
42519  /**
42520   * Remove trailing spaces and tabs from each line
42521   */
42522  removeTrailingSpaces: function removeTrailingSpaces(text) {
42523    return text.split('\n').map(line => {
42524      let i = line.length - 1;
42525      for (; i >= 0 && (line[i] === ' ' || line[i] === '\t'); i--);
42526      return line.substr(0, i + 1);
42527    }).join('\n');
42528  },
42529
42530  /**
42531   * Encode input buffer using Z-Base32 encoding.
42532   * See: https://tools.ietf.org/html/rfc6189#section-5.1.6
42533   *
42534   * @param {Uint8Array} data The binary data to encode
42535   * @returns {String} Binary data encoded using Z-Base32
42536   */
42537  encodeZBase32: function encodeZBase32(data) {
42538    if (data.length === 0) {
42539      return "";
42540    }
42541    const ALPHABET = "ybndrfg8ejkmcpqxot1uwisza345h769";
42542    const SHIFT = 5;
42543    const MASK = 31;
42544    let buffer = data[0];
42545    let index = 1;
42546    let bitsLeft = 8;
42547    let result = '';
42548    while (bitsLeft > 0 || index < data.length) {
42549      if (bitsLeft < SHIFT) {
42550        if (index < data.length) {
42551          buffer <<= 8;
42552          buffer |= data[index++] & 0xff;
42553          bitsLeft += 8;
42554        } else {
42555          const pad = SHIFT - bitsLeft;
42556          buffer <<= pad;
42557          bitsLeft += pad;
42558        }
42559      }
42560      bitsLeft -= SHIFT;
42561      result += ALPHABET[MASK & buffer >> bitsLeft];
42562    }
42563    return result;
42564  }
42565};
42566
42567},{"./config":80,"./encoding/base64":113,"./util":153,"address-rfc2822":2,"web-stream-tools":76}],154:[function(require,module,exports){
42568'use strict';
42569
42570Object.defineProperty(exports, "__esModule", {
42571  value: true
42572});
42573
42574var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); // OpenPGP.js - An OpenPGP implementation in javascript
42575// Copyright (C) 2018 Wiktor Kwapisiewicz
42576//
42577// This library is free software; you can redistribute it and/or
42578// modify it under the terms of the GNU Lesser General Public
42579// License as published by the Free Software Foundation; either
42580// version 3.0 of the License, or (at your option) any later version.
42581//
42582// This library is distributed in the hope that it will be useful,
42583// but WITHOUT ANY WARRANTY; without even the implied warranty of
42584// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
42585// Lesser General Public License for more details.
42586//
42587// You should have received a copy of the GNU Lesser General Public
42588// License along with this library; if not, write to the Free Software
42589// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
42590
42591/**
42592 * @fileoverview This class implements a client for the Web Key Directory (wkd) protocol
42593 * in order to lookup keys on designated servers.
42594 * See: https://datatracker.ietf.org/doc/draft-koch-openpgp-webkey-service/
42595 * @module wkd
42596 */
42597
42598var _util = require('./util');
42599
42600var _util2 = _interopRequireDefault(_util);
42601
42602var _crypto = require('./crypto');
42603
42604var _crypto2 = _interopRequireDefault(_crypto);
42605
42606var _key = require('./key');
42607
42608var keyMod = _interopRequireWildcard(_key);
42609
42610function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
42611
42612function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
42613
42614/**
42615 * Initialize the WKD client
42616 * @constructor
42617 */
42618function WKD() {
42619  this._fetch = typeof window !== 'undefined' ? window.fetch : require('node-fetch');
42620}
42621
42622/**
42623 * Search for a public key using Web Key Directory protocol.
42624 * @param   {String}   options.email         User's email.
42625 * @param   {Boolean}  options.rawBytes      Returns Uint8Array instead of parsed key.
42626 * @returns {Promise<Uint8Array|
42627 *           {keys: Array<module:key.Key>,
42628 *            err: (Array<Error>|null)}>}     The public key.
42629 * @async
42630 */
42631WKD.prototype.lookup = async function (options) {
42632  const fetch = this._fetch;
42633
42634  if (!options.email) {
42635    throw new Error('You must provide an email parameter!');
42636  }
42637
42638  if (!_util2.default.isEmailAddress(options.email)) {
42639    throw new Error('Invalid e-mail address.');
42640  }
42641
42642  var _$exec = /(.*)@(.*)/.exec(options.email),
42643      _$exec2 = _slicedToArray(_$exec, 3);
42644
42645  const localPart = _$exec2[1],
42646        domain = _$exec2[2];
42647
42648  const localEncoded = _util2.default.encodeZBase32((await _crypto2.default.hash.sha1(_util2.default.str_to_Uint8Array(localPart.toLowerCase()))));
42649
42650  const url = `https://${domain}/.well-known/openpgpkey/hu/${localEncoded}`;
42651
42652  return fetch(url).then(function (response) {
42653    if (response.status === 200) {
42654      return response.arrayBuffer();
42655    }
42656  }).then(function (publicKey) {
42657    if (publicKey) {
42658      const rawBytes = new Uint8Array(publicKey);
42659      if (options.rawBytes) {
42660        return rawBytes;
42661      }
42662      return keyMod.read(rawBytes);
42663    }
42664  });
42665};
42666
42667exports.default = WKD;
42668
42669},{"./crypto":95,"./key":117,"./util":153,"node-fetch":"node-fetch"}],155:[function(require,module,exports){
42670'use strict';
42671
42672Object.defineProperty(exports, "__esModule", {
42673  value: true
42674});
42675
42676var _util = require('../util.js');
42677
42678var _util2 = _interopRequireDefault(_util);
42679
42680var _config = require('../config');
42681
42682var _config2 = _interopRequireDefault(_config);
42683
42684var _crypto = require('../crypto');
42685
42686var _crypto2 = _interopRequireDefault(_crypto);
42687
42688var _packet = require('../packet');
42689
42690var _packet2 = _interopRequireDefault(_packet);
42691
42692function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
42693
42694/**
42695 * Initializes a new proxy and loads the web worker
42696 * @param {String} path            The path to the worker or 'openpgp.worker.js' by default
42697 * @param {Number} n               number of workers to initialize if path given
42698 * @param {Object} config          config The worker configuration
42699 * @param {Array<Object>} worker   alternative to path parameter: web worker initialized with 'openpgp.worker.js'
42700 * @constructor
42701 */
42702// GPG4Browsers - An OpenPGP implementation in javascript
42703// Copyright (C) 2011 Recurity Labs GmbH
42704//
42705// This library is free software; you can redistribute it and/or
42706// modify it under the terms of the GNU Lesser General Public
42707// License as published by the Free Software Foundation; either
42708// version 3.0 of the License, or (at your option) any later version.
42709//
42710// This library is distributed in the hope that it will be useful,
42711// but WITHOUT ANY WARRANTY; without even the implied warranty of
42712// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
42713// Lesser General Public License for more details.
42714//
42715// You should have received a copy of the GNU Lesser General Public
42716// License along with this library; if not, write to the Free Software
42717// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
42718
42719/**
42720 * @fileoverview Provides functions for maintaining browser workers
42721 * @see module:openpgp.initWorker
42722 * @see module:openpgp.getWorker
42723 * @see module:openpgp.destroyWorker
42724 * @see module:worker/worker
42725 * @requires util
42726 * @requires config
42727 * @requires crypto
42728 * @requires packet
42729 * @module worker/async_proxy
42730 */
42731
42732function AsyncProxy({ path = 'openpgp.worker.js', n = 1, workers = [], config } = {}) {
42733  /**
42734   * Message handling
42735   */
42736  const handleMessage = workerId => event => {
42737    const msg = event.data;
42738    switch (msg.event) {
42739      case 'loaded':
42740        this.workers[workerId].loadedResolve(true);
42741        break;
42742      case 'method-return':
42743        if (msg.err) {
42744          // fail
42745          const err = new Error(msg.err);
42746          // add worker stack
42747          err.workerStack = msg.stack;
42748          this.tasks[msg.id].reject(err);
42749        } else {
42750          // success
42751          this.tasks[msg.id].resolve(msg.data);
42752        }
42753        delete this.tasks[msg.id];
42754        this.workers[workerId].requests--;
42755        break;
42756      case 'request-seed':
42757        this.seedRandom(workerId, msg.amount);
42758        break;
42759      default:
42760        throw new Error('Unknown Worker Event.');
42761    }
42762  };
42763
42764  if (workers.length) {
42765    this.workers = workers;
42766  } else {
42767    this.workers = [];
42768    while (this.workers.length < n) {
42769      this.workers.push(new Worker(path));
42770    }
42771  }
42772
42773  let workerId = 0;
42774  this.workers.forEach(worker => {
42775    worker.loadedPromise = new Promise(resolve => {
42776      worker.loadedResolve = resolve;
42777    });
42778    worker.requests = 0;
42779    worker.onmessage = handleMessage(workerId++);
42780    worker.onerror = e => {
42781      worker.loadedResolve(false);
42782      console.error('Unhandled error in openpgp worker: ' + e.message + ' (' + e.filename + ':' + e.lineno + ')');
42783      return false;
42784    };
42785
42786    if (config) {
42787      worker.postMessage({ event: 'configure', config });
42788    }
42789  });
42790
42791  // Cannot rely on task order being maintained, use object keyed by request ID to track tasks
42792  this.tasks = {};
42793  this.currentID = 0;
42794}
42795
42796/**
42797 * Returns a promise that resolves when all workers have finished loading
42798 * @returns {Promise<Boolean>} Resolves to true if all workers have loaded succesfully; false otherwise
42799*/
42800AsyncProxy.prototype.loaded = async function () {
42801  const loaded = await Promise.all(this.workers.map(worker => worker.loadedPromise));
42802  return loaded.every(Boolean);
42803};
42804
42805/**
42806 * Get new request ID
42807 * @returns {integer}          New unique request ID
42808*/
42809AsyncProxy.prototype.getID = function () {
42810  return this.currentID++;
42811};
42812
42813/**
42814 * Send message to worker with random data
42815 * @param  {Integer} size Number of bytes to send
42816 * @async
42817 */
42818AsyncProxy.prototype.seedRandom = async function (workerId, size) {
42819  const buf = await _crypto2.default.random.getRandomBytes(size);
42820  this.workers[workerId].postMessage({ event: 'seed-random', buf }, _util2.default.getTransferables(buf, true));
42821};
42822
42823/**
42824 * Terminates the workers
42825 */
42826AsyncProxy.prototype.terminate = function () {
42827  this.workers.forEach(worker => {
42828    worker.terminate();
42829  });
42830};
42831
42832/**
42833 * Generic proxy function that handles all commands from the public api.
42834 * @param  {String} method    the public api function to be delegated to the worker thread
42835 * @param  {Object} options   the api function's options
42836 * @returns {Promise}          see the corresponding public api functions for their return types
42837 * @async
42838 */
42839AsyncProxy.prototype.delegate = function (method, options) {
42840
42841  const id = this.getID();
42842  const requests = this.workers.map(worker => worker.requests);
42843  const minRequests = Math.min(...requests);
42844  let workerId = 0;
42845  for (; workerId < this.workers.length; workerId++) {
42846    if (this.workers[workerId].requests === minRequests) {
42847      break;
42848    }
42849  }
42850
42851  return new Promise((_resolve, reject) => {
42852    // clone packets (for web worker structured cloning algorithm)
42853    this.workers[workerId].postMessage({ id: id, event: method, options: _packet2.default.clone.clonePackets(options) }, _util2.default.getTransferables(options, _config2.default.zero_copy));
42854    this.workers[workerId].requests++;
42855
42856    // remember to handle parsing cloned packets from worker
42857    this.tasks[id] = { resolve: data => _resolve(_packet2.default.clone.parseClonedPackets(_util2.default.restoreStreams(data), method)), reject };
42858  });
42859};
42860
42861exports.default = AsyncProxy;
42862
42863},{"../config":80,"../crypto":95,"../packet":126,"../util.js":153}]},{},[116])(116)
42864});