UNPKG

openpgp

Version:

OpenPGP.js is a Javascript implementation of the OpenPGP protocol. This is defined in RFC 4880.

28,532 lines • 1.2 MB
/*! OpenPGP.js v6.3.2 - 2026-09-24 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */
const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

import { createRequire } from 'module';
import * as nc from 'node:crypto';

function _mergeNamespaces(n, m) {
  m.forEach(function (e) {
    e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
      if (k !== 'default' && !(k in n)) {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  });
  return Object.freeze(n);
}

const doneWritingPromise = Symbol('doneWritingPromise');
const doneWritingResolve = Symbol('doneWritingResolve');
const doneWritingReject = Symbol('doneWritingReject');

const readingIndex = Symbol('readingIndex');

class ArrayStream extends Array {
  constructor() {
    super();
    // ES5 patch, see https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work
    Object.setPrototypeOf(this, ArrayStream.prototype);

    this[doneWritingPromise] = new Promise((resolve, reject) => {
      this[doneWritingResolve] = resolve;
      this[doneWritingReject] = reject;
    });
    this[doneWritingPromise].catch(() => {});
  }
}

ArrayStream.prototype.getReader = function() {
  if (this[readingIndex] === undefined) {
    this[readingIndex] = 0;
  }
  return {
    read: async () => {
      await this[doneWritingPromise];
      if (this[readingIndex] === this.length) {
        return { value: undefined, done: true };
      }
      return { value: this[this[readingIndex]++], done: false };
    }
  };
};

ArrayStream.prototype.readToEnd = async function(join) {
  await this[doneWritingPromise];
  const result = join(this.slice(this[readingIndex]));
  this.length = 0;
  return result;
};

ArrayStream.prototype.clone = function() {
  const clone = new ArrayStream();
  clone[doneWritingPromise] = this[doneWritingPromise].then(() => {
    clone.push(...this);
  });
  return clone;
};

/**
 * Check whether data is an ArrayStream
 * @param {Any} input  data to check
 * @returns {boolean}
 */
function isArrayStream(input) {
  return input && input.getReader && Array.isArray(input);
}

/**
 * A wrapper class over the native WritableStreamDefaultWriter.
 * It also lets you "write data to" array streams instead of streams.
 * @class
 */
function Writer(input) {
  if (!isArrayStream(input)) {
    const writer = input.getWriter();
    const releaseLock = writer.releaseLock;
    writer.releaseLock = () => {
      writer.closed.catch(function() {});
      releaseLock.call(writer);
    };
    return writer;
  }
  this.stream = input;
}

/**
 * Write a chunk of data.
 * @returns {Promise<undefined>}
 * @async
 */
Writer.prototype.write = async function(chunk) {
  this.stream.push(chunk);
};

/**
 * Close the stream.
 * @returns {Promise<undefined>}
 * @async
 */
Writer.prototype.close = async function() {
  this.stream[doneWritingResolve]();
};

/**
 * Error the stream.
 * @returns {Promise<Object>}
 * @async
 */
Writer.prototype.abort = async function(reason) {
  this.stream[doneWritingReject](reason);
  return reason;
};

/**
 * Release the writer's lock.
 * @returns {undefined}
 * @async
 */
Writer.prototype.releaseLock = function() {};

/* eslint-disable no-prototype-builtins */
typeof globalThis.process === 'object' &&
  typeof globalThis.process.versions === 'object';

/**
 * Check whether data is a Stream, and if so of which type
 * @param {Any} input  data to check
 * @returns {'web'|'node'|'array'|'web-like'|false}
 */
function isStream(input) {
  if (isArrayStream(input)) {
    return 'array';
  }
  if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {
    return 'web';
  }
  // try and detect a node native stream without having to import its class
  if (input &&
    !(globalThis.ReadableStream && input instanceof globalThis.ReadableStream) &&
    typeof input._read === 'function' && typeof input._readableState === 'object') {
    throw new Error('Native Node streams are no longer supported: please manually convert the stream to a WebStream, using e.g. `stream.Readable.toWeb`');
  }
  if (input && input.getReader) {
    return 'web-like';
  }
  return false;
}

/**
 * Check whether data is a Uint8Array
 * @param {Any} input  data to check
 * @returns {Boolean}
 */
function isUint8Array(input) {
  return Uint8Array.prototype.isPrototypeOf(input);
}

/**
 * Concat Uint8Arrays
 * @param {Array<Uint8array>} Array of Uint8Arrays to concatenate
 * @returns {Uint8array} Concatenated array
 */
function concatUint8Array(arrays) {
  if (arrays.length === 1) return arrays[0];

  let totalLength = 0;
  for (let i = 0; i < arrays.length; i++) {
    if (!isUint8Array(arrays[i])) {
      throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');
    }

    totalLength += arrays[i].length;
  }

  const result = new Uint8Array(totalLength);
  let pos = 0;
  arrays.forEach(function (element) {
    result.set(element, pos);
    pos += element.length;
  });

  return result;
}

const doneReadingSet = new WeakSet();
/**
 * The external buffer is used to store values that have been peeked or unshifted from the original stream.
 * Because of how streams are implemented, such values cannot be "put back" in the original stream,
 * but they need to be returned first when reading from the input again.
 */
const externalBuffer = Symbol('externalBuffer');

/**
 * A wrapper class over the native ReadableStreamDefaultReader.
 * This additionally implements pushing back data on the stream, which
 * lets us implement peeking and a host of convenience functions.
 * It also lets you read data other than streams, such as a Uint8Array.
 * @class
 */
function Reader(input) {
  this.stream = input;
  if (input[externalBuffer]) {
    this[externalBuffer] = input[externalBuffer].slice();
  }
  if (isArrayStream(input)) {
    const reader = input.getReader();
    this._read = reader.read.bind(reader);
    this._releaseLock = () => {};
    this._cancel = () => {};
    return;
  }
  let streamType = isStream(input);
  if (streamType) {
    const reader = input.getReader();
    this._read = reader.read.bind(reader);
    this._releaseLock = () => {
      reader.closed.catch(function() {});
      reader.releaseLock();
    };
    this._cancel = reader.cancel.bind(reader);
    return;
  }
  let doneReading = false;
  this._read = async () => {
    if (doneReading || doneReadingSet.has(input)) {
      return { value: undefined, done: true };
    }
    doneReading = true;
    return { value: input, done: false };
  };
  this._releaseLock = () => {
    if (doneReading) {
      try {
        doneReadingSet.add(input);
      } catch {}
    }
  };
}

/**
 * Read a chunk of data.
 * @returns {Promise<Object>} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }
 * @async
 */
Reader.prototype.read = async function() {
  if (this[externalBuffer] && this[externalBuffer].length) {
    const value = this[externalBuffer].shift();
    return { done: false, value };
  }
  return this._read();
};

/**
 * Allow others to read the stream.
 */
Reader.prototype.releaseLock = function() {
  if (this[externalBuffer]) {
    this.stream[externalBuffer] = this[externalBuffer];
  }
  this._releaseLock();
};

/**
 * Cancel the stream.
 */
Reader.prototype.cancel = function(reason) {
  return this._cancel(reason);
};

/**
 * Read up to and including the first \n character.
 * @returns {Promise<String|Undefined>}
 * @async
 */
Reader.prototype.readLine = async function() {
  let buffer = [];
  let returnVal;
  while (!returnVal) {
    let { done, value } = await this.read();
    value += '';
    if (done) {
      if (buffer.length) return concat(buffer);
      return;
    }
    const lineEndIndex = value.indexOf('\n') + 1;
    if (lineEndIndex) {
      returnVal = concat(buffer.concat(value.substr(0, lineEndIndex)));
      buffer = [];
    }
    if (lineEndIndex !== value.length) {
      buffer.push(value.substr(lineEndIndex));
    }
  }
  this.unshift(...buffer);
  return returnVal;
};

/**
 * Read a single byte/character.
 * @returns {Promise<Number|String|Undefined>}
 * @async
 */
Reader.prototype.readByte = async function() {
  const { done, value } = await this.read();
  if (done) return;
  const byte = value[0];
  this.unshift(slice(value, 1));
  return byte;
};

/**
 * Read a specific amount of bytes/characters, unless the stream ends before that amount.
 * @returns {Promise<Uint8Array|String|Undefined>}
 * @async
 */
Reader.prototype.readBytes = async function(length) {
  const buffer = [];
  let bufferLength = 0;
  // eslint-disable-next-line no-constant-condition
  while (true) {
    const { done, value } = await this.read();
    if (done) {
      if (buffer.length) return concat(buffer);
      return;
    }
    buffer.push(value);
    bufferLength += value.length;
    if (bufferLength >= length) {
      const bufferConcat = concat(buffer);
      this.unshift(slice(bufferConcat, length));
      return slice(bufferConcat, 0, length);
    }
  }
};

/**
 * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.
 * @returns {Promise<Uint8Array|String|Undefined>}
 * @async
 */
Reader.prototype.peekBytes = async function(length) {
  const bytes = await this.readBytes(length);
  this.unshift(bytes);
  return bytes;
};

/**
 * Push data to the front of the stream.
 * Data must have been read in the last call to read*.
 * @param {...(Uint8Array|String|Undefined)} values
 */
Reader.prototype.unshift = function(...values) {
  if (!this[externalBuffer]) {
    this[externalBuffer] = [];
  }
  if (
    values.length === 1 && isUint8Array(values[0]) &&
    this[externalBuffer].length && values[0].length &&
    this[externalBuffer][0].byteOffset >= values[0].length
  ) {
    this[externalBuffer][0] = new Uint8Array(
      this[externalBuffer][0].buffer,
      this[externalBuffer][0].byteOffset - values[0].length,
      this[externalBuffer][0].byteLength + values[0].length
    );
    return;
  }
  this[externalBuffer].unshift(...values.filter(value => value && value.length));
};

/**
 * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).
 * @param {Function} join
 * @returns {Promise<Uint8array|String|Any>} the return value of join()
 * @async
 */
Reader.prototype.readToEnd = async function(join=concat) {
  const result = [];
  // eslint-disable-next-line no-constant-condition
  while (true) {
    const { done, value } = await this.read();
    if (done) break;
    result.push(value);
  }
  return join(result);
};

/**
 * Convert data to Stream
 * @param {ReadableStream|ArrayStream|Uint8array|String} input  data to convert
 * @returns {ReadableStream|ArrayStream} Converted data
 */
function toStream(input) {
  if (isStream(input)) {
    return input;
  }
  return new ReadableStream({
    start(controller) {
      controller.enqueue(input);
      controller.close();
    }
  });
}

/**
 * Convert non-streamed data to ArrayStream; this is a noop if `input` is already a stream.
 * @param {Object} input  data to convert
 * @returns {ArrayStream} Converted data
 */
function toArrayStream(input) {
  const streamType = isStream(input);
  if (streamType) {
    if (streamType !== 'array') {
      throw new Error("Can't convert Stream to ArrayStream here, call `readToEnd` first");
    }
    return input;
  }
  const stream = new ArrayStream();
  (async () => {
    const writer = getWriter(stream);
    await writer.write(input);
    await writer.close();
  })();
  return stream;
}

/**
 * Concat a list of Uint8Arrays, Strings or Streams
 * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
 * @param {Array<Uint8array|String|ReadableStream>} Array of Uint8Arrays/Strings/Streams to concatenate
 * @returns {Uint8array|String|ReadableStream} Concatenated array
 */
function concat(list) {
  if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {
    return concatStream(list);
  }
  if (list.some(stream => isArrayStream(stream))) {
    return concatArrayStream(list);
  }
  if (typeof list[0] === 'string') {
    return list.join('');
  }
  return concatUint8Array(list);
}

/**
 * Concat a list of Streams
 * @param {Array<ReadableStream|Uint8array|String>} list  Array of Uint8Arrays/Strings/Streams to concatenate
 * @returns {ReadableStream} Concatenated list
 */
function concatStream(list) {
  const streamedList = list.map(toStream);
  const transform = transformWithCancel(async function(reason) {
    await Promise.all(transforms.map(stream => cancel(stream, reason)));
  });
  let prev = Promise.resolve();
  const transforms = streamedList.map((stream, i) => transformPair(stream, (readable, _writable) => {
    prev = prev.then(() => pipe(readable, transform.writable, {
      preventClose: i !== streamedList.length - 1
    }));
    return prev;
  }));
  return transform.readable;
}

/**
 * Concat a list of ArrayStreams
 * @param {Array<ArrayStream|Uint8array|String>} list  Array of Uint8Arrays/Strings/ArrayStreams to concatenate
 * @returns {ArrayStream} Concatenated streams
 */
function concatArrayStream(list) {
  const result = new ArrayStream();
  let prev = Promise.resolve();
  list.forEach((stream, i) => {
    prev = prev.then(() => pipe(stream, result, {
      preventClose: i !== list.length - 1
    }));
    return prev;
  });
  return result;
}

/**
 * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.
 * @param {ReadableStream|Uint8array|String} input
 * @param {WritableStream} target
 * @param {Object} (optional) options
 * @returns {Promise<undefined>} Promise indicating when piping has finished (input stream closed or errored)
 * @async
 */
async function pipe(input, target, {
  preventClose = false,
  preventAbort = false,
  preventCancel = false
} = {}) {
  if (isStream(input) && !isArrayStream(input) && !isArrayStream(target)) {
    input = toStream(input);
    try {
      if (input[externalBuffer]) {
        const writer = getWriter(target);
        for (let i = 0; i < input[externalBuffer].length; i++) {
          await writer.ready;
          await writer.write(input[externalBuffer][i]);
        }
        writer.releaseLock();
      }
      await input.pipeTo(target, {
        preventClose,
        preventAbort,
        preventCancel
      });
    } catch {}
    return;
  }
  if (!isStream(input)) {
    input = toArrayStream(input);
  }
  const reader = getReader(input);
  const writer = getWriter(target);
  try {
    // eslint-disable-next-line no-constant-condition
    while (true) {
      await writer.ready;
      const { done, value } = await reader.read();
      if (done) {
        if (!preventClose) await writer.close();
        break;
      }
      await writer.write(value);
    }
  } catch (e) {
    if (!preventAbort) await writer.abort(e);
  } finally {
    reader.releaseLock();
    writer.releaseLock();
  }
}

/**
 * Create a cancelable TransformStream.
 * @param {Function} cancel
 * @returns {TransformStream}
 */
function transformWithCancel(customCancel) {
  let pulled = false;
  let cancelled = false;
  let backpressureChangePromiseResolve, backpressureChangePromiseReject;
  let outputController;
  return {
    readable: new ReadableStream({
      start(controller) {
        outputController = controller;
      },
      pull() {
        if (backpressureChangePromiseResolve) {
          backpressureChangePromiseResolve();
        } else {
          pulled = true;
        }
      },
      async cancel(reason) {
        cancelled = true;
        if (customCancel) {
          await customCancel(reason);
        }
        if (backpressureChangePromiseReject) {
          backpressureChangePromiseReject(reason);
        }
      }
    }, {highWaterMark: 0}),
    writable: new WritableStream({
      write: async function(chunk) {
        if (cancelled) {
          throw new Error('Stream is cancelled');
        }
        outputController.enqueue(chunk);
        if (!pulled) {
          await new Promise((resolve, reject) => {
            backpressureChangePromiseResolve = resolve;
            backpressureChangePromiseReject = reject;
          });
          backpressureChangePromiseResolve = null;
          backpressureChangePromiseReject = null;
        } else {
          pulled = false;
        }
      },
      close: outputController.close.bind(outputController),
      abort: outputController.error.bind(outputController)
    })
  };
}

/**
 * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.
 * Takes an optional queuing strategy for the resulting readable stream;
 * see https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream#queuingstrategy.
 * By default, the queueing strategy is non-buffering.
 * @param {ReadableStream|Uint8array|String} input
 * @param {Function} process
 * @param {Function} finish
 * @param {Object} queuingStrategy
 * @returns {ReadableStream|Uint8array|String}
 */
function transform(input, process = () => undefined, finish = () => undefined, queuingStrategy = { highWaterMark: 0 }) {
  if (isStream(input)) {
    return _transformStream(input, process, finish, queuingStrategy);
  }
  const result1 = process(input);
  const result2 = finish();
  if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);
  return result1 !== undefined ? result1 : result2;
}

/**
 * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.
 * Takes an optional queuing strategy for the resulting readable stream;
 * see https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream#queuingstrategy.
 * By default, the queueing strategy is to buffer one chunk.
 * @param {ReadableStream|Uint8array|String} input
 * @param {Function} process
 * @param {Function} finish
 * @param {Object} queuingStrategy
 * @returns {ReadableStream|Uint8array|String}
 */
async function transformAsync(
  input,
  process = async () => undefined,
  finish = async () => undefined,
  queuingStrategy = { highWaterMark: 1 }
) {
  if (isStream(input)) {
    return _transformStream(input, process, finish, queuingStrategy);
  }
  const result1 = await process(input);
  const result2 = await finish();
  if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);
  return result1 !== undefined ? result1 : result2;
}

function _transformStream(input, process, finish, queuingStrategy) {
  if (isArrayStream(input)) {
    const output = new ArrayStream();
    (async () => {
      const writer = getWriter(output);
      try {
        const data = await readToEnd(input);
        const result1 = await process(data);
        const result2 = await finish();
        let result;
        if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);
        else result = result1 !== undefined ? result1 : result2;
        await writer.write(result);
        await writer.close();
      } catch (e) {
        await writer.abort(e);
      }
    })();
    return output;
  }
  if (isStream(input)) {
    let reader;
    let allDone = false;
    return new ReadableStream({
      start() {
        reader = input.getReader();
      },
      async pull(controller) {
        if (allDone) {
          controller.close();
          input.releaseLock();
          return;
        }
        try {
          // Read repeatedly until we have a chunk to enqueue or until
          // we can close the stream, as `pull` won't get called again
          // until we call `enqueue` or `close`.
          while (true) { // eslint-disable-line no-constant-condition
            const { value, done } = await reader.read();
            allDone = done;
            const result = await (done ? finish : process)(value);
            if (result !== undefined) {
              controller.enqueue(result);
              return; // `pull` will get called again
            }
            if (done) {
              // If `finish` didn't return a chunk to enqueue, call
              // `close` here. Otherwise, it will get called in the
              // next call to `pull`, above (since `allDone == true`).
              controller.close();
              input.releaseLock();
              return;
            }
          }
        } catch (e) {
          controller.error(e);
        }
      },
      async cancel(reason) {
        await reader.cancel(reason);
      }
    }, queuingStrategy);
  }
  throw new Error('Unreachable');
}

/**
 * Transform a stream using a helper function which is passed a readable and a writable stream.
 *   This function also maintains the possibility to cancel the input stream,
 *   and does so on cancelation of the output stream, despite cancelation
 *   normally being impossible when the input stream is being read from.
 * @param {ReadableStream|Uint8array|String} input
 * @param {Function} fn
 * @returns {ReadableStream}
 */
function transformPair(input, fn) {
  if (isStream(input) && !isArrayStream(input)) {
    let incomingTransformController;
    const incoming = new TransformStream({
      start(controller) {
        incomingTransformController = controller;
      }
    });

    const pipeDonePromise = pipe(input, incoming.writable);

    const outgoing = transformWithCancel(async function(reason) {
      incomingTransformController.error(reason);
      await pipeDonePromise;
      await new Promise(resolve => setTimeout(resolve));
    });
    fn(incoming.readable, outgoing.writable);
    return outgoing.readable;
  }
  input = toArrayStream(input);
  const output = new ArrayStream();
  fn(input, output);
  return output;
}

/**
 * Parse a stream using a helper function which is passed a Reader.
 *   The reader additionally has a remainder() method which returns a
 *   stream pointing to the remainder of input, and is linked to input
 *   for cancelation.
 * @param {ReadableStream|Uint8array|String} input
 * @param {Function} fn
 * @returns {Any} the return value of fn()
 */
function parse(input, fn) {
  let returnValue;
  const transformed = transformPair(input, (readable, writable) => {
    const reader = getReader(readable);
    reader.remainder = () => {
      reader.releaseLock();
      pipe(readable, writable);
      return transformed;
    };
    returnValue = fn(reader);
  });
  return returnValue;
}

/**
 * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.
 *   Reading either of the two returned streams will pull from the input stream.
 *   The input stream will only be canceled if both of the returned streams are canceled.
 * @param {ReadableStream|Uint8array|String} input
 * @returns {Array<ReadableStream|Uint8array|String>} array containing two copies of input
 */
function tee(input) {
  if (isArrayStream(input)) {
    throw new Error('ArrayStream cannot be tee()d, use clone() instead');
  }
  if (isStream(input)) {
    const teed = toStream(input).tee();
    teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];
    return teed;
  }
  return [slice(input), slice(input)];
}

/**
 * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.
 *   Reading from the clone will pull from the input stream.
 *   The input stream will only be canceled if both the clone and the input stream are canceled.
 * @param {ReadableStream|Uint8array|String} input
 * @returns {ReadableStream|Uint8array|String} cloned input
 */
function clone(input) {
  if (isArrayStream(input)) {
    return input.clone();
  }
  if (isStream(input)) {
    const teed = tee(input);
    overwrite(input, teed[0]);
    return teed[1];
  }
  return slice(input);
}

/**
 * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.
 *   Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.
 *   The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.
 *   If the input stream is canceled, the clone will be errored.
 * @param {ReadableStream|Uint8array|String} input
 * @returns {ReadableStream|Uint8array|String} cloned input
 */
function passiveClone(input) {
  if (isArrayStream(input)) {
    return clone(input);
  }
  if (isStream(input)) {
    return new ReadableStream({
      start(controller) {
        const transformed = transformPair(input, async (readable, writable) => {
          const reader = getReader(readable);
          const writer = getWriter(writable);
          try {
            // eslint-disable-next-line no-constant-condition
            while (true) {
              await writer.ready;
              const { done, value } = await reader.read();
              if (done) {
                try { controller.close(); } catch {}
                await writer.close();
                return;
              }
              try { controller.enqueue(value); } catch {}
              await writer.write(value);
            }
          } catch(e) {
            controller.error(e);
            await writer.abort(e);
          }
        });
        overwrite(input, transformed);
      }
    });
  }
  return slice(input);
}

/**
 * Modify a stream object to point to a different stream object.
 *   This is used internally by clone() and passiveClone() to provide an abstraction over tee().
 * @param {ReadableStream} input
 * @param {ReadableStream} clone
 */
function overwrite(input, clone) {
  // Overwrite input.getReader, input.locked, etc to point to clone
  Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {
    if (name === 'constructor') {
      return;
    }
    if (descriptor.value) {
      descriptor.value = descriptor.value.bind(clone);
    } else {
      descriptor.get = descriptor.get.bind(clone);
    }
    Object.defineProperty(input, name, descriptor);
  });
}

/**
 * Return a stream pointing to a part of the input stream.
 * @param {ReadableStream|Uint8array|String} input
 * @returns {ReadableStream|Uint8array|String} clone
 */
function slice(input, begin=0, end=Infinity) {
  if (isArrayStream(input)) {
    throw new Error('Not implemented');
  }
  if (isStream(input)) {
    if (begin >= 0 && end >= 0) {
      let reader;
      let bytesRead = 0;
      return new ReadableStream({
        start() {
          reader = input.getReader();
        },
        async pull(controller) {
          try {
            // Read repeatedly until we have a chunk to enqueue or until
            // we can close the stream, as `pull` won't get called again
            // until we call `enqueue` or `close`.
            while (true) { // eslint-disable-line no-constant-condition
              if (bytesRead < end) {
                const { value, done } = await reader.read();
                if (done) {
                  controller.close();
                  input.releaseLock();
                  return;
                }
                let valueToEnqueue;
                if (bytesRead + value.length >= begin) {
                  valueToEnqueue = slice(value, Math.max(begin - bytesRead, 0), end - bytesRead);
                }
                bytesRead += value.length;
                if (valueToEnqueue) {
                  controller.enqueue(valueToEnqueue);
                  return; // `pull` will get called again
                }
              } else {
                controller.close();
                input.releaseLock();
                return;
              }
            }
          } catch (e) {
            controller.error(e);
          }
        },
        async cancel(reason) {
          await reader.cancel(reason);
        }
      }, { highWaterMark: 0 });
    }
    if (begin < 0 && (end < 0 || end === Infinity)) {
      let lastBytes = [];
      return transform(input, value => {
        if (value.length >= -begin) lastBytes = [value];
        else lastBytes.push(value);
      }, () => slice(concat(lastBytes), begin, end));
    }
    if (begin === 0 && end < 0) {
      let lastBytes;
      return transform(input, value => {
        const returnValue = lastBytes ? concat([lastBytes, value]) : value;
        if (returnValue.length >= -end) {
          lastBytes = slice(returnValue, end);
          return slice(returnValue, begin, end);
        }
        lastBytes = returnValue;
      });
    }
    console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);
    return fromAsync(async () => slice(await readToEnd(input), begin, end));
  }
  if (input[externalBuffer]) {
    input = concat(input[externalBuffer].concat([input]));
  }
  if (isUint8Array(input)) {
    return input.subarray(begin, end === Infinity ? input.length : end);
  }
  return input.slice(begin, end);
}

/**
 * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).
 * @param {ReadableStream|Uint8array|String} input
 * @param {Function} join
 * @returns {Promise<Uint8array|String|Any>} the return value of join()
 * @async
 */
async function readToEnd(input, join=concat) {
  if (isArrayStream(input)) {
    return input.readToEnd(join);
  }
  if (isStream(input)) {
    return getReader(input).readToEnd(join);
  }
  return input;
}

/**
 * Cancel a stream.
 * @param {ReadableStream|Uint8array|String} input
 * @param {Any} reason
 * @returns {Promise<Any>} indicates when the stream has been canceled
 * @async
 */
async function cancel(input, reason) {
  if (isStream(input)) {
    if (input.cancel) {
      const cancelled = await input.cancel(reason);
      // the stream is not always cancelled at this point, so we wait some more
      await new Promise(resolve => setTimeout(resolve));
      return cancelled;
    }
    if (input.destroy) {
      input.destroy(reason);
      await new Promise(resolve => setTimeout(resolve));
      return reason;
    }
  }
}

/**
 * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.
 * @param {Function} fn
 * @returns {ArrayStream}
 */
function fromAsync(fn) {
  const arrayStream = new ArrayStream();
  (async () => {
    const writer = getWriter(arrayStream);
    try {
      await writer.write(await fn());
      await writer.close();
    } catch (e) {
      await writer.abort(e);
    }
  })();
  return arrayStream;
}

/**
 * Get a Reader
 * @param {ReadableStream|Uint8array|String} input
 * @returns {Reader}
 */
function getReader(input) {
  return new Reader(input);
}

/**
 * Get a Writer
 * @param {WritableStream} input
 * @returns {Writer}
 */
function getWriter(input) {
  return new Writer(input);
}

/**
 * @module enums
 * @access public
 */
const byValue = Symbol('byValue');
var enums = {
    /** Maps curve names under various standards to one
     * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}
     * @enum {String}
     * @readonly
     */
    curve: {
        /** NIST P-256 Curve */
        'nistP256': 'nistP256',
        /** @deprecated use `nistP256` instead */
        'p256': 'nistP256',
        /** NIST P-384 Curve */
        'nistP384': 'nistP384',
        /** @deprecated use `nistP384` instead */
        'p384': 'nistP384',
        /** NIST P-521 Curve */
        'nistP521': 'nistP521',
        /** @deprecated use `nistP521` instead */
        'p521': 'nistP521',
        /** SECG SECP256k1 Curve */
        'secp256k1': 'secp256k1',
        /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */
        'ed25519Legacy': 'ed25519Legacy',
        /** @deprecated use `ed25519Legacy` instead */
        'ed25519': 'ed25519Legacy',
        /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */
        'curve25519Legacy': 'curve25519Legacy',
        /** @deprecated use `curve25519Legacy` instead */
        'curve25519': 'curve25519Legacy',
        /** BrainpoolP256r1 Curve */
        'brainpoolP256r1': 'brainpoolP256r1',
        /** BrainpoolP384r1 Curve */
        'brainpoolP384r1': 'brainpoolP384r1',
        /** BrainpoolP512r1 Curve */
        'brainpoolP512r1': 'brainpoolP512r1'
    },
    /** A string to key specifier type
     * @enum {Integer}
     * @readonly
     */
    s2k: {
        simple: 0,
        salted: 1,
        iterated: 3,
        argon2: 4,
        gnu: 101
    },
    /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1}
     * @enum {Integer}
     * @readonly
     */
    publicKey: {
        /** RSA (Encrypt or Sign) [HAC] */
        rsaEncryptSign: 1,
        /** RSA (Encrypt only) [HAC] */
        rsaEncrypt: 2,
        /** RSA (Sign only) [HAC] */
        rsaSign: 3,
        /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */
        elgamal: 16,
        /** DSA (Sign only) [FIPS186] [HAC] */
        dsa: 17,
        /** ECDH (Encrypt only) [RFC6637] */
        ecdh: 18,
        /** ECDSA (Sign only) [RFC6637] */
        ecdsa: 19,
        /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below)
         * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */
        eddsaLegacy: 22,
        /** Reserved for AEDH */
        aedh: 23,
        /** Reserved for AEDSA */
        aedsa: 24,
        /** X25519 (Encrypt only) */
        x25519: 25,
        /** X448 (Encrypt only) */
        x448: 26,
        /** Ed25519 (Sign only) */
        ed25519: 27,
        /** Ed448 (Sign only) */
        ed448: 28
    },
    /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}
     * @enum {Integer}
     * @readonly
     */
    symmetric: {
        /** Not implemented! */
        idea: 1,
        tripledes: 2,
        cast5: 3,
        blowfish: 4,
        aes128: 7,
        aes192: 8,
        aes256: 9,
        twofish: 10
    },
    /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}
     * @enum {Integer}
     * @readonly
     */
    compression: {
        uncompressed: 0,
        /** RFC1951 */
        zip: 1,
        /** RFC1950 */
        zlib: 2,
        bzip2: 3
    },
    /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}
     * @enum {Integer}
     * @readonly
     */
    hash: {
        md5: 1,
        sha1: 2,
        ripemd: 3,
        sha256: 8,
        sha384: 9,
        sha512: 10,
        sha224: 11,
        sha3_256: 12,
        sha3_512: 14
    },
    /** A list of hash names as accepted by webCrypto functions.
     * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}
     * @enum {String}
     */
    webHash: {
        'SHA-1': 2,
        'SHA-256': 8,
        'SHA-384': 9,
        'SHA-512': 10
    },
    /** {@link https://www.rfc-editor.org/rfc/rfc9580.html#name-aead-algorithms}
     * @enum {Integer}
     * @readonly
     */
    aead: {
        eax: 1,
        ocb: 2,
        gcm: 3,
        /** @deprecated used by OpenPGP.js v5 for legacy AEAD support; use `gcm` instead for the RFC9580-standardized ID */
        experimentalGCM: 100 // Private algorithm
    },
    /** A list of packet types and numeric tags associated with them.
     * @enum {Integer}
     * @readonly
     */
    packet: {
        publicKeyEncryptedSessionKey: 1,
        signature: 2,
        symEncryptedSessionKey: 3,
        onePassSignature: 4,
        secretKey: 5,
        publicKey: 6,
        secretSubkey: 7,
        compressedData: 8,
        symmetricallyEncryptedData: 9,
        marker: 10,
        literalData: 11,
        trust: 12,
        userID: 13,
        publicSubkey: 14,
        userAttribute: 17,
        symEncryptedIntegrityProtectedData: 18,
        modificationDetectionCode: 19,
        aeadEncryptedData: 20, // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1
        padding: 21
    },
    /** Data types in the literal packet
     * @enum {Integer}
     * @readonly
     */
    literal: {
        /** Binary data 'b' */
        binary: 'b'.charCodeAt(),
        /** Text data 't' */
        text: 't'.charCodeAt(),
        /** Utf8 data 'u' */
        utf8: 'u'.charCodeAt(),
        /** MIME message body part 'm' */
        mime: 'm'.charCodeAt()
    },
    /** One pass signature packet type
     * @enum {Integer}
     * @readonly
     */
    signature: {
        /** 0x00: Signature of a binary document. */
        binary: 0,
        /** 0x01: Signature of a canonical text document.
         *
         * Canonicalyzing the document by converting line endings. */
        text: 1,
        /** 0x02: Standalone signature.
         *
         * This signature is a signature of only its own subpacket contents.
         * It is calculated identically to a signature over a zero-lengh
         * binary document.  Note that it doesn't make sense to have a V3
         * standalone signature. */
        standalone: 2,
        /** 0x10: Generic certification of a User ID and Public-Key packet.
         *
         * The issuer of this certification does not make any particular
         * assertion as to how well the certifier has checked that the owner
         * of the key is in fact the person described by the User ID. */
        certGeneric: 16,
        /** 0x11: Persona certification of a User ID and Public-Key packet.
         *
         * The issuer of this certification has not done any verification of
         * the claim that the owner of this key is the User ID specified. */
        certPersona: 17,
        /** 0x12: Casual certification of a User ID and Public-Key packet.
         *
         * The issuer of this certification has done some casual
         * verification of the claim of identity. */
        certCasual: 18,
        /** 0x13: Positive certification of a User ID and Public-Key packet.
         *
         * The issuer of this certification has done substantial
         * verification of the claim of identity.
         *
         * Most OpenPGP implementations make their "key signatures" as 0x10
         * certifications.  Some implementations can issue 0x11-0x13
         * certifications, but few differentiate between the types. */
        certPositive: 19,
        /** 0x30: Certification revocation signature
         *
         * This signature revokes an earlier User ID certification signature
         * (signature class 0x10 through 0x13) or direct-key signature
         * (0x1F).  It should be issued by the same key that issued the
         * revoked signature or an authorized revocation key.  The signature
         * is computed over the same data as the certificate that it
         * revokes, and should have a later creation date than that
         * certificate. */
        certRevocation: 48,
        /** 0x18: Subkey Binding Signature
         *
         * This signature is a statement by the top-level signing key that
         * indicates that it owns the subkey.  This signature is calculated
         * directly on the primary key and subkey, and not on any User ID or
         * other packets.  A signature that binds a signing subkey MUST have
         * an Embedded Signature subpacket in this binding signature that
         * contains a 0x19 signature made by the signing subkey on the
         * primary key and subkey. */
        subkeyBinding: 24,
        /** 0x19: Primary Key Binding Signature
         *
         * This signature is a statement by a signing subkey, indicating
         * that it is owned by the primary key and subkey.  This signature
         * is calculated the same way as a 0x18 signature: directly on the
         * primary key and subkey, and not on any User ID or other packets.
         *
         * When a signature is made over a key, the hash data starts with the
         * octet 0x99, followed by a two-octet length of the key, and then body
         * of the key packet.  (Note that this is an old-style packet header for
         * a key packet with two-octet length.)  A subkey binding signature
         * (type 0x18) or primary key binding signature (type 0x19) then hashes
         * the subkey using the same format as the main key (also using 0x99 as
         * the first octet). */
        keyBinding: 25,
        /** 0x1F: Signature directly on a key
         *
         * This signature is calculated directly on a key.  It binds the
         * information in the Signature subpackets to the key, and is
         * appropriate to be used for subpackets that provide information
         * about the key, such as the Revocation Key subpacket.  It is also
         * appropriate for statements that non-self certifiers want to make
         * about the key itself, rather than the binding between a key and a
         * name. */
        key: 31,
        /** 0x20: Key revocation signature
         *
         * The signature is calculated directly on the key being revoked.  A
         * revoked key is not to be used.  Only revocation signatures by the
         * key being revoked, or by an authorized revocation key, should be
         * considered valid revocation signatures.a */
        keyRevocation: 32,
        /** 0x28: Subkey revocation signature
         *
         * The signature is calculated directly on the subkey being revoked.
         * A revoked subkey is not to be used.  Only revocation signatures
         * by the top-level signature key that is bound to this subkey, or
         * by an authorized revocation key, should be considered valid
         * revocation signatures.
         *
         * Key revocation signatures (types 0x20 and 0x28)
         * hash only the key being revoked. */
        subkeyRevocation: 40,
        /** 0x40: Timestamp signature.
         * This signature is only meaningful for the timestamp contained in
         * it. */
        timestamp: 64,
        /** 0x50: Third-Party Confirmation signature.
         *
         * This signature is a signature over some other OpenPGP Signature
         * packet(s).  It is analogous to a notary seal on the signed data.
         * A third-party signature SHOULD include Signature Target
         * subpacket(s) to give easy identification.  Note that we really do
         * mean SHOULD.  There are plausible uses for this (such as a blind
         * party that only sees the signature, not the key or source
         * document) that cannot include a target subpacket. */
        thirdParty: 80
    },
    /** Signature subpacket type
     * @enum {Integer}
     * @readonly
     */
    signatureSubpacket: {
        signatureCreationTime: 2,
        signatureExpirationTime: 3,
        exportableCertification: 4,
        trustSignature: 5,
        regularExpression: 6,
        revocable: 7,
        keyExpirationTime: 9,
        placeholderBackwardsCompatibility: 10,
        preferredSymmetricAlgorithms: 11,
        revocationKey: 12,
        issuerKeyID: 16,
        notationData: 20,
        preferredHashAlgorithms: 21,
        preferredCompressionAlgorithms: 22,
        keyServerPreferences: 23,
        preferredKeyServer: 24,
        primaryUserID: 25,
        policyURI: 26,
        keyFlags: 27,
        signersUserID: 28,
        reasonForRevocation: 29,
        features: 30,
        signatureTarget: 31,
        embeddedSignature: 32,
        issuerFingerprint: 33,
        preferredAEADAlgorithms: 34,
        preferredCipherSuites: 39
    },
    /** Key flags
     * @enum {Integer}
     * @readonly
     */
    keyFlags: {
        /** 0x01 - This key may be used to certify other keys. */
        certifyKeys: 1,
        /** 0x02 - This key may be used to sign data. */
        signData: 2,
        /** 0x04 - This key may be used to encrypt communications. */
        encryptCommunication: 4,
        /** 0x08 - This key may be used to encrypt storage. */
        encryptStorage: 8,
        /** 0x10 - The private component of this key may have been split
         *        by a secret-sharing mechanism. */
        splitPrivateKey: 16,
        /** 0x20 - This key may be used for authentication. */
        authentication: 32,
        /** 0x80 - The private component of this key may be in the
         *        possession of more than one person. */
        sharedPrivateKey: 128
    },
    /** Armor type
     * @enum {Integer}
     * @readonly
     */
    armor: {
        multipartSection: 0,
        multipartLast: 1,
        signed: 2,
        message: 3,
        publicKey: 4,
        privateKey: 5,
        signature: 6
    },
    /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}
     * @enum {Integer}
     * @readonly
     */
    reasonForRevocation: {
        /** No reason specified (key revocations or cert revocations) */
        noReason: 0,
        /** Key is superseded (key revocations) */
        keySuperseded: 1,
        /** Key material has been compromised (key revocations) */
        keyCompromised: 2,
        /** Key is retired and no longer used (key revocations) */
        keyRetired: 3,
        /** User ID information is no longer valid (cert revocations) */
        userIDInvalid: 32
    },
    /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}
     * @enum {Integer}
     * @readonly
     */
    features: {
        /** 0x01 - Modification Detection (packets 18 and 19) */
        modificationDetection: 1,
        /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5
         *         Symmetric-Key Encrypted Session Key Packets (packet 3) */
        aead: 2,
        /** 0x04 - Version 5 Public-Key Packet format and corresponding new
          *        fingerprint format */
        v5Keys: 4,
        seipdv2: 8
    },
    /**
     * Asserts validity of given value and converts from string/integer to integer.
     * @param {Object} type target enum type
     * @param {String|Integer} e value to check and/or convert
     * @returns {Integer} enum value if it exists
     * @throws {Error} if the value is invalid
     */
    write: function (type, e) {
        if (typeof e === 'number') {
            e = this.read(type, e);
        }
        if (type[e] !== undefined) {
            return type[e];
        }
        throw new Error('Invalid enum value.');
    },
    /**
     * Converts enum integer value to the corresponding string, if it exists.
     * @param {Object} type target enum type
     * @param {Integer} e value to convert
     * @returns {String} name of enum value if it exists
     * @throws {Error} if the value is invalid
     */
    read: function (type, e) {
        if (!type[byValue]) {
            type[byValue] = [];
            Object.entries(type).forEach(([key, value]) => {
                type[byValue][value] = key;
            });
        }
        if (type[byValue][e] !== undefined) {
            return type[byValue][e];
        }
        throw new Error('Invalid enum value.');
    }
};

// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Global configuration values
 * @module config
 * @access public
 */
const config = {
    /**
     * @memberof module:config
     * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}
     */
    preferredHashAlgorithm: enums.hash.sha512,
    /**
     * @memberof module:config
     * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}
     */
    preferredSymmetricAlgorithm: enums.symmetric.aes256,
    /**
     * @memberof module:config
     * @property {Integer} compression Default compression algorithm {@link module:enums.compression}
     */
    preferredCompressionAlgorithm: enums.compression.uncompressed,
    /**
     * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.
     * This option is applicable to:
     * - key generation (encryption key preferences),
     * - password-based message encryption, and
     * - private key encryption.
     * In the case of message encryption using public keys, the encryption key preferences are respected instead.
     * Note: not all OpenPGP implementations are compatible with this option.
     * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-10.html|draft-crypto-refresh-10}
     * @memberof module:config
     * @property {Boolean} aeadProtect
     */
    aeadProtect: false,
    /**
     * When reading OpenPGP v4 private keys (e.g. those generated in OpenPGP.js when not setting `config.v5Keys = true`)
     * which were encrypted by OpenPGP.js v5 (or older) using `config.aeadProtect = true`,
     * this option must be set, otherwise key parsing and/or key decryption will fail.
     * Note: only set this flag if you know that the keys are of the legacy type, as non-legacy keys
     * will be processed incorrectly.
     */
    parseAEADEncryptedV4KeysAsLegacy: false,
    /**
     * Default Authenticated Encryption with Additional Data (AEAD) encryption mode
     * Only has an effect when aeadProtect is set to true.
     * @memberof module:config
     * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}
     */
    preferredAEADAlgorithm: enums.aead.gcm,
    /**
     * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode
     * Only has an effect when aeadProtect is set to true.
     * Must be an integer value from 0 to 56.
     * @memberof module:config
     * @property {Integer} aeadChunkSizeByte
     */
    aeadChunkSizeByte: 12,
    /**
     * Use v6 keys.
     * Note: not all OpenPGP implementations are compatible with this option.
     * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
     * @memberof module:config
     * @property {Boolean} v6Keys
     */
    v6Keys: false,
    /**
     * Enable parsing v5 keys and v5 signatures (which is different from the AEAD-encrypted SEIPDv2 packet).
     * These are non-standard entities, which in the crypto-refresh have been superseded
     * by v6 keys and v6 signatures, respectively.
     * However, generation of v5 entities was supported behind config flag in OpenPGP.js v5, and some other libraries,
     * hence parsing them might be necessary in some cases.
     * @memberof module:config
     * @property {Boolean} enableParsingV5Entities
     */
    enableParsingV5Entities: false,
    /**
     * S2K (String to Key) type, used for key derivation in the context of secret key encryption
     * and password-encrypted data. Weaker s2k options are not allowed.
     * Note: Argon2 is the strongest option but not all OpenPGP implementations are compatible with it
     * (pending standardisation).
     * @memberof module:config
     * @property {enums.s2k.argon2|enums.s2k.iterated} s2kType {@link module:enums.s2k}
     */
    s2kType: enums.s2k.iterated,
    /**
     * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3| RFC4880 3.7.1.3}:
     * Iteration Count Byte for Iterated and Salted S2K (String to Key).
     * Only relevant if `config.s2kType` is set to `enums.s2k.iterated`.
     * Note: this is the exponent value, not the final number of iterations (refer to specs for more details).
     * @memberof module:config
     * @property {Integer} s2kIterationCountByte
     */
    s2kIterationCountByte: 224,
    /**
     * {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-07.html#section-3.7.1.4| draft-crypto-refresh 3.7.1.4}:
     * Argon2 parameters for S2K (String to Key).
     * Only relevant if `config.s2kType` is set to `enums.s2k.argon2`.
     * Default settings correspond to the second recommendation from RFC9106 ("uniformly safe option"),
     * to ensure compatibility with memory-constrained environments.
     * For more details on the choice of parameters, see https://tools.ietf.org/html/rfc9106#section-4.
     * @memberof module:config
     * @property {Object} params
     * @property {Integer} params.passes - number of iterations t
     * @property {Integer} params.parallelism - degree of parallelism p
     * @property {Integer} params.memoryExponent - one-octet exponent indicating the memory size, which will be: 2**memoryExponent kibibytes.
     */
    s2kArgon2Params: {
        passes: 3,
        parallelism: 4, // lanes
        memoryExponent: 16 // 64 MiB of RAM
    },
    /**
     * Max memory exponent allowed for Argon2 memory allocation (e.g. `maxArgon2MemoryExponent: 20` corresponds
     * to a memory limit of 2**20 KiB = 1GiB).
     * This limit is applied both on encryption (if `config.s2kType` is set to `enums.s2k.argon2`)
     * and decryption.
     * If the input memory exponent exceeds this value, the library will not attempt the argon2 key derivation
     * and instead directly throw an `Argon2OutOfMemoryError` error.
     * NB: on encryption, if `s2kArgon2Params.memoryExponent` is larger than `maxArgon2MemoryExponent`,
     * the operation will fail.
     */
    maxArgon2MemoryExponent: 30,
    /**
     * Allow decryption of messages without integrity protection.
     * This is an **insecure** setting:
     *  - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.
     *  - it enables downgrade attacks against integrity-protected messages.
     * @memberof module:config
     * @property {Boolean} allowUnauthenticatedMessages
     */
    allowUnauthenticatedMessages: false,
    /**
     * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to
     * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible
     * and deferring checking their integrity until the decrypted stream has been read in full.
     *
     * This setting is **insecure** if the encrypted data has been corrupted by a malicious entity:
     * - if the partially decrypted message is processed further or displayed to the user, it opens up the possibility of attacks such as EFAIL
     *    (see https://efail.de/).
     * - an attacker with access to traces or timing info of internal processing errors could learn some info about the data.
     *
     * NB: this setting does not apply to AEAD-encrypted data, where the AEAD data chunk is never released until integrity is confirmed.
     * @memberof module:config
     * @property {Boolean} allowUnauthenticatedStream
     */
    allowUnauthenticatedStream: false,
    /**
     * Minimum RSA key size allowed for key generation and message signing, verification and encryption.
     * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.
     * @memberof module:config
     * @property {Number} minRSABits
     */
    minRSABits: 2047,
    /**
     * Work-around for rare GPG decryption bug when encrypting with multiple passwords.
     * **Slower and slightly less secure**
     * @memberof module:config
     * @property {Boolean} passwordCollisionCheck
     */
    passwordCollisionCheck: false,
    /**
     * Allow decryption using RSA keys without `encrypt` flag.
     * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug
     * where key flags were ignored when selecting a key for encryption.
     * @memberof module:config
     * @property {Boolean} allowInsecureDecryptionWithSigningKeys
     */
    allowInsecureDecryptionWithSigningKeys: false,
    /**
     * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined.
     * Instead, a verification key will also be consider valid as long as it is valid at the current time.
     * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted,
     * and have self-signature's creation date that does not match the primary key creation date.
     * @memberof module:config
     * @property {Boolean} allowInsecureDecryptionWithSigningKeys
     */
    allowInsecureVerificationWithReformattedKeys: false,
    /**
     * Allow using keys that do not have any key flags set.
     * Key flags are needed to restrict key usage to specific purposes: for instance, a signing key could only be allowed to certify other keys, and not sign messages
     * (see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-10.html#section-5.2.3.29).
     * Some older keys do not declare any key flags, which means they are not allowed to be used for any operation.
     * This setting allows using such keys for any operation for which they are compatible, based on their public key algorithm.
     */
    allowMissingKeyFlags: false,
    /**
     * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).
     * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:
     * - new/incoming messages are automatically decrypted (without user interaction);
     * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely).
     * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`.
     * @memberof module:config
     * @property {Boolean} constantTimePKCS1Decryption
     */
    constantTimePKCS1Decryption: false,
    /**
     * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled.
     * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail.
     * However, the more algorithms are added, the slower the decryption procedure becomes.
     * @memberof module:config
     * @property {Set<Integer>} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}
     */
    constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),
    /**
     * @memberof module:config
     * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error
     */
    ignoreUnsupportedPackets: true,
    /**
     * @memberof module:config
     * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error
     */
    ignoreMalformedPackets: false,
    /**
     * @memberof module:config
     * @property {Boolean} enforceGrammar whether parsed OpenPGP messages must comform to the OpenPGP grammar
     *    defined in https://www.rfc-editor.org/rfc/rfc9580.html#name-openpgp-messages .
     */
    enforceGrammar: true,
    /**
     * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only
     * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable
     * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message).
     * @memberof module:config
     * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket]
     */
    additionalAllowedPackets: [],
    /**
     * @memberof module:config
     * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages
     */
    showVersion: false,
    /**
     * @memberof module:config
     * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages
     */
    showComment: false,
    /**
     * @memberof module:config
     * @property {String} versionString A version string to be included in armored messages
     */
    versionString: 'OpenPGP.js 6.3.2',
    /**
     * @memberof module:config
     * @property {String} commentString A comment string to be included in armored messages
     */
    commentString: 'https://openpgpjs.org',
    /**
     * Max userID string length (used for parsing)
     * @memberof module:config
     * @property {Integer} maxUserIDLength
     */
    maxUserIDLength: 1024 * 5,
    /**
     * Maximum size of decompressed messages
     * When decompressing a larger message, OpenPGP.js will throw an error.
     * @memberof module:config
     * @property {Integer} maxDecompressedMessageSize
     */
    maxDecompressedMessageSize: Infinity,
    /**
     * Contains notatations that are considered "known". Known notations do not trigger
     * validation error when the notation is marked as critical.
     * @memberof module:config
     * @property {Array} knownNotations
     */
    knownNotations: [],
    /**
     * If true, a salt notation is used to randomize signatures generated by v4 and v5 keys (v6 signatures are always non-deterministic, by design).
     * This protects EdDSA signatures from potentially leaking the secret key in case of faults (i.e. bitflips) which, in principle, could occur
     * during the signing computation. It is added to signatures of any algo for simplicity, and as it may also serve as protection in case of
     * weaknesses in the hash algo, potentially hindering e.g. some chosen-prefix attacks.
     * NOTE: the notation is interoperable, but will reveal that the signature has been generated using OpenPGP.js, which may not be desirable in some cases.
     */
    nonDeterministicSignaturesViaNotation: true,
    /**
     * Whether to use the the noble-curves library for curves (other than Curve25519) that are not supported by the available native crypto API.
     * When false, certain standard curves will not be supported (depending on the platform).
     * @memberof module:config
     * @property {Boolean} useEllipticFallback
     */
    useEllipticFallback: true,
    /**
     * Reject insecure hash algorithms
     * @memberof module:config
     * @property {Set<Integer>} rejectHashAlgorithms {@link module:enums.hash}
     */
    rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),
    /**
     * Reject insecure message hash algorithms
     * @memberof module:config
     * @property {Set<Integer>} rejectMessageHashAlgorithms {@link module:enums.hash}
     */
    rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),
    /**
     * Reject insecure public key algorithms for key generation and message encryption, signing or verification
     * @memberof module:config
     * @property {Set<Integer>} rejectPublicKeyAlgorithms {@link module:enums.publicKey}
     */
    rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),
    /**
     * Reject non-standard curves for key generation, message encryption, signing or verification
     * @memberof module:config
     * @property {Set<String>} rejectCurves {@link module:enums.curve}
     */
    rejectCurves: new Set([enums.curve.secp256k1])
};

// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/* eslint-disable no-console */
/**
 * This object contains utility functions
 * @module util
 * @access private
 */
const debugMode = (() => {
    try {
        return process.env.NODE_ENV === 'development';
    }
    catch { }
    return false;
})();
const util = {
    isString: function (data) {
        return typeof data === 'string' || data instanceof String;
    },
    nodeRequire: createRequire(import.meta.url),
    isArray: function (data) {
        return data instanceof Array;
    },
    isUint8Array: isUint8Array,
    isStream: isStream,
    /**
     * Load noble-curves lib on demand and return the requested curve function
     * @param {enums.publicKey} publicKeyAlgo
     * @param {enums.curve} [curveName] - for algos supporting different curves (e.g. ECDSA)
     * @returns curve implementation
     * @throws on unrecognized curve, or curve not implemented by noble-curve
     */
    getNobleCurve: async (publicKeyAlgo, curveName) => {
        if (!config.useEllipticFallback) {
            throw new Error('This curve is only supported in the full build of OpenPGP.js');
        }
        const { nobleCurves } = await Promise.resolve().then(function () { return noble_curves; });
        switch (publicKeyAlgo) {
            case enums.publicKey.ecdh:
            case enums.publicKey.ecdsa: {
                const curve = nobleCurves.get(curveName);
                if (!curve)
                    throw new Error('Unsupported curve');
                return curve;
            }
            case enums.publicKey.x448:
                return nobleCurves.get('x448');
            case enums.publicKey.ed448:
                return nobleCurves.get('ed448');
            default:
                throw new Error('Unsupported curve');
        }
    },
    readNumber: function (bytes) {
        let n = 0;
        for (let i = 0; i < bytes.length; i++) {
            n += (256 ** i) * bytes[bytes.length - 1 - i];
        }
        return n;
    },
    writeNumber: function (n, bytes) {
        const b = new Uint8Array(bytes);
        for (let i = 0; i < bytes; i++) {
            b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;
        }
        return b;
    },
    readDate: function (bytes) {
        const n = util.readNumber(bytes);
        const d = new Date(n * 1000);
        return d;
    },
    writeDate: function (time) {
        const numeric = Math.floor(time.getTime() / 1000);
        return util.writeNumber(numeric, 4);
    },
    normalizeDate: function (time = Date.now()) {
        return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);
    },
    /**
     * Read one MPI from bytes in input
     * @param {Uint8Array} bytes - Input data to parse
     * @returns {Uint8Array} Parsed MPI.
     */
    readMPI: function (bytes) {
        const bits = (bytes[0] << 8) | bytes[1];
        const bytelen = (bits + 7) >>> 3;
        // There is a decryption oracle risk here by enforcing the MPI length using `readExactSubarray` in the context of SEIPDv1 encrypted signatures,
        // where unauthenticated streamed decryption is done (via `config.allowUnauthenticatedStream`), since the decrypted signature data being processed
        // has not been authenticated (yet).
        // However, such config setting is known to be insecure, and there are other packet parsing errors that can cause similar issues.
        // Also, AEAD is also not affected.
        return util.readExactSubarray(bytes, 2, 2 + bytelen);
    },
    /**
     * Read exactly `end - start` bytes from input.
     * This is a stricter version of `.subarray`.
     * @param {Uint8Array} input - Input data to parse
     * @returns {Uint8Array} subarray of size always equal to `end - start`
     * @throws if the input array is too short.
     */
    readExactSubarray: function (input, start, end) {
        if (input.length < end) {
            throw new Error('Input array too short');
        }
        return input.subarray(start, end);
    },
    /**
     * Left-pad Uint8Array to length by adding 0x0 bytes
     * @param {Uint8Array} bytes - Data to pad
     * @param {Number} length - Padded length
     * @returns {Uint8Array} Padded bytes.
     */
    leftPad(bytes, length) {
        if (bytes.length > length) {
            throw new Error('Input array too long');
        }
        const padded = new Uint8Array(length);
        const offset = length - bytes.length;
        padded.set(bytes, offset);
        return padded;
    },
    /**
     * Convert a Uint8Array to an MPI-formatted Uint8Array.
     * @param {Uint8Array} bin - An array of 8-bit integers to convert
     * @returns {Uint8Array} MPI-formatted Uint8Array.
     */
    uint8ArrayToMPI: function (bin) {
        const bitSize = util.uint8ArrayBitLength(bin);
        if (bitSize === 0) {
            throw new Error('Zero MPI');
        }
        const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));
        const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);
        return util.concatUint8Array([prefix, stripped]);
    },
    /**
     * Return bit length of the input data
     * @param {Uint8Array} bin input data (big endian)
     * @returns bit length
     */
    uint8ArrayBitLength: function (bin) {
        let i; // index of leading non-zero byte
        for (i = 0; i < bin.length; i++)
            if (bin[i] !== 0)
                break;
        if (i === bin.length) {
            return 0;
        }
        const stripped = bin.subarray(i);
        return (stripped.length - 1) * 8 + util.nbits(stripped[0]);
    },
    /**
     * Convert a hex string to an array of 8-bit integers
     * @param {String} hex - A hex string to convert
     * @returns {Uint8Array} An array of 8-bit integers.
     */
    hexToUint8Array: function (hex) {
        const result = new Uint8Array(hex.length >> 1);
        for (let k = 0; k < hex.length >> 1; k++) {
            result[k] = parseInt(hex.substr(k << 1, 2), 16);
        }
        return result;
    },
    /**
     * Convert an array of 8-bit integers to a hex string
     * @param {Uint8Array} bytes - Array of 8-bit integers to convert
     * @returns {String} Hexadecimal representation of the array.
     */
    uint8ArrayToHex: function (bytes) {
        const hexAlphabet = '0123456789abcdef';
        let s = '';
        bytes.forEach(v => { s += hexAlphabet[v >> 4] + hexAlphabet[v & 15]; });
        return s;
    },
    /**
     * Convert a string to an array of 8-bit integers
     * @param {String} str - String to convert
     * @returns {Uint8Array} An array of 8-bit integers.
     */
    stringToUint8Array: function (str) {
        return transform(str, str => {
            if (!util.isString(str)) {
                throw new Error('stringToUint8Array: Data must be in the form of a string');
            }
            const result = new Uint8Array(str.length);
            for (let i = 0; i < str.length; i++) {
                result[i] = str.charCodeAt(i);
            }
            return result;
        });
    },
    /**
     * Convert an array of 8-bit integers to a string
     * @param {Uint8Array} bytes - An array of 8-bit integers to convert
     * @returns {String} String representation of the array.
     */
    uint8ArrayToString: function (bytes) {
        bytes = new Uint8Array(bytes);
        const result = [];
        const bs = 1 << 14;
        const j = bytes.length;
        for (let i = 0; i < j; i += bs) {
            result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));
        }
        return result.join('');
    },
    /**
     * Convert a native javascript string to a Uint8Array of utf8 bytes
     * @param {String|ReadableStream} str - The string to convert
     * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.
     */
    encodeUTF8: function (str) {
        const encoder = new TextEncoder('utf-8');
        function process(value, lastChunk = false) {
            return encoder.encode(value, { stream: !lastChunk });
        }
        return transform(str, process, () => process('', true));
    },
    /**
     * Convert a Uint8Array of utf8 bytes to a native javascript string
     * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes
     * @returns {String|ReadableStream} A native javascript string.
     */
    decodeUTF8: function (utf8) {
        const decoder = new TextDecoder('utf-8');
        function process(value, lastChunk = false) {
            return decoder.decode(value, { stream: !lastChunk });
        }
        return transform(utf8, process, () => process(new Uint8Array(), true));
    },
    /**
     * Concat a list of Uint8Arrays, Strings or Streams
     * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
     * @param {Array<Uint8Array|String|ReadableStream>} Array - Of Uint8Arrays/Strings/Streams to concatenate
     * @returns {Uint8Array|String|ReadableStream} Concatenated array.
     */
    concat: concat,
    /**
     * Concat Uint8Arrays
     * @param {Array<Uint8Array>} Array - Of Uint8Arrays to concatenate
     * @returns {Uint8Array} Concatenated array.
     */
    concatUint8Array: concatUint8Array,
    /**
     * Check Uint8Array equality
     * @param {Uint8Array} array1 - First array
     * @param {Uint8Array} array2 - Second array
     * @returns {Boolean} Equality.
     */
    equalsUint8Array: function (array1, array2) {
        if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {
            throw new Error('Data must be in the form of a Uint8Array');
        }
        if (array1.length !== array2.length) {
            return false;
        }
        for (let i = 0; i < array1.length; i++) {
            if (array1[i] !== array2[i]) {
                return false;
            }
        }
        return true;
    },
    /**
     * Same as Array.findLastIndex, which is not supported on Safari 14 .
     * @param {Array} arr
     * @param {function(element, index, arr): boolean} findFn
     * @return index of last element matching `findFn`, -1 if not found
     */
    findLastIndex: function (arr, findFn) {
        for (let i = arr.length; i >= 0; i--) {
            if (findFn(arr[i], i, arr)) {
                return i;
            }
        }
        return -1;
    },
    /**
     * Check Uint8Array equality in algorithmic constant time
     * @param {Uint8Array} array1 - First array
     * @param {Uint8Array} array2 - Second array
     * @returns {Boolean} Equality
     * @throws on input arrays of different lengths
     */
    timingSafeEqualsUint8Array: function (array1, array2) {
        if (array1.length !== array2.length) {
            throw new Error('Equal input arrays expected');
        }
        let equal = 1;
        for (let i = 0; i < array1.length; i++) {
            equal &= array1[i] === array2[i];
        }
        return !!equal;
    },
    /**
     * Calculates a 16bit sum of a Uint8Array by adding each character
     * codes modulus 65535
     * @param {Uint8Array} Uint8Array - To create a sum of
     * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.
     */
    writeChecksum: function (text) {
        let s = 0;
        for (let i = 0; i < text.length; i++) {
            s = (s + text[i]) & 0xFFFF;
        }
        return util.writeNumber(s, 2);
    },
    /**
     * Helper function to print a debug message. Debug
     * messages are only printed if
     * @param {String} str - String of the debug message
     */
    printDebug: function (str) {
        if (debugMode) {
            console.log('[OpenPGP.js debug]', str);
        }
    },
    /**
     * Helper function to print a debug error. Debug
     * messages are only printed if
     * @param {String} str - String of the debug message
     */
    printDebugError: function (error) {
        if (debugMode) {
            console.error('[OpenPGP.js debug]', error);
        }
    },
    // returns bit length of the integer x
    nbits: function (x) {
        let r = 1;
        let t = x >>> 16;
        if (t !== 0) {
            x = t;
            r += 16;
        }
        t = x >> 8;
        if (t !== 0) {
            x = t;
            r += 8;
        }
        t = x >> 4;
        if (t !== 0) {
            x = t;
            r += 4;
        }
        t = x >> 2;
        if (t !== 0) {
            x = t;
            r += 2;
        }
        t = x >> 1;
        if (t !== 0) {
            x = t;
            r += 1;
        }
        return r;
    },
    /**
     * If S[1] == 0, then double(S) == (S[2..128] || 0);
     * otherwise, double(S) == (S[2..128] || 0) xor
     * (zeros(120) || 10000111).
     *
     * Both OCB and EAX (through CMAC) require this function to be constant-time.
     *
     * @param {Uint8Array} data
     */
    double: function (data) {
        const doubleVar = new Uint8Array(data.length);
        const last = data.length - 1;
        for (let i = 0; i < last; i++) {
            doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);
        }
        doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);
        return doubleVar;
    },
    /**
     * Shift a Uint8Array to the right by n bits
     * @param {Uint8Array} array - The array to shift
     * @param {Integer} bits - Amount of bits to shift (MUST be smaller
     * than 8)
     * @returns {String} Resulting array.
     */
    shiftRight: function (array, bits) {
        if (bits) {
            for (let i = array.length - 1; i >= 0; i--) {
                array[i] >>= bits;
                if (i > 0) {
                    array[i] |= (array[i - 1] << (8 - bits));
                }
            }
        }
        return array;
    },
    /**
     * Get native Web Cryptography API.
     * @returns {Object} The SubtleCrypto API
     * @throws if the API is not available
     */
    getWebCrypto: function () {
        const globalWebCrypto = typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;
        // Fallback for Node 16, which does not expose WebCrypto as a global
        const webCrypto = globalWebCrypto || this.getNodeCrypto()?.webcrypto.subtle;
        if (!webCrypto) {
            throw new Error('The WebCrypto API is not available');
        }
        return webCrypto;
    },
    /** @typedef {import('node:crypto')} NodeCrypto */
    /**
     * Get native Node.js crypto api.
     * @returns {NodeCrypto} The crypto module or 'undefined'.
     */
    getNodeCrypto: function () {
        return this.nodeRequire('crypto');
    },
    getNodeZlib: function () {
        return this.nodeRequire('zlib');
    },
    /**
     * Get native Node.js Buffer constructor. This should be used since
     * Buffer is not available under browserify.
     * @returns {Function} The Buffer constructor or 'undefined'.
     */
    getNodeBuffer: function () {
        return (this.nodeRequire('buffer') || {}).Buffer;
    },
    getHardwareConcurrency: function () {
        if (typeof navigator !== 'undefined') {
            return navigator.hardwareConcurrency || 1;
        }
        const os = this.nodeRequire('os'); // Assume we're on Node.js.
        return os.cpus().length;
    },
    /**
     * Test email format to ensure basic compliance:
     * - must include a single @
     * - no control or space unicode chars allowed
     * - no backslash and square brackets (as the latter can mess with the userID parsing)
     * - cannot end with a punctuation char
     * These checks are not meant to be exhaustive; applications are strongly encouraged to implement stricter validation,
     * e.g. based on the W3C HTML spec (https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email)).
     */
    isEmailAddress: function (data) {
        if (!util.isString(data)) {
            return false;
        }
        const re = /^[^\p{C}\p{Z}@<>\\]+@[^\p{C}\p{Z}@<>\\]+[^\p{C}\p{Z}\p{P}]$/u;
        return re.test(data);
    },
    /**
     * Normalize line endings to <CR><LF>
     * Support any encoding where CR=0x0D, LF=0x0A
     */
    canonicalizeEOL: function (data) {
        const CR = 13;
        const LF = 10;
        let carryOverCR = false;
        return transform(data, bytes => {
            if (carryOverCR) {
                bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);
            }
            if (bytes[bytes.length - 1] === CR) {
                carryOverCR = true;
                bytes = bytes.subarray(0, -1);
            }
            else {
                carryOverCR = false;
            }
            let index;
            const indices = [];
            for (let i = 0;; i = index) {
                index = bytes.indexOf(LF, i) + 1;
                if (index) {
                    if (bytes[index - 2] !== CR)
                        indices.push(index);
                }
                else {
                    break;
                }
            }
            if (!indices.length) {
                return bytes;
            }
            const normalized = new Uint8Array(bytes.length + indices.length);
            let j = 0;
            for (let i = 0; i < indices.length; i++) {
                const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);
                normalized.set(sub, j);
                j += sub.length;
                normalized[j - 1] = CR;
                normalized[j] = LF;
                j++;
            }
            normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);
            return normalized;
        }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));
    },
    /**
     * Convert line endings from canonicalized <CR><LF> to native <LF>
     * Support any encoding where CR=0x0D, LF=0x0A
     */
    nativeEOL: function (data) {
        const CR = 13;
        const LF = 10;
        let carryOverCR = false;
        return transform(data, bytes => {
            if (carryOverCR && bytes[0] !== LF) {
                bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);
            }
            else {
                bytes = new Uint8Array(bytes); // Don't mutate passed bytes
            }
            if (bytes[bytes.length - 1] === CR) {
                carryOverCR = true;
                bytes = bytes.subarray(0, -1);
            }
            else {
                carryOverCR = false;
            }
            let index;
            let j = 0;
            for (let i = 0; i !== bytes.length; i = index) {
                index = bytes.indexOf(CR, i) + 1;
                if (!index)
                    index = bytes.length;
                const last = index - (bytes[index] === LF ? 1 : 0);
                if (i)
                    bytes.copyWithin(j, i, last);
                j += last - i;
            }
            return bytes.subarray(0, j);
        }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));
    },
    /**
     * Remove trailing spaces, carriage returns and tabs from each line
     */
    removeTrailingSpaces: function (text) {
        return text.split('\n').map(line => {
            let i = line.length - 1;
            for (; i >= 0 && (line[i] === ' ' || line[i] === '\t' || line[i] === '\r'); i--)
                ;
            return line.substr(0, i + 1);
        }).join('\n');
    },
    wrapError: function (error, cause) {
        if (!cause) {
            if (error instanceof Error) {
                return error;
            }
            return new Error(error);
        }
        if (error instanceof Error) {
            // update error message
            try {
                error.message += ': ' + cause.message;
                error.cause = cause;
            }
            catch { }
            return error;
        }
        return new Error(error + ': ' + cause.message, { cause });
    },
    /**
     * Map allowed packet tags to corresponding classes
     * Meant to be used to format `allowedPacket` for Packetlist.read
     * @param {Array<Object>} allowedClasses
     * @returns {Object} map from enum.packet to corresponding *Packet class
     */
    constructAllowedPackets: function (allowedClasses) {
        const map = {};
        allowedClasses.forEach(PacketClass => {
            if (!PacketClass.tag) {
                throw new Error('Invalid input: expected a packet class');
            }
            map[PacketClass.tag] = PacketClass;
        });
        return map;
    },
    /**
     * Return a Promise that will resolve as soon as one of the promises in input resolves
     * or will reject if all input promises all rejected
     * (similar to Promise.any, but with slightly different error handling)
     * @param {Array<Promise>} promises
     * @return {Promise<Any>} Promise resolving to the result of the fastest fulfilled promise
     *                          or rejected with the Error of the last resolved Promise (if all promises are rejected)
     */
    anyPromise: function (promises) {
        return new Promise((resolve, reject) => {
            let exception;
            void Promise.all(promises.map(async (promise) => {
                try {
                    resolve(await promise);
                }
                catch (e) {
                    exception = e;
                }
            })).then(() => {
                reject(exception);
            });
        });
    },
    /**
     * Return either `a` or `b` based on `cond`, in algorithmic constant time.
     * @param {Boolean} cond
     * @param {Uint8Array} a
     * @param {Uint8Array} b
     * @returns `a` if `cond` is true, `b` otherwise
     */
    selectUint8Array: function (cond, a, b) {
        const length = Math.max(a.length, b.length);
        const result = new Uint8Array(length);
        let end = 0;
        for (let i = 0; i < result.length; i++) {
            result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond));
            end += (cond & i < a.length) | ((1 - cond) & i < b.length);
        }
        return result.subarray(0, end);
    },
    /**
     * Return either `a` or `b` based on `cond`, in algorithmic constant time.
     * NB: it only supports `a, b` with values between 0-255.
     * @param {Boolean} cond
     * @param {Uint8} a
     * @param {Uint8} b
     * @returns `a` if `cond` is true, `b` otherwise
     */
    selectUint8: function (cond, a, b) {
        return (a & (256 - cond)) | (b & (255 + cond));
    },
    /**
     * @param {module:enums.symmetric} cipherAlgo
     */
    isAES: function (cipherAlgo) {
        return cipherAlgo === enums.symmetric.aes128 || cipherAlgo === enums.symmetric.aes192 || cipherAlgo === enums.symmetric.aes256;
    }
};

/* OpenPGP radix-64/base64 string encoding/decoding
 * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de
 * version 1.0, check www.haneWIN.de for the latest version
 *
 * This software is provided as-is, without express or implied warranty.
 * Permission to use, copy, modify, distribute or sell this software, with or
 * without fee, for any purpose and by any individual or organization, is hereby
 * granted, provided that the above copyright notice and this paragraph appear
 * in all copies. Distribution as a part of an application or binary must
 * include the above copyright notice in the documentation and/or other materials
 * provided with the application or distribution.
 */
/**
 * @module encoding/base64
 * @access private
 */
const Buffer$3 = util.getNodeBuffer();
let encodeChunk;
let decodeChunk;
if (Buffer$3) {
    encodeChunk = buf => Buffer$3.from(buf).toString('base64');
    decodeChunk = str => {
        const b = Buffer$3.from(str, 'base64');
        return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
    };
}
else {
    encodeChunk = buf => btoa(util.uint8ArrayToString(buf));
    decodeChunk = str => util.stringToUint8Array(atob(str));
}
/**
 * Convert binary array to radix-64
 * @param {Uint8Array | ReadableStream<Uint8Array>} data - Uint8Array to convert
 * @returns {String | ReadableStream<String>} Radix-64 version of input string.
 * @static
 */
function encode$1(data) {
    let buf = new Uint8Array();
    return transform(data, value => {
        buf = util.concatUint8Array([buf, value]);
        const r = [];
        const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).
        const lines = Math.floor(buf.length / bytesPerLine);
        const bytes = lines * bytesPerLine;
        const encoded = encodeChunk(buf.subarray(0, bytes));
        for (let i = 0; i < lines; i++) {
            r.push(encoded.substr(i * 60, 60));
            r.push('\n');
        }
        buf = buf.subarray(bytes);
        return r.join('');
    }, () => (buf.length ? encodeChunk(buf) + '\n' : ''));
}
/**
 * Convert radix-64 to binary array
 * @param {String | ReadableStream<String>} data - Radix-64 string to convert
 * @returns {Uint8Array | ReadableStream<Uint8Array>} Binary array version of input string.
 * @static
 */
function decode$1(data) {
    let buf = '';
    return transform(data, value => {
        buf += value;
        // Count how many whitespace characters there are in buf
        let spaces = 0;
        const spacechars = [' ', '\t', '\r', '\n'];
        for (let i = 0; i < spacechars.length; i++) {
            const spacechar = spacechars[i];
            for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {
                spaces++;
            }
        }
        // Backtrack until we have 4n non-whitespace characters
        // that we can safely base64-decode
        let length = buf.length;
        for (; length > 0 && (length - spaces) % 4 !== 0; length--) {
            if (spacechars.includes(buf[length]))
                spaces--;
        }
        const decoded = decodeChunk(buf.substr(0, length));
        buf = buf.substr(length);
        return decoded;
    }, () => decodeChunk(buf));
}
/**
 * Convert a Base-64 encoded string an array of 8-bit integer
 *
 * Note: accepts both Radix-64 and URL-safe strings
 * @param {String} base64 - Base-64 encoded string to convert
 * @returns {Uint8Array} An array of 8-bit integers.
 */
function b64ToUint8Array(base64) {
    return decode$1(base64.replace(/-/g, '+').replace(/_/g, '/'));
}
/**
 * Convert an array of 8-bit integer to a Base-64 encoded string
 * @param {Uint8Array} bytes - An array of 8-bit integers to convert
 * @param {bool} url - If true, output is URL-safe
 * @returns {String} Base-64 encoded string.
 */
function uint8ArrayToB64(bytes, url) {
    let encoded = encode$1(bytes).replace(/[\r\n]/g, '');
    {
        encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');
    }
    return encoded;
}

/** @access private */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Finds out which Ascii Armoring type is used. Throws error if unknown type.
 * @param {String} text - ascii armored text
 * @returns {Integer} 0 = MESSAGE PART n of m.
 *         1 = MESSAGE PART n
 *         2 = SIGNED MESSAGE
 *         3 = PGP MESSAGE
 *         4 = PUBLIC KEY BLOCK
 *         5 = PRIVATE KEY BLOCK
 *         6 = SIGNATURE
 * @private
 */
function getType(text) {
    const reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;
    const header = text.match(reHeader);
    if (!header) {
        throw new Error('Unknown ASCII armor type');
    }
    // BEGIN PGP MESSAGE, PART X/Y
    // Used for multi-part messages, where the armor is split amongst Y
    // parts, and this is the Xth part out of Y.
    if (/MESSAGE, PART \d+\/\d+/.test(header[1])) {
        return enums.armor.multipartSection;
    }
    // BEGIN PGP MESSAGE, PART X
    // Used for multi-part messages, where this is the Xth part of an
    // unspecified number of parts. Requires the MESSAGE-ID Armor
    // Header to be used.
    if (/MESSAGE, PART \d+/.test(header[1])) {
        return enums.armor.multipartLast;
    }
    // BEGIN PGP SIGNED MESSAGE
    if (/SIGNED MESSAGE/.test(header[1])) {
        return enums.armor.signed;
    }
    // BEGIN PGP MESSAGE
    // Used for signed, encrypted, or compressed files.
    if (/MESSAGE/.test(header[1])) {
        return enums.armor.message;
    }
    // BEGIN PGP PUBLIC KEY BLOCK
    // Used for armoring public keys.
    if (/PUBLIC KEY BLOCK/.test(header[1])) {
        return enums.armor.publicKey;
    }
    // BEGIN PGP PRIVATE KEY BLOCK
    // Used for armoring private keys.
    if (/PRIVATE KEY BLOCK/.test(header[1])) {
        return enums.armor.privateKey;
    }
    // BEGIN PGP SIGNATURE
    // Used for detached signatures, OpenPGP/MIME signatures, and
    // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE
    // for detached signatures.
    if (/SIGNATURE/.test(header[1])) {
        return enums.armor.signature;
    }
}
/**
 * Add additional information to the armor version of an OpenPGP binary
 * packet block.
 * @author  Alex
 * @version 2011-12-16
 * @param {String} [customComment] - Additional comment to add to the armored string
 * @returns {String} The header information.
 * @private
 */
function addheader(customComment, config) {
    let result = '';
    if (config.showVersion) {
        result += 'Version: ' + config.versionString + '\n';
    }
    if (config.showComment) {
        result += 'Comment: ' + config.commentString + '\n';
    }
    if (customComment) {
        result += 'Comment: ' + customComment + '\n';
    }
    result += '\n';
    return result;
}
/**
 * Calculates a checksum over the given data and returns it base64 encoded
 * @param {String | ReadableStream<String>} data - Data to create a CRC-24 checksum for
 * @returns {String | ReadableStream<String>} Base64 encoded checksum.
 * @private
 */
function getCheckSum(data) {
    const crc = createcrc24(data);
    return encode$1(crc);
}
// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview
const crc_table = [
    new Array(0xFF),
    new Array(0xFF),
    new Array(0xFF),
    new Array(0xFF)
];
for (let i = 0; i <= 0xFF; i++) {
    let crc = i << 16;
    for (let j = 0; j < 8; j++) {
        crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);
    }
    crc_table[0][i] =
        ((crc & 0xFF0000) >> 16) |
            (crc & 0x00FF00) |
            ((crc & 0x0000FF) << 16);
}
for (let i = 0; i <= 0xFF; i++) {
    crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];
}
for (let i = 0; i <= 0xFF; i++) {
    crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];
}
for (let i = 0; i <= 0xFF; i++) {
    crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness
const isLittleEndian$1 = (function () {
    const buffer = new ArrayBuffer(2);
    new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);
    // Int16Array uses the platform's endianness.
    return new Int16Array(buffer)[0] === 0xFF;
}());
/**
 * Internal function to calculate a CRC-24 checksum over a given string (data)
 * @param {String | ReadableStream<String>} input - Data to create a CRC-24 checksum for
 * @returns {Uint8Array | ReadableStream<Uint8Array>} The CRC-24 checksum.
 * @private
 */
function createcrc24(input) {
    let crc = 0xCE04B7;
    return transform(input, value => {
        const len32 = isLittleEndian$1 ? Math.floor(value.length / 4) : 0;
        const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);
        for (let i = 0; i < len32; i++) {
            crc ^= arr32[i];
            crc =
                crc_table[0][(crc >> 24) & 0xFF] ^
                    crc_table[1][(crc >> 16) & 0xFF] ^
                    crc_table[2][(crc >> 8) & 0xFF] ^
                    crc_table[3][(crc >> 0) & 0xFF];
        }
        for (let i = len32 * 4; i < value.length; i++) {
            crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];
        }
    }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));
}
/**
 * Verify armored headers. crypto-refresh-06, section 6.2:
 * "An OpenPGP implementation may consider improperly formatted Armor
 * Headers to be corruption of the ASCII Armor, but SHOULD make an
 * effort to recover."
 * @private
 * @param {Array<String>} headers - Armor headers
 */
function verifyHeaders$1(headers) {
    for (let i = 0; i < headers.length; i++) {
        if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) {
            util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i]));
        }
        if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {
            util.printDebugError(new Error('Unknown header: ' + headers[i]));
        }
    }
}
/**
 * Remove the (optional) checksum from an armored message.
 * @param {String} text - OpenPGP armored message
 * @returns {String} The body of the armored message.
 * @private
 */
function removeChecksum(text) {
    let body = text;
    const lastEquals = text.lastIndexOf('=');
    if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum
        body = text.slice(0, lastEquals);
    }
    return body;
}
/**
 * Dearmor an OpenPGP armored message; verify the checksum and return
 * the encoded bytes
 * @param {String} input - OpenPGP armored message
 * @returns {Promise<Object>} An object with attribute "text" containing the message text,
 * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type
 * @async
 * @static
 */
function unarmor(input) {
    return new Promise((resolve, reject) => {
        try {
            const reSplit = /^-----[^-]+-----$/m;
            const reEmptyLine = /^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;
            let type;
            const headers = [];
            let lastHeaders = headers;
            let headersDone;
            let text = [];
            let textDone;
            const data = decode$1(transformPair(input, async (readable, writable) => {
                const reader = getReader(readable);
                try {
                    while (true) {
                        let line = await reader.readLine();
                        if (line === undefined) {
                            throw new Error('Misformed armored text');
                        }
                        // remove trailing whitespace at end of lines
                        line = util.removeTrailingSpaces(line.replace(/[\r\n]/g, ''));
                        if (!type) {
                            if (reSplit.test(line)) {
                                type = getType(line);
                            }
                        }
                        else if (!headersDone) {
                            if (reSplit.test(line)) {
                                reject(new Error('Mandatory blank line missing between armor headers and armor data'));
                            }
                            if (!reEmptyLine.test(line)) {
                                lastHeaders.push(line);
                            }
                            else {
                                verifyHeaders$1(lastHeaders);
                                headersDone = true;
                                if (textDone || type !== enums.armor.signed) {
                                    resolve({ text, data, headers, type });
                                    break;
                                }
                            }
                        }
                        else if (!textDone && type === enums.armor.signed) {
                            if (!reSplit.test(line)) {
                                // Reverse dash-escaping for msg
                                text.push(line.replace(/^- /, ''));
                            }
                            else {
                                text = text.join('\r\n');
                                textDone = true;
                                verifyHeaders$1(lastHeaders);
                                lastHeaders = [];
                                headersDone = false;
                            }
                        }
                    }
                }
                catch (e) {
                    reject(e);
                    return;
                }
                const writer = getWriter(writable);
                try {
                    while (true) {
                        await writer.ready;
                        const { done, value } = await reader.read();
                        if (done) {
                            throw new Error('Misformed armored text');
                        }
                        const line = value + '';
                        if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {
                            await writer.write(line);
                        }
                        else {
                            let remainder = await reader.readToEnd();
                            if (!remainder.length)
                                remainder = '';
                            remainder = line + remainder;
                            remainder = util.removeTrailingSpaces(remainder.replace(/\r/g, ''));
                            const parts = remainder.split(reSplit);
                            if (parts.length === 1) {
                                throw new Error('Misformed armored text');
                            }
                            const body = removeChecksum(parts[0].slice(0, -1));
                            await writer.write(body);
                            break;
                        }
                    }
                    await writer.ready;
                    await writer.close();
                }
                catch (e) {
                    await writer.abort(e);
                }
            }));
        }
        catch (e) {
            reject(e);
        }
    }).then(async (result) => {
        if (isArrayStream(result.data)) {
            result.data = await readToEnd(result.data);
        }
        return result;
    });
}
/**
 * Armor an OpenPGP binary packet block
 * @param {module:enums.armor} messageType - Type of the message
 * @param {Uint8Array | ReadableStream<Uint8Array>} body - The message body to armor
 * @param {Integer} [partIndex]
 * @param {Integer} [partTotal]
 * @param {String} [customComment] - Additional comment to add to the armored string
 * @param {Boolean} [emitChecksum] - Whether to compute and include the CRC checksum
 *  (NB: some types of data must not include it, but compliance is left as responsibility of the caller: this function does not carry out any checks)
 * @param {Object} [config] - Full configuration, defaults to openpgp.config
 * @returns {String | ReadableStream<String>} Armored text.
 * @static
 */
function armor(messageType, body, partIndex, partTotal, customComment, emitChecksum = false, config$1 = config) {
    let text;
    let hash;
    if (messageType === enums.armor.signed) {
        text = body.text;
        hash = body.hash;
        body = body.data;
    }
    // unless explicitly forbidden by the spec, we need to include the checksum to work around a GnuPG bug
    // where data fails to be decoded if the base64 ends with no padding chars (=) (see https://dev.gnupg.org/T7071)
    const maybeBodyClone = emitChecksum && passiveClone(body);
    const result = [];
    switch (messageType) {
        case enums.armor.multipartSection:
            result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n');
            result.push(addheader(customComment, config$1));
            result.push(encode$1(body));
            maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));
            result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n');
            break;
        case enums.armor.multipartLast:
            result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\n');
            result.push(addheader(customComment, config$1));
            result.push(encode$1(body));
            maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));
            result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\n');
            break;
        case enums.armor.signed:
            result.push('-----BEGIN PGP SIGNED MESSAGE-----\n');
            result.push(hash ? `Hash: ${hash}\n\n` : '\n');
            result.push(text.replace(/^-/mg, '- -'));
            result.push('\n-----BEGIN PGP SIGNATURE-----\n');
            result.push(addheader(customComment, config$1));
            result.push(encode$1(body));
            maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));
            result.push('-----END PGP SIGNATURE-----\n');
            break;
        case enums.armor.message:
            result.push('-----BEGIN PGP MESSAGE-----\n');
            result.push(addheader(customComment, config$1));
            result.push(encode$1(body));
            maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));
            result.push('-----END PGP MESSAGE-----\n');
            break;
        case enums.armor.publicKey:
            result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\n');
            result.push(addheader(customComment, config$1));
            result.push(encode$1(body));
            maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));
            result.push('-----END PGP PUBLIC KEY BLOCK-----\n');
            break;
        case enums.armor.privateKey:
            result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\n');
            result.push(addheader(customComment, config$1));
            result.push(encode$1(body));
            maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));
            result.push('-----END PGP PRIVATE KEY BLOCK-----\n');
            break;
        case enums.armor.signature:
            result.push('-----BEGIN PGP SIGNATURE-----\n');
            result.push(addheader(customComment, config$1));
            result.push(encode$1(body));
            maybeBodyClone && result.push('=', getCheckSum(maybeBodyClone));
            result.push('-----END PGP SIGNATURE-----\n');
            break;
    }
    return util.concat(result);
}

/**
 * @module biginteger
 * @access private
 */
// Operations are not constant time, but we try and limit timing leakage where we can
const _0n$8 = BigInt(0);
const _1n$c = BigInt(1);
function uint8ArrayToBigInt(bytes) {
    const hexAlphabet = '0123456789ABCDEF';
    let s = '';
    bytes.forEach(v => {
        s += hexAlphabet[v >> 4] + hexAlphabet[v & 15];
    });
    return BigInt('0x0' + s);
}
function mod$1(a, m) {
    const reduced = a % m;
    return reduced < _0n$8 ? reduced + m : reduced;
}
/**
 * Return either `a` or `b` based on `cond`, in algorithmic constant time.
 * @param {BigInt} cond
 * @param {BigInt} a
 * @param {BigInt} b
 * @returns `a` if `cond` is `1n`, `b` otherwise
 */
function selectBigInt(cond, a, b) {
    const mask = -cond; // ~0n === -1n
    return (a & mask) | (b & ~mask);
}
/**
 * Compute modular exponentiation using square and multiply
 * @param {BigInt} a - Base
 * @param {BigInt} e - Exponent
 * @param {BigInt} n - Modulo
 * @returns {BigInt} b ** e mod n.
 */
function modExp(b, e, n) {
    if (n === _0n$8)
        throw Error('Modulo cannot be zero');
    if (n === _1n$c)
        return BigInt(0);
    if (e < _0n$8)
        throw Error('Unsopported negative exponent');
    let exp = e;
    let x = b;
    x %= n;
    let r = BigInt(1);
    while (exp > _0n$8) {
        const lsb = (exp & _1n$c);
        exp >>= _1n$c; // e / 2
        // Always compute multiplication step, to reduce timing leakage
        const rx = (r * x) % n;
        // Update r only if lsb is 1 (odd exponent)
        r = selectBigInt(lsb, rx, r);
        x = (x * x) % n; // Square
    }
    return r;
}
function abs(x) {
    return x >= _0n$8 ? x : -x;
}
/**
 * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)
 * Given a and b, compute (x, y) such that ax + by = gdc(a, b).
 * Negative numbers are also supported.
 * @param {BigInt} a - First operand
 * @param {BigInt} b - Second operand
 * @returns {{ gcd, x, y: bigint }}
 */
function _egcd(aInput, bInput) {
    let x = BigInt(0);
    let y = BigInt(1);
    let xPrev = BigInt(1);
    let yPrev = BigInt(0);
    // Deal with negative numbers: run algo over absolute values,
    // and "move" the sign to the returned x and/or y.
    // See https://math.stackexchange.com/questions/37806/extended-euclidean-algorithm-with-negative-numbers
    let a = abs(aInput);
    let b = abs(bInput);
    const aNegated = aInput < _0n$8;
    const bNegated = bInput < _0n$8;
    while (b !== _0n$8) {
        const q = a / b;
        let tmp = x;
        x = xPrev - q * x;
        xPrev = tmp;
        tmp = y;
        y = yPrev - q * y;
        yPrev = tmp;
        tmp = b;
        b = a % b;
        a = tmp;
    }
    return {
        x: aNegated ? -xPrev : xPrev,
        y: bNegated ? -yPrev : yPrev,
        gcd: a
    };
}
/**
 * Compute the inverse of `a` modulo `n`
 * Note: `a` and and `n` must be relatively prime
 * @param {BigInt} a
 * @param {BigInt} n - Modulo
 * @returns {BigInt} x such that a*x = 1 mod n
 * @throws {Error} if the inverse does not exist
 */
function modInv(a, n) {
    const { gcd, x } = _egcd(a, n);
    if (gcd !== _1n$c) {
        throw new Error('Inverse does not exist');
    }
    return mod$1(x + n, n);
}
/**
 * Compute greatest common divisor between this and n
 * @param {BigInt} aInput - Operand
 * @param {BigInt} bInput - Operand
 * @returns {BigInt} gcd
 */
function gcd(aInput, bInput) {
    let a = aInput;
    let b = bInput;
    while (b !== _0n$8) {
        const tmp = b;
        b = a % b;
        a = tmp;
    }
    return a;
}
/**
 * Get this value as an exact Number (max 53 bits)
 * Fails if this value is too large
 * @returns {Number}
 */
function bigIntToNumber(x) {
    const number = Number(x);
    if (number > Number.MAX_SAFE_INTEGER) {
        // We throw and error to conform with the bn.js implementation
        throw new Error('Number can only safely store up to 53 bits');
    }
    return number;
}
/**
 * Get value of i-th bit
 * @param {BigInt} x
 * @param {Number} i - Bit index
 * @returns {Number} Bit value.
 */
function getBit(x, i) {
    const bit = (x >> BigInt(i)) & _1n$c;
    return bit === _0n$8 ? 0 : 1;
}
/**
 * Compute bit length
 */
function bitLength(x) {
    // -1n >> -1n is -1n
    // 1n >> 1n is 0n
    const target = x < _0n$8 ? BigInt(-1) : _0n$8;
    let bitlen = 1;
    let tmp = x;
    while ((tmp >>= _1n$c) !== target) {
        bitlen++;
    }
    return bitlen;
}
/**
 * Compute byte length
 */
function byteLength(x) {
    const target = x < _0n$8 ? BigInt(-1) : _0n$8;
    const _8n = BigInt(8);
    let len = 1;
    let tmp = x;
    while ((tmp >>= _8n) !== target) {
        len++;
    }
    return len;
}
/**
 * Get Uint8Array representation of this number
 * @param {String} endian - Endianess of output array (defaults to 'be')
 * @param {Number} length - Of output array
 * @returns {Uint8Array}
 */
function bigIntToUint8Array(x, endian = 'be', length) {
    // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)
    // this is faster than shift+mod iterations
    let hex = x.toString(16);
    if (hex.length % 2 === 1) {
        hex = '0' + hex;
    }
    const rawLength = hex.length / 2;
    const bytes = new Uint8Array(length || rawLength);
    // parse hex
    const offset = length ? length - rawLength : 0;
    let i = 0;
    while (i < rawLength) {
        bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);
        i++;
    }
    if (endian !== 'be') {
        bytes.reverse();
    }
    return bytes;
}

// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// The GPG4Browsers crypto interface
/**
 * @fileoverview Provides tools for retrieving secure randomness from browsers or Node.js
 * @module crypto/random
 * @access private
 */
const nodeCrypto$8 = util.getNodeCrypto();
/**
 * Retrieve secure random byte array of the specified length
 * @param {Integer} length - Length in bytes to generate
 * @returns {Uint8Array} Random byte array.
 */
function getRandomBytes(length) {
    const webcrypto = typeof crypto !== 'undefined' ? crypto : nodeCrypto$8?.webcrypto;
    if (webcrypto?.getRandomValues) {
        const buf = new Uint8Array(length);
        return webcrypto.getRandomValues(buf);
    }
    else {
        throw new Error('No secure random number generator available.');
    }
}
/**
 * Create a secure random BigInt that is greater than or equal to min and less than max.
 * @param {bigint} min - Lower bound, included
 * @param {bigint} max - Upper bound, excluded
 * @returns {bigint} Random BigInt.
 * @async
 */
function getRandomBigInteger(min, max) {
    if (max < min) {
        throw new Error('Illegal parameter value: max <= min');
    }
    const modulus = max - min;
    const bytes = byteLength(modulus);
    // Using a while loop is necessary to avoid bias introduced by the mod operation.
    // However, we request 64 extra random bits so that the bias is negligible.
    // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
    const r = uint8ArrayToBigInt(getRandomBytes(bytes + 8));
    return mod$1(r, modulus) + min;
}

// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2018 Proton Technologies AG
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview Algorithms for probabilistic random prime generation
 * @module crypto/public_key/prime
 * @access private
 */
const _1n$b = BigInt(1);
/**
 * Generate a probably prime random number
 * @param bits - Bit length of the prime
 * @param e - Optional RSA exponent to check against the prime
 * @param k - Optional number of iterations of Miller-Rabin test
 */
function randomProbablePrime(bits, e, k) {
    const _30n = BigInt(30);
    const min = _1n$b << BigInt(bits - 1);
    /*
     * We can avoid any multiples of 3 and 5 by looking at n mod 30
     * n mod 30 = 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
     * the next possible prime is mod 30:
     *            1  7  7  7  7  7  7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1
     */
    const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2];
    let n = getRandomBigInteger(min, min << _1n$b);
    let i = bigIntToNumber(mod$1(n, _30n));
    do {
        n += BigInt(adds[i]);
        i = (i + adds[i]) % adds.length;
        // If reached the maximum, go back to the minimum.
        if (bitLength(n) > bits) {
            n = mod$1(n, min << _1n$b);
            n += min;
            i = bigIntToNumber(mod$1(n, _30n));
        }
    } while (!isProbablePrime(n, e, k));
    return n;
}
/**
 * Probabilistic primality testing
 * @param n - Number to test
 * @param e - Optional RSA exponent to check against the prime
 * @param k - Optional number of iterations of Miller-Rabin test
 */
function isProbablePrime(n, e, k) {
    if (e && gcd(n - _1n$b, e) !== _1n$b) {
        return false;
    }
    if (!divisionTest(n)) {
        return false;
    }
    if (!fermat(n)) {
        return false;
    }
    if (!millerRabin(n, k)) {
        return false;
    }
    // TODO implement the Lucas test
    // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
    return true;
}
/**
 * Tests whether n is probably prime or not using Fermat's test with b = 2.
 * Fails if b^(n-1) mod n != 1.
 * @param n - Number to test
 * @param b - Optional Fermat test base
 */
function fermat(n, b = BigInt(2)) {
    return modExp(b, n - _1n$b, n) === _1n$b;
}
function divisionTest(n) {
    const _0n = BigInt(0);
    return smallPrimes.every(m => mod$1(n, m) !== _0n);
}
// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c
const smallPrimes = [
    7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
    47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
    103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
    157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
    211, 223, 227, 229, 233, 239, 241, 251, 257, 263,
    269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
    331, 337, 347, 349, 353, 359, 367, 373, 379, 383,
    389, 397, 401, 409, 419, 421, 431, 433, 439, 443,
    449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
    509, 521, 523, 541, 547, 557, 563, 569, 571, 577,
    587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
    643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
    709, 719, 727, 733, 739, 743, 751, 757, 761, 769,
    773, 787, 797, 809, 811, 821, 823, 827, 829, 839,
    853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
    919, 929, 937, 941, 947, 953, 967, 971, 977, 983,
    991, 997, 1009, 1013, 1019, 1021, 1031, 1033,
    1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,
    1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
    1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,
    1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,
    1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,
    1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,
    1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
    1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,
    1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,
    1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,
    1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,
    1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
    1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,
    1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,
    1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,
    1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,
    1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
    2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,
    2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,
    2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,
    2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,
    2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
    2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,
    2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,
    2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,
    2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,
    2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
    2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,
    2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,
    2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,
    2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,
    2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
    3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,
    3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,
    3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,
    3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,
    3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
    3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,
    3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,
    3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,
    3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,
    3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
    3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,
    3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,
    3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,
    3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,
    3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
    4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,
    4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,
    4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,
    4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,
    4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
    4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,
    4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,
    4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,
    4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,
    4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,
    4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,
    4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,
    4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,
    4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,
    4957, 4967, 4969, 4973, 4987, 4993, 4999
].map(n => BigInt(n));
// Miller-Rabin - Miller Rabin algorithm for primality test
// Copyright Fedor Indutny, 2014.
//
// This software is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin
// Sample syntax for Fixed-Base Miller-Rabin:
// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))
/**
 * Tests whether n is probably prime or not using the Miller-Rabin test.
 * See HAC Remark 4.28.
 * @param n - Number to test
 * @param k - Optional number of iterations of Miller-Rabin test
 * @param rand - Optional function to generate potential witnesses
 * @returns {boolean}
 * @async
 */
function millerRabin(n, k, rand) {
    const len = bitLength(n);
    if (!k) {
        k = Math.max(1, (len / 48) | 0);
    }
    const n1 = n - _1n$b; // n - 1
    // Find d and s, (n - 1) = (2 ^ s) * d;
    let s = 0;
    while (!getBit(n1, s)) {
        s++;
    }
    const d = n >> BigInt(s);
    for (; k > 0; k--) {
        const a = getRandomBigInteger(BigInt(2), n1);
        let x = modExp(a, d, n);
        if (x === _1n$b || x === n1) {
            continue;
        }
        let i;
        for (i = 1; i < s; i++) {
            x = mod$1(x * x, n);
            if (x === _1n$b) {
                return false;
            }
            if (x === n1) {
                break;
            }
        }
        if (i === s) {
            return false;
        }
    }
    return true;
}

/**
 * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.
 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
 * @see {@link https://github.com/indutny/hash.js|hash.js}
 * @module crypto/hash
 * @access private
 */
const webCrypto$8 = util.getWebCrypto();
const nodeCrypto$7 = util.getNodeCrypto();
const nodeCryptoHashes = nodeCrypto$7 && nodeCrypto$7.getHashes();
function nodeHash(type) {
    if (!nodeCrypto$7 || !nodeCryptoHashes.includes(type)) {
        return;
    }
    // eslint-disable-next-line @typescript-eslint/require-await
    return async function (data) {
        const shasum = nodeCrypto$7.createHash(type);
        return transform(data, value => {
            shasum.update(value);
        }, () => new Uint8Array(shasum.digest()));
    };
}
function nobleHash(nobleHashName, webCryptoHashName) {
    const getNobleHash = async () => {
        const { nobleHashes } = await Promise.resolve().then(function () { return noble_hashes; });
        const hash = nobleHashes.get(nobleHashName);
        if (!hash)
            throw new Error('Unsupported hash');
        return hash;
    };
    return async function (data) {
        if (isArrayStream(data)) {
            data = await readToEnd(data);
        }
        if (util.isStream(data)) {
            const hash = await getNobleHash();
            const hashInstance = hash.create();
            return transform(data, value => {
                hashInstance.update(value);
            }, () => hashInstance.digest());
        }
        else if (webCrypto$8 && webCryptoHashName) {
            return new Uint8Array(await webCrypto$8.digest(webCryptoHashName, data));
        }
        else {
            const hash = await getNobleHash();
            return hash(data);
        }
    };
}
const md5$1 = nodeHash('md5') || nobleHash('md5');
const sha1$2 = nodeHash('sha1') || nobleHash('sha1', 'SHA-1');
const sha224$2 = nodeHash('sha224') || nobleHash('sha224');
const sha256$2 = nodeHash('sha256') || nobleHash('sha256', 'SHA-256');
const sha384$2 = nodeHash('sha384') || nobleHash('sha384', 'SHA-384');
const sha512$2 = nodeHash('sha512') || nobleHash('sha512', 'SHA-512');
const ripemd = nodeHash('ripemd160') || nobleHash('ripemd160');
const sha3_256$1 = nodeHash('sha3-256') || nobleHash('sha3_256');
const sha3_512$1 = nodeHash('sha3-512') || nobleHash('sha3_512');
/**
 * Create a hash on the specified data using the specified algorithm
 * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
 * @param {Uint8Array} data - Data to be hashed
 * @returns {Promise<Uint8Array>} Hash value.
 */
function computeDigest(algo, data) {
    switch (algo) {
        case enums.hash.md5:
            return md5$1(data);
        case enums.hash.sha1:
            return sha1$2(data);
        case enums.hash.ripemd:
            return ripemd(data);
        case enums.hash.sha256:
            return sha256$2(data);
        case enums.hash.sha384:
            return sha384$2(data);
        case enums.hash.sha512:
            return sha512$2(data);
        case enums.hash.sha224:
            return sha224$2(data);
        case enums.hash.sha3_256:
            return sha3_256$1(data);
        case enums.hash.sha3_512:
            return sha3_512$1(data);
        default:
            throw new Error('Unsupported hash function');
    }
}
/**
 * Returns the hash size in bytes of the specified hash algorithm type
 * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
 * @returns {Integer} Size in bytes of the resulting hash.
 */
function getHashByteLength(algo) {
    switch (algo) {
        case enums.hash.md5:
            return 16;
        case enums.hash.sha1:
        case enums.hash.ripemd:
            return 20;
        case enums.hash.sha256:
            return 32;
        case enums.hash.sha384:
            return 48;
        case enums.hash.sha512:
            return 64;
        case enums.hash.sha224:
            return 28;
        case enums.hash.sha3_256:
            return 32;
        case enums.hash.sha3_512:
            return 64;
        default:
            throw new Error('Invalid hash algorithm.');
    }
}

// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview Provides EME-PKCS1-v1_5 encoding and decoding and EMSA-PKCS1-v1_5 encoding function
 * @see module:crypto/public_key/rsa
 * @see module:crypto/public_key/elliptic/ecdh
 * @see PublicKeyEncryptedSessionKeyPacket
 * @module crypto/pkcs1
 * @access private
 */
/**
 * ASN1 object identifiers for hashes
 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}
 */
const hash_headers = [];
hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,
    0x10];
hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];
hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];
hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,
    0x04, 0x20];
hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,
    0x04, 0x30];
hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
    0x00, 0x04, 0x40];
hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,
    0x00, 0x04, 0x1C];
hash_headers[12] = [0x30, 0x31, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x08, 0x05,
    0x00, 0x04, 0x20];
hash_headers[14] = [0x30, 0x51, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0a, 0x05,
    0x00, 0x04, 0x40];
/**
 * Create padding with secure random data
 * @private
 * @param {Integer} length - Length of the padding in bytes
 * @returns {Uint8Array} Random padding.
 */
function getPKCS1Padding(length) {
    const result = new Uint8Array(length);
    let count = 0;
    while (count < length) {
        const randomBytes = getRandomBytes(length - count);
        for (let i = 0; i < randomBytes.length; i++) {
            if (randomBytes[i] !== 0) {
                result[count++] = randomBytes[i];
            }
        }
    }
    return result;
}
/**
 * Create a EME-PKCS1-v1_5 padded message
 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}
 * @param {Uint8Array} message - Message to be encoded
 * @param {Integer} keyLength - The length in octets of the key modulus
 * @returns {Uint8Array} EME-PKCS1 padded message.
 */
function emeEncode(message, keyLength) {
    const mLength = message.length;
    // length checking
    if (mLength > keyLength - 11) {
        throw new Error('Message too long');
    }
    // Generate an octet string PS of length k - mLen - 3 consisting of
    // pseudo-randomly generated nonzero octets
    const PS = getPKCS1Padding(keyLength - mLength - 3);
    // Concatenate PS, the message M, and other padding to form an
    // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.
    const encoded = new Uint8Array(keyLength);
    // 0x00 byte
    encoded[1] = 2;
    encoded.set(PS, 2);
    // 0x00 bytes
    encoded.set(message, keyLength - mLength);
    return encoded;
}
/**
 * Decode a EME-PKCS1-v1_5 padded message
 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}
 * @param {Uint8Array} encoded - Encoded message bytes
 * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing)
 * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given)
 * @throws {Error} on decoding failure, unless `randomPayload` is provided
 */
function emeDecode(encoded, randomPayload) {
    // encoded format: 0x00 0x02 <PS> 0x00 <payload>
    let offset = 2;
    let separatorNotFound = 1;
    for (let j = offset; j < encoded.length; j++) {
        separatorNotFound &= encoded[j] !== 0;
        offset += separatorNotFound;
    }
    const psLen = offset - 2;
    const payload = encoded.subarray(offset + 1); // discard the 0x00 separator
    const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound;
    if (randomPayload) {
        return util.selectUint8Array(isValidPadding, payload, randomPayload);
    }
    if (isValidPadding) {
        return payload;
    }
    throw new Error('Decryption error');
}
/**
 * Create a EMSA-PKCS1-v1_5 padded message
 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}
 * @param {Integer} algo - Hash algorithm type used
 * @param {Uint8Array} hashed - Message to be encoded
 * @param {Integer} emLen - Intended length in octets of the encoded message
 * @returns {Uint8Array} Encoded message.
 */
function emsaEncode(algo, hashed, emLen) {
    let i;
    if (hashed.length !== getHashByteLength(algo)) {
        throw new Error('Invalid hash length');
    }
    // produce an ASN.1 DER value for the hash function used.
    // Let T be the full hash prefix
    const hashPrefix = new Uint8Array(hash_headers[algo].length);
    for (i = 0; i < hash_headers[algo].length; i++) {
        hashPrefix[i] = hash_headers[algo][i];
    }
    // and let tLen be the length in octets prefix and hashed data
    const tLen = hashPrefix.length + hashed.length;
    if (emLen < tLen + 11) {
        throw new Error('Intended encoded message length too short');
    }
    // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF
    // The length of PS will be at least 8 octets
    const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);
    // Concatenate PS, the hash prefix, hashed data, and other padding to form the
    // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed
    const EM = new Uint8Array(emLen);
    EM[1] = 0x01;
    EM.set(PS, 2);
    EM.set(hashPrefix, emLen - tLen);
    EM.set(hashed, emLen - hashed.length);
    return EM;
}

// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview RSA implementation
 * @module crypto/public_key/rsa
 * @access private
 */
const webCrypto$7 = util.getWebCrypto();
const nodeCrypto$6 = util.getNodeCrypto();
const _1n$a = BigInt(1);
/** Create signature
 * @param {module:enums.hash} hashAlgo - Hash algorithm
 * @param {Uint8Array} data - Message
 * @param {Uint8Array} n - RSA public modulus
 * @param {Uint8Array} e - RSA public exponent
 * @param {Uint8Array} d - RSA private exponent
 * @param {Uint8Array} p - RSA private prime p
 * @param {Uint8Array} q - RSA private prime q
 * @param {Uint8Array} u - RSA private coefficient
 * @param {Uint8Array} hashed - Hashed message
 * @returns {Promise<Uint8Array>} RSA Signature.
 * @async
 */
async function sign$6(hashAlgo, data, n, e, d, p, q, u, hashed) {
    if (getHashByteLength(hashAlgo) >= n.length) {
        // Throw here instead of `emsaEncode` below, to provide a clearer and consistent error
        // e.g. if a 512-bit RSA key is used with a SHA-512 digest.
        // The size limit is actually slightly different but here we only care about throwing
        // on common key sizes.
        throw new Error('Digest size cannot exceed key modulus size');
    }
    if (data && !util.isStream(data)) {
        if (util.getWebCrypto()) {
            try {
                return await webSign$1(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);
            }
            catch (err) {
                util.printDebugError(err);
            }
        }
        else if (util.getNodeCrypto()) {
            return nodeSign$1(hashAlgo, data, n, e, d, p, q, u);
        }
    }
    return bnSign(hashAlgo, n, d, hashed);
}
/**
 * Verify signature
 * @param {module:enums.hash} hashAlgo - Hash algorithm
 * @param {Uint8Array} data - Message
 * @param {Uint8Array} s - Signature
 * @param {Uint8Array} n - RSA public modulus
 * @param {Uint8Array} e - RSA public exponent
 * @param {Uint8Array} hashed - Hashed message
 * @returns {Promise<Boolean>}
 * @async
 */
async function verify$6(hashAlgo, data, s, n, e, hashed) {
    if (data && !util.isStream(data)) {
        if (util.getWebCrypto()) {
            try {
                return await webVerify$1(enums.read(enums.webHash, hashAlgo), data, s, n, e);
            }
            catch (err) {
                util.printDebugError(err);
            }
        }
        else if (util.getNodeCrypto()) {
            return nodeVerify$1(hashAlgo, data, s, n, e);
        }
    }
    return bnVerify(hashAlgo, s, n, e, hashed);
}
/**
 * Encrypt message
 * @param {Uint8Array} data - Message
 * @param {Uint8Array} n - RSA public modulus
 * @param {Uint8Array} e - RSA public exponent
 * @returns {Promise<Uint8Array>} RSA Ciphertext.
 * @async
 */
// eslint-disable-next-line @typescript-eslint/require-await
async function encrypt$6(data, n, e) {
    if (util.getNodeCrypto()) {
        return nodeEncrypt$1(data, n, e);
    }
    return bnEncrypt(data, n, e);
}
/**
 * Decrypt RSA message
 * @param {Uint8Array} m - Message
 * @param {Uint8Array} n - RSA public modulus
 * @param {Uint8Array} e - RSA public exponent
 * @param {Uint8Array} d - RSA private exponent
 * @param {Uint8Array} p - RSA private prime p
 * @param {Uint8Array} q - RSA private prime q
 * @param {Uint8Array} u - RSA private coefficient
 * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing
 *                                     (needed for constant-time processing)
 * @returns {Promise<String>} RSA Plaintext.
 * @throws {Error} on decryption error, unless `randomPayload` is given
 * @async
 */
// eslint-disable-next-line @typescript-eslint/require-await
async function decrypt$6(data, n, e, d, p, q, u, randomPayload) {
    // Node v18.19.1, 20.11.1 and 21.6.2 have disabled support for PKCS#1 decryption,
    // and we want to avoid checking the error type to decide if the random payload
    // should indeed be returned.
    if (util.getNodeCrypto() && !randomPayload) {
        try {
            return nodeDecrypt$1(data, n, e, d, p, q, u);
        }
        catch (err) {
            util.printDebugError(err);
        }
    }
    return bnDecrypt(data, n, e, d, p, q, u, randomPayload);
}
/**
 * Generate a new random private key B bits long with public exponent E.
 *
 * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using
 * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.
 * @see module:crypto/public_key/prime
 * @param {Integer} bits - RSA bit length
 * @param {Integer} e - RSA public exponent
 * @returns {Promise<{n, e, d,
 *            p, q ,u: Uint8Array}>} RSA public modulus, RSA public exponent, RSA private exponent,
 *                                  RSA private prime p, RSA private prime q, u = p ** -1 mod q
 * @async
 */
async function generate$4(bits, e) {
    e = BigInt(e);
    // Native RSA keygen using Web Crypto
    if (util.getWebCrypto()) {
        const keyGenOpt = {
            name: 'RSASSA-PKCS1-v1_5',
            modulusLength: bits, // the specified keysize in bits
            publicExponent: bigIntToUint8Array(e), // take three bytes (max 65537) for exponent
            hash: {
                name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'
            }
        };
        const keyPair = await webCrypto$7.generateKey(keyGenOpt, true, ['sign', 'verify']);
        // export the generated keys as JsonWebKey (JWK)
        // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33
        const jwk = await webCrypto$7.exportKey('jwk', keyPair.privateKey);
        // map JWK parameters to corresponding OpenPGP names
        return jwkToPrivate(jwk, e);
    }
    else if (util.getNodeCrypto()) {
        const opts = {
            modulusLength: bits,
            publicExponent: bigIntToNumber(e),
            publicKeyEncoding: { type: 'pkcs1', format: 'jwk' },
            privateKeyEncoding: { type: 'pkcs1', format: 'jwk' }
        };
        const jwk = await new Promise((resolve, reject) => {
            nodeCrypto$6.generateKeyPair('rsa', opts, (err, _, jwkPrivateKey) => {
                if (err) {
                    reject(err);
                }
                else {
                    resolve(jwkPrivateKey);
                }
            });
        });
        return jwkToPrivate(jwk, e);
    }
    // RSA keygen fallback using 40 iterations of the Miller-Rabin test
    // See https://stackoverflow.com/a/6330138 for justification
    // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST
    let p;
    let q;
    let n;
    do {
        q = randomProbablePrime(bits - (bits >> 1), e, 40);
        p = randomProbablePrime(bits >> 1, e, 40);
        n = p * q;
    } while (bitLength(n) !== bits);
    const phi = (p - _1n$a) * (q - _1n$a);
    if (q < p) {
        [p, q] = [q, p];
    }
    return {
        n: bigIntToUint8Array(n),
        e: bigIntToUint8Array(e),
        d: bigIntToUint8Array(modInv(e, phi)),
        p: bigIntToUint8Array(p),
        q: bigIntToUint8Array(q),
        // dp: d.mod(p.subn(1)),
        // dq: d.mod(q.subn(1)),
        u: bigIntToUint8Array(modInv(p, q))
    };
}
/**
 * Validate RSA parameters
 * @param {Uint8Array} n - RSA public modulus
 * @param {Uint8Array} e - RSA public exponent
 * @param {Uint8Array} d - RSA private exponent
 * @param {Uint8Array} p - RSA private prime p
 * @param {Uint8Array} q - RSA private prime q
 * @param {Uint8Array} u - RSA inverse of p w.r.t. q
 * @returns {Promise<Boolean>} Whether params are valid.
 * @async
 */
// eslint-disable-next-line @typescript-eslint/require-await
async function validateParams$9(n, e, d, p, q, u) {
    n = uint8ArrayToBigInt(n);
    p = uint8ArrayToBigInt(p);
    q = uint8ArrayToBigInt(q);
    // expect pq = n
    if ((p * q) !== n) {
        return false;
    }
    const _2n = BigInt(2);
    // expect p*u = 1 mod q
    u = uint8ArrayToBigInt(u);
    if (mod$1(p * u, q) !== BigInt(1)) {
        return false;
    }
    e = uint8ArrayToBigInt(e);
    d = uint8ArrayToBigInt(d);
    /**
     * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)
     * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]
     * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]
     *
     * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)
     */
    const nSizeOver3 = BigInt(Math.floor(bitLength(n) / 3));
    const r = getRandomBigInteger(_2n, _2n << nSizeOver3); // r in [ 2, 2^{|n|/3} ) < p and q
    const rde = r * d * e;
    const areInverses = mod$1(rde, p - _1n$a) === r && mod$1(rde, q - _1n$a) === r;
    if (!areInverses) {
        return false;
    }
    return true;
}
function bnSign(hashAlgo, n, d, hashed) {
    n = uint8ArrayToBigInt(n);
    const m = uint8ArrayToBigInt(emsaEncode(hashAlgo, hashed, byteLength(n)));
    d = uint8ArrayToBigInt(d);
    return bigIntToUint8Array(modExp(m, d, n), 'be', byteLength(n));
}
async function webSign$1(hashName, data, n, e, d, p, q, u) {
    /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.
     * We swap them in privateToJWK, so it usually works out, but nevertheless,
     * not all OpenPGP keys are compatible with this requirement.
     * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still
     * does if the underlying Web Crypto does so (though the tested implementations
     * don't do so).
     */
    const jwk = privateToJWK$1(n, e, d, p, q, u);
    const algo = {
        name: 'RSASSA-PKCS1-v1_5',
        hash: { name: hashName }
    };
    const key = await webCrypto$7.importKey('jwk', jwk, algo, false, ['sign']);
    return new Uint8Array(await webCrypto$7.sign('RSASSA-PKCS1-v1_5', key, data));
}
function nodeSign$1(hashAlgo, data, n, e, d, p, q, u) {
    const sign = nodeCrypto$6.createSign(enums.read(enums.hash, hashAlgo));
    sign.write(data);
    sign.end();
    const jwk = privateToJWK$1(n, e, d, p, q, u);
    return new Uint8Array(sign.sign({ key: jwk, format: 'jwk', type: 'pkcs1' }));
}
function bnVerify(hashAlgo, s, n, e, hashed) {
    n = uint8ArrayToBigInt(n);
    s = uint8ArrayToBigInt(s);
    e = uint8ArrayToBigInt(e);
    if (s >= n) {
        throw new Error('Signature size cannot exceed modulus size');
    }
    const EM1 = bigIntToUint8Array(modExp(s, e, n), 'be', byteLength(n));
    const EM2 = emsaEncode(hashAlgo, hashed, byteLength(n));
    return util.equalsUint8Array(EM1, EM2);
}
async function webVerify$1(hashName, data, s, n, e) {
    const jwk = publicToJWK(n, e);
    const key = await webCrypto$7.importKey('jwk', jwk, {
        name: 'RSASSA-PKCS1-v1_5',
        hash: { name: hashName }
    }, false, ['verify']);
    return webCrypto$7.verify('RSASSA-PKCS1-v1_5', key, s, data);
}
function nodeVerify$1(hashAlgo, data, s, n, e) {
    const jwk = publicToJWK(n, e);
    const key = { key: jwk, format: 'jwk', type: 'pkcs1' };
    const verify = nodeCrypto$6.createVerify(enums.read(enums.hash, hashAlgo));
    verify.write(data);
    verify.end();
    try {
        return verify.verify(key, s);
    }
    catch {
        return false;
    }
}
function nodeEncrypt$1(data, n, e) {
    const jwk = publicToJWK(n, e);
    const key = { key: jwk, format: 'jwk', type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING };
    return new Uint8Array(nodeCrypto$6.publicEncrypt(key, data));
}
function bnEncrypt(data, n, e) {
    n = uint8ArrayToBigInt(n);
    data = uint8ArrayToBigInt(emeEncode(data, byteLength(n)));
    e = uint8ArrayToBigInt(e);
    if (data >= n) {
        throw new Error('Message size cannot exceed modulus size');
    }
    return bigIntToUint8Array(modExp(data, e, n), 'be', byteLength(n));
}
function nodeDecrypt$1(data, n, e, d, p, q, u) {
    const jwk = privateToJWK$1(n, e, d, p, q, u);
    const key = { key: jwk, format: 'jwk', type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING };
    try {
        return new Uint8Array(nodeCrypto$6.privateDecrypt(key, data));
    }
    catch {
        throw new Error('Decryption error');
    }
}
function bnDecrypt(data, n, e, d, p, q, u, randomPayload) {
    data = uint8ArrayToBigInt(data);
    n = uint8ArrayToBigInt(n);
    e = uint8ArrayToBigInt(e);
    d = uint8ArrayToBigInt(d);
    p = uint8ArrayToBigInt(p);
    q = uint8ArrayToBigInt(q);
    u = uint8ArrayToBigInt(u);
    if (data >= n) {
        throw new Error('Data too large.');
    }
    const dq = mod$1(d, q - _1n$a); // d mod (q-1)
    const dp = mod$1(d, p - _1n$a); // d mod (p-1)
    const unblinder = getRandomBigInteger(BigInt(2), n);
    const blinder = modExp(modInv(unblinder, n), e, n);
    data = mod$1(data * blinder, n);
    const mp = modExp(data, dp, p); // data**{d mod (q-1)} mod p
    const mq = modExp(data, dq, q); // data**{d mod (p-1)} mod q
    const h = mod$1(u * (mq - mp), q); // u * (mq-mp) mod q (operands already < q)
    let result = h * p + mp; // result < n due to relations above
    result = mod$1(result * unblinder, n);
    return emeDecode(bigIntToUint8Array(result, 'be', byteLength(n)), randomPayload);
}
/** Convert Openpgp private key params to jwk key according to
 * @link https://tools.ietf.org/html/rfc7517
 * @param {String} hashAlgo
 * @param {Uint8Array} n
 * @param {Uint8Array} e
 * @param {Uint8Array} d
 * @param {Uint8Array} p
 * @param {Uint8Array} q
 * @param {Uint8Array} u
 */
function privateToJWK$1(n, e, d, p, q, u) {
    const pNum = uint8ArrayToBigInt(p);
    const qNum = uint8ArrayToBigInt(q);
    const dNum = uint8ArrayToBigInt(d);
    let dq = mod$1(dNum, qNum - _1n$a); // d mod (q-1)
    let dp = mod$1(dNum, pNum - _1n$a); // d mod (p-1)
    dp = bigIntToUint8Array(dp);
    dq = bigIntToUint8Array(dq);
    return {
        kty: 'RSA',
        n: uint8ArrayToB64(n),
        e: uint8ArrayToB64(e),
        d: uint8ArrayToB64(d),
        // switch p and q
        p: uint8ArrayToB64(q),
        q: uint8ArrayToB64(p),
        // switch dp and dq
        dp: uint8ArrayToB64(dq),
        dq: uint8ArrayToB64(dp),
        qi: uint8ArrayToB64(u),
        ext: true
    };
}
/** Convert Openpgp key public params to jwk key according to
 * @link https://tools.ietf.org/html/rfc7517
 * @param {String} hashAlgo
 * @param {Uint8Array} n
 * @param {Uint8Array} e
 */
function publicToJWK(n, e) {
    return {
        kty: 'RSA',
        n: uint8ArrayToB64(n),
        e: uint8ArrayToB64(e),
        ext: true
    };
}
/** Convert JWK private key to OpenPGP private key params */
function jwkToPrivate(jwk, e) {
    return {
        n: b64ToUint8Array(jwk.n),
        e: bigIntToUint8Array(e),
        d: b64ToUint8Array(jwk.d),
        // switch p and q
        p: b64ToUint8Array(jwk.q),
        q: b64ToUint8Array(jwk.p),
        // Since p and q are switched in places, u is the inverse of jwk.q
        u: b64ToUint8Array(jwk.qi)
    };
}

// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview ElGamal implementation
 * @module crypto/public_key/elgamal
 * @access private
 */
const _1n$9 = BigInt(1);
/**
 * ElGamal Encryption function
 * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)
 * @param {Uint8Array} data - To be padded and encrypted
 * @param {Uint8Array} p
 * @param {Uint8Array} g
 * @param {Uint8Array} y
 * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}
 * @async
 */
// eslint-disable-next-line @typescript-eslint/require-await
async function encrypt$5(data, p, g, y) {
    p = uint8ArrayToBigInt(p);
    g = uint8ArrayToBigInt(g);
    y = uint8ArrayToBigInt(y);
    const padded = emeEncode(data, byteLength(p));
    const m = uint8ArrayToBigInt(padded);
    // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ*
    // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]
    const k = getRandomBigInteger(_1n$9, p - _1n$9);
    return {
        c1: bigIntToUint8Array(modExp(g, k, p)),
        c2: bigIntToUint8Array(mod$1(modExp(y, k, p) * m, p))
    };
}
/**
 * ElGamal Encryption function
 * @param {Uint8Array} c1
 * @param {Uint8Array} c2
 * @param {Uint8Array} p
 * @param {Uint8Array} x
 * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing
 *                                     (needed for constant-time processing)
 * @returns {Promise<Uint8Array>} Unpadded message.
 * @throws {Error} on decryption error, unless `randomPayload` is given
 * @async
 */
// eslint-disable-next-line @typescript-eslint/require-await
async function decrypt$5(c1, c2, p, x, randomPayload) {
    c1 = uint8ArrayToBigInt(c1);
    c2 = uint8ArrayToBigInt(c2);
    p = uint8ArrayToBigInt(p);
    x = uint8ArrayToBigInt(x);
    const padded = mod$1(modInv(modExp(c1, x, p), p) * c2, p);
    return emeDecode(bigIntToUint8Array(padded, 'be', byteLength(p)), randomPayload);
}
/**
 * Validate ElGamal parameters
 * @param {Uint8Array} pBytes - ElGamal prime
 * @param {Uint8Array} gBytes - ElGamal group generator
 * @param {Uint8Array} yBytes - ElGamal public key
 * @param {Uint8Array} xBytes - ElGamal private exponent
 * @returns {Promise<Boolean>} Whether params are valid.
 * @async
 */
// eslint-disable-next-line @typescript-eslint/require-await
async function validateParams$8(pBytes, gBytes, yBytes, xBytes) {
    const p = uint8ArrayToBigInt(pBytes);
    const g = uint8ArrayToBigInt(gBytes);
    const y = uint8ArrayToBigInt(yBytes);
    // Check that 1 < g < p
    if (g <= _1n$9 || g >= p) {
        return false;
    }
    // Expect p-1 to be large
    const pSize = BigInt(bitLength(p));
    const _1023n = BigInt(1023);
    if (pSize < _1023n) {
        return false;
    }
    /**
     * g should have order p-1
     * Check that g ** (p-1) = 1 mod p
     */
    if (modExp(g, p - _1n$9, p) !== _1n$9) {
        return false;
    }
    /**
     * Since p-1 is not prime, g might have a smaller order that divides p-1
     * We want to make sure that the order is large enough to hinder a small subgroup attack
     *
     * We just check g**i != 1 for all i up to a threshold
     */
    let res = g;
    let i = BigInt(1);
    const _2n = BigInt(2);
    const threshold = _2n << BigInt(17); // we want order > threshold
    while (i < threshold) {
        res = mod$1(res * g, p);
        if (res === _1n$9) {
            return false;
        }
        i++;
    }
    /**
     * Re-derive public key y' = g ** x mod p
     * Expect y == y'
     *
     * Blinded exponentiation computes g**{r(p-1) + x} to compare to y
     */
    const x = uint8ArrayToBigInt(xBytes);
    const r = getRandomBigInteger(_2n << (pSize - _1n$9), _2n << pSize); // draw r of same size as p-1
    const rqx = (p - _1n$9) * r + x;
    if (y !== modExp(g, rqx, p)) {
        return false;
    }
    return true;
}

// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2015-2016 Decentral
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Wrapper to an OID value
 *
 * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}:
 * The sequence of octets in the third column is the result of applying
 * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier
 * with subsequent truncation.  The truncation removes the two fields of
 * encoded Object Identifier.  The first omitted field is one octet
 * representing the Object Identifier tag, and the second omitted field
 * is the length of the Object Identifier body.  For example, the
 * complete ASN.1 DER encoding for the NIST P-256 curve OID is "06 08 2A
 * 86 48 CE 3D 03 01 07", from which the first entry in the table above
 * is constructed by omitting the first two octets.  Only the truncated
 * sequence of octets is the valid representation of a curve OID.
 * @module type/oid
 * @access private
 */
const knownOIDs = {
    '2a8648ce3d030107': enums.curve.nistP256,
    '2b81040022': enums.curve.nistP384,
    '2b81040023': enums.curve.nistP521,
    '2b8104000a': enums.curve.secp256k1,
    '2b06010401da470f01': enums.curve.ed25519Legacy,
    '2b060104019755010501': enums.curve.curve25519Legacy,
    '2b2403030208010107': enums.curve.brainpoolP256r1,
    '2b240303020801010b': enums.curve.brainpoolP384r1,
    '2b240303020801010d': enums.curve.brainpoolP512r1
};
class OID {
    constructor(oid) {
        if (oid instanceof OID) {
            this.oid = oid.oid;
        }
        else if (util.isArray(oid) ||
            util.isUint8Array(oid)) {
            oid = new Uint8Array(oid);
            if (oid[0] === 0x06) { // DER encoded oid byte array
                if (oid[1] !== oid.length - 2) {
                    throw new Error('Length mismatch in DER encoded oid');
                }
                oid = oid.subarray(2);
            }
            this.oid = oid;
        }
        else {
            this.oid = '';
        }
    }
    /**
     * Method to read an OID object
     * @param {Uint8Array} input - Where to read the OID from
     * @returns {Number} Number of read bytes.
     */
    read(input) {
        if (input.length >= 1) {
            const length = input[0];
            if (input.length >= 1 + length) {
                this.oid = input.subarray(1, 1 + length);
                return 1 + this.oid.length;
            }
        }
        throw new Error('Invalid oid');
    }
    /**
     * Serialize an OID object
     * @returns {Uint8Array} Array with the serialized value the OID.
     */
    write() {
        return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);
    }
    /**
     * Serialize an OID object as a hex string
     * @returns {string} String with the hex value of the OID.
     */
    toHex() {
        return util.uint8ArrayToHex(this.oid);
    }
    /**
     * If a known curve object identifier, return the canonical name of the curve
     * @returns {enums.curve} String with the canonical name of the curve
     * @throws if unknown
     */
    getName() {
        const name = knownOIDs[this.toHex()];
        if (!name) {
            throw new Error('Unknown curve object identifier.');
        }
        return name;
    }
}

// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview Functions for reading and writing packets
 * @module packet/packet
 * @access private
 */
function readSimpleLength(bytes) {
    let len = 0;
    let offset;
    const type = bytes[0];
    if (type < 192) {
        [len] = bytes;
        offset = 1;
    }
    else if (type < 255) {
        len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;
        offset = 2;
    }
    else if (type === 255) {
        len = util.readNumber(bytes.subarray(1, 1 + 4));
        offset = 5;
    }
    return {
        len: len,
        offset: offset
    };
}
/**
 * Encodes a given integer of length to the openpgp length specifier to a
 * string
 *
 * @param {Integer} length - The length to encode
 * @returns {Uint8Array} String with openpgp length representation.
 */
function writeSimpleLength(length) {
    if (length < 192) {
        return new Uint8Array([length]);
    }
    else if (length > 191 && length < 8384) {
        /*
          * let a = (total data packet length) - 192 let bc = two octet
          * representation of a let d = b + 192
          */
        return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);
    }
    return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);
}
function writePartialLength(power) {
    if (power < 0 || power > 30) {
        throw new Error('Partial Length power must be between 1 and 30');
    }
    return new Uint8Array([224 + power]);
}
function writeTag(tag_type) {
    /* we're only generating v4 packet headers here */
    return new Uint8Array([0xC0 | tag_type]);
}
/**
 * Writes a packet header version 4 with the given tag_type and length to a
 * string
 *
 * @param {Integer} tag_type - Tag type
 * @param {Integer} length - Length of the payload
 * @returns {String} String of the header.
 */
function writeHeader(tag_type, length) {
    /* we're only generating v4 packet headers here */
    return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);
}
/**
 * Whether the packet type supports partial lengths per RFC4880
 * @param {Integer} tag - Tag type
 * @returns {Boolean} String of the header.
 */
function supportsStreaming(tag) {
    return [
        enums.packet.literalData,
        enums.packet.compressedData,
        enums.packet.symmetricallyEncryptedData,
        enums.packet.symEncryptedIntegrityProtectedData,
        enums.packet.aeadEncryptedData
    ].includes(tag);
}
/**
 * Generic static Packet Parser function
 *
 * @param {Uint8Array | ReadableStream<Uint8Array>} input - Input stream as string
 * @param {Function} callback - Function to call with the parsed packet
 * @returns {Promise<Boolean>} Returns false if the stream was empty and parsing is done, and true otherwise.
 */
async function readPacket(reader, useStreamType, callback) {
    let writer;
    let callbackReturned;
    try {
        const peekedBytes = await reader.peekBytes(2);
        // some sanity checks
        if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {
            throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');
        }
        const headerByte = await reader.readByte();
        let tag = -1;
        let format = -1;
        let packetLength;
        format = 0; // 0 = old format; 1 = new format
        if ((headerByte & 0x40) !== 0) {
            format = 1;
        }
        let packetLengthType;
        if (format) {
            // new format header
            tag = headerByte & 0x3F; // bit 5-0
        }
        else {
            // old format header
            tag = (headerByte & 0x3F) >> 2; // bit 5-2
            packetLengthType = headerByte & 0x03; // bit 1-0
        }
        const packetSupportsStreaming = supportsStreaming(tag);
        let packet = null;
        if (useStreamType && packetSupportsStreaming) {
            if (useStreamType === 'array') {
                const arrayStream = new ArrayStream();
                writer = getWriter(arrayStream);
                packet = arrayStream;
            }
            else {
                const transform = new TransformStream();
                writer = getWriter(transform.writable);
                packet = transform.readable;
            }
            callbackReturned = callback({ tag, packet });
        }
        else {
            packet = [];
        }
        let wasPartialLength;
        do {
            if (!format) {
                // 4.2.1. Old Format Packet Lengths
                switch (packetLengthType) {
                    case 0:
                        // The packet has a one-octet length. The header is 2 octets
                        // long.
                        packetLength = await reader.readByte();
                        break;
                    case 1:
                        // The packet has a two-octet length. The header is 3 octets
                        // long.
                        packetLength = (await reader.readByte() << 8) | await reader.readByte();
                        break;
                    case 2:
                        // The packet has a four-octet length. The header is 5
                        // octets long.
                        // The final `>>> 0` is needed because `<< 24` operates on signed 32-bit integers:
                        // without it, lengths >= 2**31 parse as negative
                        packetLength = ((await reader.readByte() << 24) | (await reader.readByte() << 16) |
                            (await reader.readByte() << 8) | await reader.readByte()) >>> 0;
                        break;
                    default:
                        // 3 - The packet is of indeterminate length. The header is 1
                        // octet long, and the implementation must determine how long
                        // the packet is. If the packet is in a file, this means that
                        // the packet extends until the end of the file. In general,
                        // an implementation SHOULD NOT use indeterminate-length
                        // packets except where the end of the data will be clear
                        // from the context, and even then it is better to use a
                        // definite length, or a new format header. The new format
                        // headers described below have a mechanism for precisely
                        // encoding data of indeterminate length.
                        packetLength = Infinity;
                        break;
                }
            }
            else { // 4.2.2. New Format Packet Lengths
                // 4.2.2.1. One-Octet Lengths
                const lengthByte = await reader.readByte();
                wasPartialLength = false;
                if (lengthByte < 192) {
                    packetLength = lengthByte;
                    // 4.2.2.2. Two-Octet Lengths
                }
                else if (lengthByte >= 192 && lengthByte < 224) {
                    packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;
                    // 4.2.2.4. Partial Body Lengths
                }
                else if (lengthByte > 223 && lengthByte < 255) {
                    packetLength = 1 << (lengthByte & 0x1F);
                    wasPartialLength = true;
                    if (!packetSupportsStreaming) {
                        throw new TypeError('This packet type does not support partial lengths.');
                    }
                    // 4.2.2.3. Five-Octet Lengths
                }
                else {
                    // The final `>>> 0` is needed because `<< 24` operates on signed 32-bit integers:
                    // without it, lengths >= 2**31 parse as negative
                    packetLength = ((await reader.readByte() << 24) | (await reader.readByte() << 16) |
                        (await reader.readByte() << 8) | await reader.readByte()) >>> 0;
                }
            }
            if (packetLength > 0) {
                let bytesRead = 0;
                while (true) {
                    if (writer)
                        await writer.ready;
                    const { done, value } = await reader.read();
                    if (done) {
                        if (packetLength === Infinity)
                            break;
                        throw new Error('Unexpected end of packet');
                    }
                    const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);
                    if (writer)
                        await writer.write(chunk);
                    else
                        packet.push(chunk);
                    bytesRead += value.length;
                    if (bytesRead >= packetLength) {
                        reader.unshift(value.subarray(packetLength - bytesRead + value.length));
                        break;
                    }
                }
            }
        } while (wasPartialLength);
        if (writer) {
            await writer.ready;
            await writer.close();
        }
        else {
            packet = util.concatUint8Array(packet);
            await callback({ tag, packet });
        }
    }
    catch (e) {
        if (writer) {
            await writer.abort(e);
            return true;
        }
        else {
            throw e;
        }
    }
    finally {
        if (writer) {
            await callbackReturned;
        }
    }
}
class UnsupportedError extends Error {
    constructor(...params) {
        super(...params);
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, UnsupportedError);
        }
        this.name = 'UnsupportedError';
    }
}
// unknown packet types are handled differently depending on the packet criticality
class UnknownPacketError extends UnsupportedError {
    constructor(...params) {
        super(...params);
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, UnsupportedError);
        }
        this.name = 'UnknownPacketError';
    }
}
class MalformedPacketError extends UnsupportedError {
    constructor(...params) {
        super(...params);
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, UnsupportedError);
        }
        this.name = 'MalformedPacketError';
    }
}
class UnparseablePacket {
    constructor(tag, rawContent) {
        this.tag = tag;
        this.rawContent = rawContent;
    }
    write() {
        return this.rawContent;
    }
}

// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2018 Proton Technologies AG
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview Implementation of EdDSA following RFC4880bis-03 for OpenPGP
 * @module crypto/public_key/elliptic/eddsa
 * @access private
 */
/**
 * Generate (non-legacy) EdDSA key
 * @param {module:enums.publicKey} algo - Algorithm identifier
 * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>}
 */
async function generate$3(algo) {
    switch (algo) {
        case enums.publicKey.ed25519:
            try {
                const webCrypto = util.getWebCrypto();
                const webCryptoKey = await webCrypto.generateKey('Ed25519', true, ['sign', 'verify'])
                    .catch(err => {
                    if (err.name === 'OperationError') { // Temporary (hopefully) fix for WebKit on Linux
                        const newErr = new Error('Unexpected key generation issue');
                        newErr.name = 'NotSupportedError';
                        throw newErr;
                    }
                    throw err;
                });
                const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);
                const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);
                return {
                    A: new Uint8Array(b64ToUint8Array(publicKey.x)),
                    seed: b64ToUint8Array(privateKey.d, true)
                };
            }
            catch (err) {
                if (err.name !== 'NotSupportedError') {
                    throw err;
                }
                const { default: ed25519 } = await Promise.resolve().then(function () { return naclFast; });
                const seed = getRandomBytes(getPayloadSize$1(algo));
                // not using `ed25519.sign.keyPair` since it returns the expanded secret, so using `fromSeed` instead is more straightforward
                const { publicKey: A } = ed25519.sign.keyPair.fromSeed(seed);
                return { A, seed };
            }
        case enums.publicKey.ed448: {
            const ed448 = await util.getNobleCurve(enums.publicKey.ed448);
            const { secretKey: seed, publicKey: A } = ed448.keygen();
            return { A, seed };
        }
        default:
            throw new Error('Unsupported EdDSA algorithm');
    }
}
/**
 * Sign a message using the provided key
 * @param {module:enums.publicKey} algo - Algorithm identifier
 * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)
 * @param {Uint8Array} message - Message to sign
 * @param {Uint8Array} publicKey - Public key
 * @param {Uint8Array} privateKey - Private key used to sign the message
 * @param {Uint8Array} hashed - The hashed message
 * @returns {Promise<{
 *   RS: Uint8Array
 * }>} Signature of the message
 * @async
 */
async function sign$5(algo, hashAlgo, message, publicKey, privateKey, hashed) {
    if (getHashByteLength(hashAlgo) < getHashByteLength(getPreferredHashAlgo$2(algo))) {
        // Enforce digest sizes:
        // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4
        // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4
        throw new Error('Hash algorithm too weak for EdDSA.');
    }
    switch (algo) {
        case enums.publicKey.ed25519:
            try {
                const webCrypto = util.getWebCrypto();
                const jwk = privateKeyToJWK$1(algo, publicKey, privateKey);
                const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['sign']);
                const signature = new Uint8Array(await webCrypto.sign('Ed25519', key, hashed));
                return { RS: signature };
            }
            catch (err) {
                if (err.name !== 'NotSupportedError') {
                    throw err;
                }
                const { default: ed25519 } = await Promise.resolve().then(function () { return naclFast; });
                const secretKey = util.concatUint8Array([privateKey, publicKey]);
                const signature = ed25519.sign.detached(hashed, secretKey);
                return { RS: signature };
            }
        case enums.publicKey.ed448: {
            const ed448 = await util.getNobleCurve(enums.publicKey.ed448);
            const signature = ed448.sign(hashed, privateKey);
            return { RS: signature };
        }
        default:
            throw new Error('Unsupported EdDSA algorithm');
    }
}
/**
 * Verifies if a signature is valid for a message
 * @param {module:enums.publicKey} algo - Algorithm identifier
 * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature
 * @param  {{ RS: Uint8Array }} signature Signature to verify the message
 * @param {Uint8Array} m - Message to verify
 * @param {Uint8Array} publicKey - Public key used to verify the message
 * @param {Uint8Array} hashed - The hashed message
 * @returns {Boolean}
 * @async
 */
async function verify$5(algo, hashAlgo, { RS }, m, publicKey, hashed) {
    if (getHashByteLength(hashAlgo) < getHashByteLength(getPreferredHashAlgo$2(algo))) {
        // Enforce digest sizes:
        // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4
        // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4
        throw new Error('Hash algorithm too weak for EdDSA.');
    }
    switch (algo) {
        case enums.publicKey.ed25519:
            try {
                const webCrypto = util.getWebCrypto();
                const jwk = publicKeyToJWK$1(algo, publicKey);
                const key = await webCrypto.importKey('jwk', jwk, 'Ed25519', false, ['verify']);
                const verified = await webCrypto.verify('Ed25519', key, RS, hashed);
                return verified;
            }
            catch (err) {
                if (err.name !== 'NotSupportedError') {
                    throw err;
                }
                const { default: ed25519 } = await Promise.resolve().then(function () { return naclFast; });
                return ed25519.sign.detached.verify(hashed, RS, publicKey);
            }
        case enums.publicKey.ed448: {
            const ed448 = await util.getNobleCurve(enums.publicKey.ed448);
            return ed448.verify(RS, hashed, publicKey);
        }
        default:
            throw new Error('Unsupported EdDSA algorithm');
    }
}
/**
 * Validate (non-legacy) EdDSA parameters
 * @param {module:enums.publicKey} algo - Algorithm identifier
 * @param {Uint8Array} A - EdDSA public point
 * @param {Uint8Array} seed - EdDSA secret seed
 * @param {Uint8Array} oid - (legacy only) EdDSA OID
 * @returns {Promise<Boolean>} Whether params are valid.
 * @async
 */
async function validateParams$7(algo, A, seed) {
    switch (algo) {
        case enums.publicKey.ed25519:
            // If webcrypto support is available, we sign-verify random data, as the import-export
            // functions might not implement validity checks.
            // If we need to fallback to JS, we instead only re-derive the public key,
            // as this is much faster than sign-verify.
            try {
                const webCrypto = util.getWebCrypto();
                const jwkPrivate = privateKeyToJWK$1(algo, A, seed);
                const jwkPublic = publicKeyToJWK$1(algo, A);
                const privateCryptoKey = await webCrypto.importKey('jwk', jwkPrivate, 'Ed25519', false, ['sign']);
                const publicCryptoKey = await webCrypto.importKey('jwk', jwkPublic, 'Ed25519', false, ['verify']);
                const randomData = getRandomBytes(8);
                const signature = new Uint8Array(await webCrypto.sign('Ed25519', privateCryptoKey, randomData));
                const verified = await webCrypto.verify('Ed25519', publicCryptoKey, signature, randomData);
                return verified;
            }
            catch (err) {
                if (err.name !== 'NotSupportedError') {
                    return false;
                }
                const { default: ed25519 } = await Promise.resolve().then(function () { return naclFast; });
                const { publicKey } = ed25519.sign.keyPair.fromSeed(seed);
                return util.equalsUint8Array(A, publicKey);
            }
        case enums.publicKey.ed448: {
            const ed448 = await util.getNobleCurve(enums.publicKey.ed448);
            const publicKey = ed448.getPublicKey(seed);
            return util.equalsUint8Array(A, publicKey);
        }
        default:
            return false;
    }
}
function getPayloadSize$1(algo) {
    switch (algo) {
        case enums.publicKey.ed25519:
            return 32;
        case enums.publicKey.ed448:
            return 57;
        default:
            throw new Error('Unsupported EdDSA algorithm');
    }
}
function getPreferredHashAlgo$2(algo) {
    switch (algo) {
        case enums.publicKey.ed25519:
            return enums.hash.sha256;
        case enums.publicKey.ed448:
            return enums.hash.sha512;
        default:
            throw new Error('Unknown EdDSA algo');
    }
}
const publicKeyToJWK$1 = (algo, publicKey) => {
    switch (algo) {
        case enums.publicKey.ed25519: {
            const jwk = {
                kty: 'OKP',
                crv: 'Ed25519',
                x: uint8ArrayToB64(publicKey),
                ext: true
            };
            return jwk;
        }
        default:
            throw new Error('Unsupported EdDSA algorithm');
    }
};
const privateKeyToJWK$1 = (algo, publicKey, privateKey) => {
    switch (algo) {
        case enums.publicKey.ed25519: {
            const jwk = publicKeyToJWK$1(algo, publicKey);
            jwk.d = uint8ArrayToB64(privateKey);
            return jwk;
        }
        default:
            throw new Error('Unsupported EdDSA algorithm');
    }
};

var eddsa$1 = /*#__PURE__*/Object.freeze({
  __proto__: null,
  generate: generate$3,
  getPayloadSize: getPayloadSize$1,
  getPreferredHashAlgo: getPreferredHashAlgo$2,
  sign: sign$5,
  validateParams: validateParams$7,
  verify: verify$5
});

/**
 * Utilities for hex, bytes, CSPRNG.
 * @module
 */
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
function isBytes$1(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is Uint8Array. */
function abytes$1(b, ...lengths) {
    if (!isBytes$1(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/** Asserts a hash instance has not been destroyed / finished */
function aexists$1(instance, checkFinished = true) {
    if (instance.destroyed)
        throw new Error('Hash instance has been destroyed');
    if (checkFinished && instance.finished)
        throw new Error('Hash#digest() has already been called');
}
/** Asserts output is properly-sized byte array */
function aoutput$1(out, instance) {
    abytes$1(out);
    const min = instance.outputLen;
    if (out.length < min) {
        throw new Error('digestInto() expects output buffer of length at least ' + min);
    }
}
/** Cast u8 / u16 / u32 to u8. */
function u8$1(arr) {
    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
function u32$1(arr) {
    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
function clean$1(...arrays) {
    for (let i = 0; i < arrays.length; i++) {
        arrays[i].fill(0);
    }
}
/** Create DataView of an array for easy byte-level manipulation. */
function createView$1(arr) {
    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
const isLE$1 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/**
 * Converts string to bytes using UTF8 encoding.
 * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
 */
function utf8ToBytes$1(str) {
    if (typeof str !== 'string')
        throw new Error('string expected');
    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
 * Normalizes (non-hex) string or Uint8Array to Uint8Array.
 * Warning: when Uint8Array is passed, it would NOT get copied.
 * Keep in mind for future mutable operations.
 */
function toBytes$1(data) {
    if (typeof data === 'string')
        data = utf8ToBytes$1(data);
    else if (isBytes$1(data))
        data = copyBytes$1(data);
    else
        throw new Error('Uint8Array expected, got ' + typeof data);
    return data;
}
/**
 * Checks if two U8A use same underlying buffer and overlaps.
 * This is invalid and can corrupt data.
 */
function overlapBytes(a, b) {
    return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
        a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
        b.byteOffset < a.byteOffset + a.byteLength // b starts before a end
    );
}
/**
 * If input and output overlap and input starts before output, we will overwrite end of input before
 * we start processing it, so this is not supported for most ciphers (except chacha/salse, which designed with this)
 */
function complexOverlapBytes(input, output) {
    // This is very cursed. It works somehow, but I'm completely unsure,
    // reasoning about overlapping aligned windows is very hard.
    if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
        throw new Error('complex overlap of input and output is not supported');
}
/**
 * Copies several Uint8Arrays into one.
 */
function concatBytes$1(...arrays) {
    let sum = 0;
    for (let i = 0; i < arrays.length; i++) {
        const a = arrays[i];
        abytes$1(a);
        sum += a.length;
    }
    const res = new Uint8Array(sum);
    for (let i = 0, pad = 0; i < arrays.length; i++) {
        const a = arrays[i];
        res.set(a, pad);
        pad += a.length;
    }
    return res;
}
/** Compares 2 uint8array-s in kinda constant time. */
function equalBytes(a, b) {
    if (a.length !== b.length)
        return false;
    let diff = 0;
    for (let i = 0; i < a.length; i++)
        diff |= a[i] ^ b[i];
    return diff === 0;
}
/**
 * Wraps a cipher: validates args, ensures encrypt() can only be called once.
 * @__NO_SIDE_EFFECTS__
 */
const wrapCipher = (params, constructor) => {
    function wrappedCipher(key, ...args) {
        // Validate key
        abytes$1(key);
        // Big-Endian hardware is rare. Just in case someone still decides to run ciphers:
        if (!isLE$1)
            throw new Error('Non little-endian hardware is not yet supported');
        // Validate nonce if nonceLength is present
        if (params.nonceLength !== undefined) {
            const nonce = args[0];
            if (!nonce)
                throw new Error('nonce / iv required');
            if (params.varSizeNonce)
                abytes$1(nonce);
            else
                abytes$1(nonce, params.nonceLength);
        }
        // Validate AAD if tagLength present
        const tagl = params.tagLength;
        if (tagl && args[1] !== undefined) {
            abytes$1(args[1]);
        }
        const cipher = constructor(key, ...args);
        const checkOutput = (fnLength, output) => {
            if (output !== undefined) {
                if (fnLength !== 2)
                    throw new Error('cipher output not supported');
                abytes$1(output);
            }
        };
        // Create wrapped cipher with validation and single-use encryption
        let called = false;
        const wrCipher = {
            encrypt(data, output) {
                if (called)
                    throw new Error('cannot encrypt() twice with same key + nonce');
                called = true;
                abytes$1(data);
                checkOutput(cipher.encrypt.length, output);
                return cipher.encrypt(data, output);
            },
            decrypt(data, output) {
                abytes$1(data);
                if (tagl && data.length < tagl)
                    throw new Error('invalid ciphertext length: smaller than tagLength=' + tagl);
                checkOutput(cipher.decrypt.length, output);
                return cipher.decrypt(data, output);
            },
        };
        return wrCipher;
    }
    Object.assign(wrappedCipher, params);
    return wrappedCipher;
};
/**
 * By default, returns u8a of length.
 * When out is available, it checks it for validity and uses it.
 */
function getOutput(expectedLength, out, onlyAligned = true) {
    if (out === undefined)
        return new Uint8Array(expectedLength);
    if (out.length !== expectedLength)
        throw new Error('invalid output length, expected ' + expectedLength + ', got: ' + out.length);
    if (onlyAligned && !isAligned32(out))
        throw new Error('invalid output, must be aligned');
    return out;
}
/** Polyfill for Safari 14. */
function setBigUint64$1(view, byteOffset, value, isLE) {
    if (typeof view.setBigUint64 === 'function')
        return view.setBigUint64(byteOffset, value, isLE);
    const _32n = BigInt(32);
    const _u32_max = BigInt(0xffffffff);
    const wh = Number((value >> _32n) & _u32_max);
    const wl = Number(value & _u32_max);
    const h = 0;
    const l = 4;
    view.setUint32(byteOffset + h, wh, isLE);
    view.setUint32(byteOffset + l, wl, isLE);
}
function u64Lengths(dataLength, aadLength, isLE) {
    const num = new Uint8Array(16);
    const view = createView$1(num);
    setBigUint64$1(view, 0, BigInt(aadLength), isLE);
    setBigUint64$1(view, 8, BigInt(dataLength), isLE);
    return num;
}
// Is byte array aligned to 4 byte offset (u32)?
function isAligned32(bytes) {
    return bytes.byteOffset % 4 === 0;
}
// copy bytes to new u8a (aligned). Because Buffer.slice is broken.
function copyBytes$1(bytes) {
    return Uint8Array.from(bytes);
}

/**
 * GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV.
 *
 * Implemented in terms of GHash with conversion function for keys
 * GCM GHASH from
 * [NIST SP800-38d](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf),
 * SIV from
 * [RFC 8452](https://datatracker.ietf.org/doc/html/rfc8452).
 *
 * GHASH   modulo: x^128 + x^7   + x^2   + x     + 1
 * POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
 *
 * @module
 */
// prettier-ignore
const BLOCK_SIZE$1 = 16;
// TODO: rewrite
// temporary padding buffer
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
const ZEROS32 = u32$1(ZEROS16);
const POLY$1 = 0xe1; // v = 2*v % POLY
// v = 2*v % POLY
// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x
// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor)
const mul2$1 = (s0, s1, s2, s3) => {
    const hiBit = s3 & 1;
    return {
        s3: (s2 << 31) | (s3 >>> 1),
        s2: (s1 << 31) | (s2 >>> 1),
        s1: (s0 << 31) | (s1 >>> 1),
        s0: (s0 >>> 1) ^ ((POLY$1 << 24) & -(hiBit & 1)), // reduce % poly
    };
};
const swapLE = (n) => (((n >>> 0) & 0xff) << 24) |
    (((n >>> 8) & 0xff) << 16) |
    (((n >>> 16) & 0xff) << 8) |
    ((n >>> 24) & 0xff) |
    0;
/**
 * `mulX_POLYVAL(ByteReverse(H))` from spec
 * @param k mutated in place
 */
function _toGHASHKey(k) {
    k.reverse();
    const hiBit = k[15] & 1;
    // k >>= 1
    let carry = 0;
    for (let i = 0; i < k.length; i++) {
        const t = k[i];
        k[i] = (t >>> 1) | carry;
        carry = (t & 1) << 7;
    }
    k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;
    return k;
}
const estimateWindow = (bytes) => {
    if (bytes > 64 * 1024)
        return 8;
    if (bytes > 1024)
        return 4;
    return 2;
};
class GHASH {
    // We select bits per window adaptively based on expectedLength
    constructor(key, expectedLength) {
        this.blockLen = BLOCK_SIZE$1;
        this.outputLen = BLOCK_SIZE$1;
        this.s0 = 0;
        this.s1 = 0;
        this.s2 = 0;
        this.s3 = 0;
        this.finished = false;
        key = toBytes$1(key);
        abytes$1(key, 16);
        const kView = createView$1(key);
        let k0 = kView.getUint32(0, false);
        let k1 = kView.getUint32(4, false);
        let k2 = kView.getUint32(8, false);
        let k3 = kView.getUint32(12, false);
        // generate table of doubled keys (half of montgomery ladder)
        const doubles = [];
        for (let i = 0; i < 128; i++) {
            doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });
            ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2$1(k0, k1, k2, k3));
        }
        const W = estimateWindow(expectedLength || 1024);
        if (![1, 2, 4, 8].includes(W))
            throw new Error('ghash: invalid window size, expected 2, 4 or 8');
        this.W = W;
        const bits = 128; // always 128 bits;
        const windows = bits / W;
        const windowSize = (this.windowSize = 2 ** W);
        const items = [];
        // Create precompute table for window of W bits
        for (let w = 0; w < windows; w++) {
            // truth table: 00, 01, 10, 11
            for (let byte = 0; byte < windowSize; byte++) {
                // prettier-ignore
                let s0 = 0, s1 = 0, s2 = 0, s3 = 0;
                for (let j = 0; j < W; j++) {
                    const bit = (byte >>> (W - j - 1)) & 1;
                    if (!bit)
                        continue;
                    const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];
                    (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3);
                }
                items.push({ s0, s1, s2, s3 });
            }
        }
        this.t = items;
    }
    _updateBlock(s0, s1, s2, s3) {
        (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3);
        const { W, t, windowSize } = this;
        // prettier-ignore
        let o0 = 0, o1 = 0, o2 = 0, o3 = 0;
        const mask = (1 << W) - 1; // 2**W will kill performance.
        let w = 0;
        for (const num of [s0, s1, s2, s3]) {
            for (let bytePos = 0; bytePos < 4; bytePos++) {
                const byte = (num >>> (8 * bytePos)) & 0xff;
                for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {
                    const bit = (byte >>> (W * bitPos)) & mask;
                    const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];
                    (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3);
                    w += 1;
                }
            }
        }
        this.s0 = o0;
        this.s1 = o1;
        this.s2 = o2;
        this.s3 = o3;
    }
    update(data) {
        aexists$1(this);
        data = toBytes$1(data);
        abytes$1(data);
        const b32 = u32$1(data);
        const blocks = Math.floor(data.length / BLOCK_SIZE$1);
        const left = data.length % BLOCK_SIZE$1;
        for (let i = 0; i < blocks; i++) {
            this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);
        }
        if (left) {
            ZEROS16.set(data.subarray(blocks * BLOCK_SIZE$1));
            this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);
            clean$1(ZEROS32); // clean tmp buffer
        }
        return this;
    }
    destroy() {
        const { t } = this;
        // clean precompute table
        for (const elm of t) {
            (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0);
        }
    }
    digestInto(out) {
        aexists$1(this);
        aoutput$1(out, this);
        this.finished = true;
        const { s0, s1, s2, s3 } = this;
        const o32 = u32$1(out);
        o32[0] = s0;
        o32[1] = s1;
        o32[2] = s2;
        o32[3] = s3;
        return out;
    }
    digest() {
        const res = new Uint8Array(BLOCK_SIZE$1);
        this.digestInto(res);
        this.destroy();
        return res;
    }
}
class Polyval extends GHASH {
    constructor(key, expectedLength) {
        key = toBytes$1(key);
        abytes$1(key);
        const ghKey = _toGHASHKey(copyBytes$1(key));
        super(ghKey, expectedLength);
        clean$1(ghKey);
    }
    update(data) {
        data = toBytes$1(data);
        aexists$1(this);
        const b32 = u32$1(data);
        const left = data.length % BLOCK_SIZE$1;
        const blocks = Math.floor(data.length / BLOCK_SIZE$1);
        for (let i = 0; i < blocks; i++) {
            this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0]));
        }
        if (left) {
            ZEROS16.set(data.subarray(blocks * BLOCK_SIZE$1));
            this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0]));
            clean$1(ZEROS32);
        }
        return this;
    }
    digestInto(out) {
        aexists$1(this);
        aoutput$1(out, this);
        this.finished = true;
        // tmp ugly hack
        const { s0, s1, s2, s3 } = this;
        const o32 = u32$1(out);
        o32[0] = s0;
        o32[1] = s1;
        o32[2] = s2;
        o32[3] = s3;
        return out.reverse();
    }
}
function wrapConstructorWithKey(hashCons) {
    const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes$1(msg)).digest();
    const tmp = hashCons(new Uint8Array(16), 0);
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (key, expectedLength) => hashCons(key, expectedLength);
    return hashC;
}
/** GHash MAC for AES-GCM. */
const ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength));
/** Polyval MAC for AES-SIV. */
wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength));

/**
 * [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
 * a.k.a. Advanced Encryption Standard
 * is a variant of Rijndael block cipher, standardized by NIST in 2001.
 * We provide the fastest available pure JS implementation.
 *
 * Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:
 * 1. **S-box**, table substitution
 * 2. **Shift rows**, cyclic shift left of all rows of data array
 * 3. **Mix columns**, multiplying every column by fixed polynomial
 * 4. **Add round key**, round_key xor i-th column of array
 *
 * Check out [FIPS-197](https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf)
 * and [original proposal](https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf)
 * @module
 */
const BLOCK_SIZE = 16;
const BLOCK_SIZE32 = 4;
const EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE);
const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8
// TODO: remove multiplication, binary ops only
function mul2(n) {
    return (n << 1) ^ (POLY & -(n >> 7));
}
function mul(a, b) {
    let res = 0;
    for (; b > 0; b >>= 1) {
        // Montgomery ladder
        res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).
        a = mul2(a); // a = 2*a
    }
    return res;
}
// AES S-box is generated using finite field inversion,
// an affine transform, and xor of a constant 0x63.
const sbox = /* @__PURE__ */ (() => {
    const t = new Uint8Array(256);
    for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))
        t[i] = x;
    const box = new Uint8Array(256);
    box[0] = 0x63; // first elm
    for (let i = 0; i < 255; i++) {
        let x = t[255 - i];
        x |= x << 8;
        box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;
    }
    clean$1(t);
    return box;
})();
// Inverted S-box
const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));
// Rotate u32 by 8
const rotr32_8 = (n) => (n << 24) | (n >>> 8);
const rotl32_8 = (n) => (n << 8) | (n >>> 24);
// The byte swap operation for uint32 (LE<->BE)
const byteSwap$1 = (word) => ((word << 24) & 0xff000000) |
    ((word << 8) & 0xff0000) |
    ((word >>> 8) & 0xff00) |
    ((word >>> 24) & 0xff);
// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:
// - LE instead of BE
// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;
//   so index is u16, instead of u8. This speeds up things, unexpectedly
function genTtable(sbox, fn) {
    if (sbox.length !== 256)
        throw new Error('Wrong sbox length');
    const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));
    const T1 = T0.map(rotl32_8);
    const T2 = T1.map(rotl32_8);
    const T3 = T2.map(rotl32_8);
    const T01 = new Uint32Array(256 * 256);
    const T23 = new Uint32Array(256 * 256);
    const sbox2 = new Uint16Array(256 * 256);
    for (let i = 0; i < 256; i++) {
        for (let j = 0; j < 256; j++) {
            const idx = i * 256 + j;
            T01[idx] = T0[i] ^ T1[j];
            T23[idx] = T2[i] ^ T3[j];
            sbox2[idx] = (sbox[i] << 8) | sbox[j];
        }
    }
    return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };
}
const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));
const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));
const xPowers = /* @__PURE__ */ (() => {
    const p = new Uint8Array(16);
    for (let i = 0, x = 1; i < 16; i++, x = mul2(x))
        p[i] = x;
    return p;
})();
/** Key expansion used in CTR. */
function expandKeyLE(key) {
    abytes$1(key);
    const len = key.length;
    if (![16, 24, 32].includes(len))
        throw new Error('aes: invalid key size, should be 16, 24 or 32, got ' + len);
    const { sbox2 } = tableEncoding;
    const toClean = [];
    if (!isAligned32(key))
        toClean.push((key = copyBytes$1(key)));
    const k32 = u32$1(key);
    const Nk = k32.length;
    const subByte = (n) => applySbox(sbox2, n, n, n, n);
    const xk = new Uint32Array(len + 28); // expanded key
    xk.set(k32);
    // 4.3.1 Key expansion
    for (let i = Nk; i < xk.length; i++) {
        let t = xk[i - 1];
        if (i % Nk === 0)
            t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
        else if (Nk > 6 && i % Nk === 4)
            t = subByte(t);
        xk[i] = xk[i - Nk] ^ t;
    }
    clean$1(...toClean);
    return xk;
}
function expandKeyDecLE(key) {
    const encKey = expandKeyLE(key);
    const xk = encKey.slice();
    const Nk = encKey.length;
    const { sbox2 } = tableEncoding;
    const { T0, T1, T2, T3 } = tableDecoding;
    // Inverse key by chunks of 4 (rounds)
    for (let i = 0; i < Nk; i += 4) {
        for (let j = 0; j < 4; j++)
            xk[i + j] = encKey[Nk - i - 4 + j];
    }
    clean$1(encKey);
    // apply InvMixColumn except first & last round
    for (let i = 4; i < Nk - 4; i++) {
        const x = xk[i];
        const w = applySbox(sbox2, x, x, x, x);
        xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];
    }
    return xk;
}
// Apply tables
function apply0123(T01, T23, s0, s1, s2, s3) {
    return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^
        T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);
}
function applySbox(sbox2, s0, s1, s2, s3) {
    return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |
        (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));
}
function encrypt$4(xk, s0, s1, s2, s3) {
    const { sbox2, T01, T23 } = tableEncoding;
    let k = 0;
    (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);
    const rounds = xk.length / 4 - 2;
    for (let i = 0; i < rounds; i++) {
        const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
        const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
        const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
        const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
        (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);
    }
    // last round (without mixcolumns, so using SBOX2 table)
    const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
    const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
    const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
    const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
    return { s0: t0, s1: t1, s2: t2, s3: t3 };
}
// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different
function decrypt$4(xk, s0, s1, s2, s3) {
    const { sbox2, T01, T23 } = tableDecoding;
    let k = 0;
    (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);
    const rounds = xk.length / 4 - 2;
    for (let i = 0; i < rounds; i++) {
        const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);
        const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);
        const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);
        const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);
        (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);
    }
    // Last round
    const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);
    const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);
    const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);
    const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
    return { s0: t0, s1: t1, s2: t2, s3: t3 };
}
// TODO: investigate merging with ctr32
function ctrCounter(xk, nonce, src, dst) {
    abytes$1(nonce, BLOCK_SIZE);
    abytes$1(src);
    const srcLen = src.length;
    dst = getOutput(srcLen, dst);
    complexOverlapBytes(src, dst);
    const ctr = nonce;
    const c32 = u32$1(ctr);
    // Fill block (empty, ctr=0)
    let { s0, s1, s2, s3 } = encrypt$4(xk, c32[0], c32[1], c32[2], c32[3]);
    const src32 = u32$1(src);
    const dst32 = u32$1(dst);
    // process blocks
    for (let i = 0; i + 4 <= src32.length; i += 4) {
        dst32[i + 0] = src32[i + 0] ^ s0;
        dst32[i + 1] = src32[i + 1] ^ s1;
        dst32[i + 2] = src32[i + 2] ^ s2;
        dst32[i + 3] = src32[i + 3] ^ s3;
        // Full 128 bit counter with wrap around
        let carry = 1;
        for (let i = ctr.length - 1; i >= 0; i--) {
            carry = (carry + (ctr[i] & 0xff)) | 0;
            ctr[i] = carry & 0xff;
            carry >>>= 8;
        }
        ({ s0, s1, s2, s3 } = encrypt$4(xk, c32[0], c32[1], c32[2], c32[3]));
    }
    // leftovers (less than block)
    // It's possible to handle > u32 fast, but is it worth it?
    const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
    if (start < srcLen) {
        const b32 = new Uint32Array([s0, s1, s2, s3]);
        const buf = u8$1(b32);
        for (let i = start, pos = 0; i < srcLen; i++, pos++)
            dst[i] = src[i] ^ buf[pos];
        clean$1(b32);
    }
    return dst;
}
// AES CTR with overflowing 32 bit counter
// It's possible to do 32le significantly simpler (and probably faster) by using u32.
// But, we need both, and perf bottleneck is in ghash anyway.
function ctr32(xk, isLE, nonce, src, dst) {
    abytes$1(nonce, BLOCK_SIZE);
    abytes$1(src);
    dst = getOutput(src.length, dst);
    const ctr = nonce; // write new value to nonce, so it can be re-used
    const c32 = u32$1(ctr);
    const view = createView$1(ctr);
    const src32 = u32$1(src);
    const dst32 = u32$1(dst);
    const ctrPos = isLE ? 0 : 12;
    const srcLen = src.length;
    // Fill block (empty, ctr=0)
    let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value
    let { s0, s1, s2, s3 } = encrypt$4(xk, c32[0], c32[1], c32[2], c32[3]);
    // process blocks
    for (let i = 0; i + 4 <= src32.length; i += 4) {
        dst32[i + 0] = src32[i + 0] ^ s0;
        dst32[i + 1] = src32[i + 1] ^ s1;
        dst32[i + 2] = src32[i + 2] ^ s2;
        dst32[i + 3] = src32[i + 3] ^ s3;
        ctrNum = (ctrNum + 1) >>> 0; // u32 wrap
        view.setUint32(ctrPos, ctrNum, isLE);
        ({ s0, s1, s2, s3 } = encrypt$4(xk, c32[0], c32[1], c32[2], c32[3]));
    }
    // leftovers (less than a block)
    const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
    if (start < srcLen) {
        const b32 = new Uint32Array([s0, s1, s2, s3]);
        const buf = u8$1(b32);
        for (let i = start, pos = 0; i < srcLen; i++, pos++)
            dst[i] = src[i] ^ buf[pos];
        clean$1(b32);
    }
    return dst;
}
/**
 * CTR: counter mode. Creates stream cipher.
 * Requires good IV. Parallelizable. OK, but no MAC.
 */
const ctr = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) {
    function processCtr(buf, dst) {
        abytes$1(buf);
        if (dst !== undefined) {
            abytes$1(dst);
            if (!isAligned32(dst))
                throw new Error('unaligned destination');
        }
        const xk = expandKeyLE(key);
        const n = copyBytes$1(nonce); // align + avoid changing
        const toClean = [xk, n];
        if (!isAligned32(buf))
            toClean.push((buf = copyBytes$1(buf)));
        const out = ctrCounter(xk, n, buf, dst);
        clean$1(...toClean);
        return out;
    }
    return {
        encrypt: (plaintext, dst) => processCtr(plaintext, dst),
        decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),
    };
});
function validateBlockDecrypt(data) {
    abytes$1(data);
    if (data.length % BLOCK_SIZE !== 0) {
        throw new Error('aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE);
    }
}
function validateBlockEncrypt(plaintext, pcks5, dst) {
    abytes$1(plaintext);
    let outLen = plaintext.length;
    const remaining = outLen % BLOCK_SIZE;
    if (!pcks5 && remaining !== 0)
        throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');
    if (!isAligned32(plaintext))
        plaintext = copyBytes$1(plaintext);
    const b = u32$1(plaintext);
    if (pcks5) {
        let left = BLOCK_SIZE - remaining;
        if (!left)
            left = BLOCK_SIZE; // if no bytes left, create empty padding block
        outLen = outLen + left;
    }
    dst = getOutput(outLen, dst);
    complexOverlapBytes(plaintext, dst);
    const o = u32$1(dst);
    return { b, o, out: dst };
}
function validatePCKS(data, pcks5) {
    if (!pcks5)
        return data;
    const len = data.length;
    if (!len)
        throw new Error('aes/pcks5: empty ciphertext not allowed');
    const lastByte = data[len - 1];
    if (lastByte <= 0 || lastByte > 16)
        throw new Error('aes/pcks5: wrong padding');
    const out = data.subarray(0, -lastByte);
    for (let i = 0; i < lastByte; i++)
        if (data[len - i - 1] !== lastByte)
            throw new Error('aes/pcks5: wrong padding');
    return out;
}
function padPCKS(left) {
    const tmp = new Uint8Array(16);
    const tmp32 = u32$1(tmp);
    tmp.set(left);
    const paddingByte = BLOCK_SIZE - left.length;
    for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)
        tmp[i] = paddingByte;
    return tmp32;
}
/**
 * CBC: Cipher-Block-Chaining. Key is previous round’s block.
 * Fragile: needs proper padding. Unauthenticated: needs MAC.
 */
const cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {
    const pcks5 = !opts.disablePadding;
    return {
        encrypt(plaintext, dst) {
            const xk = expandKeyLE(key);
            const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
            let _iv = iv;
            const toClean = [xk];
            if (!isAligned32(_iv))
                toClean.push((_iv = copyBytes$1(_iv)));
            const n32 = u32$1(_iv);
            // prettier-ignore
            let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
            let i = 0;
            for (; i + 4 <= b.length;) {
                (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);
                ({ s0, s1, s2, s3 } = encrypt$4(xk, s0, s1, s2, s3));
                (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
            }
            if (pcks5) {
                const tmp32 = padPCKS(plaintext.subarray(i * 4));
                (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);
                ({ s0, s1, s2, s3 } = encrypt$4(xk, s0, s1, s2, s3));
                (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
            }
            clean$1(...toClean);
            return _out;
        },
        decrypt(ciphertext, dst) {
            validateBlockDecrypt(ciphertext);
            const xk = expandKeyDecLE(key);
            let _iv = iv;
            const toClean = [xk];
            if (!isAligned32(_iv))
                toClean.push((_iv = copyBytes$1(_iv)));
            const n32 = u32$1(_iv);
            dst = getOutput(ciphertext.length, dst);
            if (!isAligned32(ciphertext))
                toClean.push((ciphertext = copyBytes$1(ciphertext)));
            complexOverlapBytes(ciphertext, dst);
            const b = u32$1(ciphertext);
            const o = u32$1(dst);
            // prettier-ignore
            let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
            for (let i = 0; i + 4 <= b.length;) {
                // prettier-ignore
                const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;
                (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);
                const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt$4(xk, s0, s1, s2, s3);
                (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);
            }
            clean$1(...toClean);
            return validatePCKS(dst, pcks5);
        },
    };
});
/**
 * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.
 * Unauthenticated: needs MAC.
 */
const cfb = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescfb(key, iv) {
    function processCfb(src, isEncrypt, dst) {
        abytes$1(src);
        const srcLen = src.length;
        dst = getOutput(srcLen, dst);
        if (overlapBytes(src, dst))
            throw new Error('overlapping src and dst not supported.');
        const xk = expandKeyLE(key);
        let _iv = iv;
        const toClean = [xk];
        if (!isAligned32(_iv))
            toClean.push((_iv = copyBytes$1(_iv)));
        if (!isAligned32(src))
            toClean.push((src = copyBytes$1(src)));
        const src32 = u32$1(src);
        const dst32 = u32$1(dst);
        const next32 = isEncrypt ? dst32 : src32;
        const n32 = u32$1(_iv);
        // prettier-ignore
        let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
        for (let i = 0; i + 4 <= src32.length;) {
            const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt$4(xk, s0, s1, s2, s3);
            dst32[i + 0] = src32[i + 0] ^ e0;
            dst32[i + 1] = src32[i + 1] ^ e1;
            dst32[i + 2] = src32[i + 2] ^ e2;
            dst32[i + 3] = src32[i + 3] ^ e3;
            (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]);
        }
        // leftovers (less than block)
        const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
        if (start < srcLen) {
            ({ s0, s1, s2, s3 } = encrypt$4(xk, s0, s1, s2, s3));
            const buf = u8$1(new Uint32Array([s0, s1, s2, s3]));
            for (let i = start, pos = 0; i < srcLen; i++, pos++)
                dst[i] = src[i] ^ buf[pos];
            clean$1(buf);
        }
        clean$1(...toClean);
        return dst;
    }
    return {
        encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),
        decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst),
    };
});
// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen
function computeTag(fn, isLE, key, data, AAD) {
    const aadLength = AAD ? AAD.length : 0;
    const h = fn.create(key, data.length + aadLength);
    if (AAD)
        h.update(AAD);
    const num = u64Lengths(8 * data.length, 8 * aadLength, isLE);
    h.update(data);
    h.update(num);
    const res = h.digest();
    clean$1(num);
    return res;
}
/**
 * GCM: Galois/Counter Mode.
 * Modern, parallel version of CTR, with MAC.
 * Be careful: MACs can be forged.
 * Unsafe to use random nonces under the same key, due to collision chance.
 * As for nonce size, prefer 12-byte, instead of 8-byte.
 */
const gcm = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true }, function aesgcm(key, nonce, AAD) {
    // NIST 800-38d doesn't enforce minimum nonce length.
    // We enforce 8 bytes for compat with openssl.
    // 12 bytes are recommended. More than 12 bytes would be converted into 12.
    if (nonce.length < 8)
        throw new Error('aes/gcm: invalid nonce length');
    const tagLength = 16;
    function _computeTag(authKey, tagMask, data) {
        const tag = computeTag(ghash, false, authKey, data, AAD);
        for (let i = 0; i < tagMask.length; i++)
            tag[i] ^= tagMask[i];
        return tag;
    }
    function deriveKeys() {
        const xk = expandKeyLE(key);
        const authKey = EMPTY_BLOCK.slice();
        const counter = EMPTY_BLOCK.slice();
        ctr32(xk, false, counter, counter, authKey);
        // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces
        if (nonce.length === 12) {
            counter.set(nonce);
        }
        else {
            const nonceLen = EMPTY_BLOCK.slice();
            const view = createView$1(nonceLen);
            setBigUint64$1(view, 8, BigInt(nonce.length * 8), false);
            // ghash(nonce || u64be(0) || u64be(nonceLen*8))
            const g = ghash.create(authKey).update(nonce).update(nonceLen);
            g.digestInto(counter); // digestInto doesn't trigger '.destroy'
            g.destroy();
        }
        const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);
        return { xk, authKey, counter, tagMask };
    }
    return {
        encrypt(plaintext) {
            const { xk, authKey, counter, tagMask } = deriveKeys();
            const out = new Uint8Array(plaintext.length + tagLength);
            const toClean = [xk, authKey, counter, tagMask];
            if (!isAligned32(plaintext))
                toClean.push((plaintext = copyBytes$1(plaintext)));
            ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));
            const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));
            toClean.push(tag);
            out.set(tag, plaintext.length);
            clean$1(...toClean);
            return out;
        },
        decrypt(ciphertext) {
            const { xk, authKey, counter, tagMask } = deriveKeys();
            const toClean = [xk, authKey, tagMask, counter];
            if (!isAligned32(ciphertext))
                toClean.push((ciphertext = copyBytes$1(ciphertext)));
            const data = ciphertext.subarray(0, -tagLength);
            const passedTag = ciphertext.subarray(-tagLength);
            const tag = _computeTag(authKey, tagMask, data);
            toClean.push(tag);
            if (!equalBytes(tag, passedTag))
                throw new Error('aes/gcm: invalid ghash tag');
            const out = ctr32(xk, false, counter, data);
            clean$1(...toClean);
            return out;
        },
    };
});
function isBytes32(a) {
    return (a instanceof Uint32Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array'));
}
function encryptBlock(xk, block) {
    abytes$1(block, 16);
    if (!isBytes32(xk))
        throw new Error('_encryptBlock accepts result of expandKeyLE');
    const b32 = u32$1(block);
    let { s0, s1, s2, s3 } = encrypt$4(xk, b32[0], b32[1], b32[2], b32[3]);
    (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);
    return block;
}
function decryptBlock(xk, block) {
    abytes$1(block, 16);
    if (!isBytes32(xk))
        throw new Error('_decryptBlock accepts result of expandKeyLE');
    const b32 = u32$1(block);
    let { s0, s1, s2, s3 } = decrypt$4(xk, b32[0], b32[1], b32[2], b32[3]);
    (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);
    return block;
}
/**
 * AES-W (base for AESKW/AESKWP).
 * Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf),
 * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),
 * [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/).
 */
const AESW = {
    /*
    High-level pseudocode:
    ```
    A: u64 = IV
    out = []
    for (let i=0, ctr = 0; i<6; i++) {
      for (const chunk of chunks(plaintext, 8)) {
        A ^= swapEndianess(ctr++)
        [A, res] = chunks(encrypt(A || chunk), 8);
        out ||= res
      }
    }
    out = A || out
    ```
    Decrypt is the same, but reversed.
    */
    encrypt(kek, out) {
        // Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints.
        // If you need it larger, open an issue.
        if (out.length >= 2 ** 32)
            throw new Error('plaintext should be less than 4gb');
        const xk = expandKeyLE(kek);
        if (out.length === 16)
            encryptBlock(xk, out);
        else {
            const o32 = u32$1(out);
            // prettier-ignore
            let a0 = o32[0], a1 = o32[1]; // A
            for (let j = 0, ctr = 1; j < 6; j++) {
                for (let pos = 2; pos < o32.length; pos += 2, ctr++) {
                    const { s0, s1, s2, s3 } = encrypt$4(xk, a0, a1, o32[pos], o32[pos + 1]);
                    // A = MSB(64, B) ^ t where t = (n*j)+i
                    (a0 = s0), (a1 = s1 ^ byteSwap$1(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3);
                }
            }
            (o32[0] = a0), (o32[1] = a1); // out = A || out
        }
        xk.fill(0);
    },
    decrypt(kek, out) {
        if (out.length - 8 >= 2 ** 32)
            throw new Error('ciphertext should be less than 4gb');
        const xk = expandKeyDecLE(kek);
        const chunks = out.length / 8 - 1; // first chunk is IV
        if (chunks === 1)
            decryptBlock(xk, out);
        else {
            const o32 = u32$1(out);
            // prettier-ignore
            let a0 = o32[0], a1 = o32[1]; // A
            for (let j = 0, ctr = chunks * 6; j < 6; j++) {
                for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {
                    a1 ^= byteSwap$1(ctr);
                    const { s0, s1, s2, s3 } = decrypt$4(xk, a0, a1, o32[pos], o32[pos + 1]);
                    (a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3);
                }
            }
            (o32[0] = a0), (o32[1] = a1);
        }
        xk.fill(0);
    },
};
const AESKW_IV = /* @__PURE__ */ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6
/**
 * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.
 * Reduces block size from 16 to 8 bytes.
 * For padded version, use aeskwp.
 * [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),
 * [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf).
 */
const aeskw = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({
    encrypt(plaintext) {
        if (!plaintext.length || plaintext.length % 8 !== 0)
            throw new Error('invalid plaintext length');
        if (plaintext.length === 8)
            throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead');
        const out = concatBytes$1(AESKW_IV, plaintext);
        AESW.encrypt(kek, out);
        return out;
    },
    decrypt(ciphertext) {
        // ciphertext must be at least 24 bytes and a multiple of 8 bytes
        // 24 because should have at least two block (1 iv + 2).
        // Replace with 16 to enable '8-byte keys'
        if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)
            throw new Error('invalid ciphertext length');
        const out = copyBytes$1(ciphertext);
        AESW.decrypt(kek, out);
        if (!equalBytes(out.subarray(0, 8), AESKW_IV))
            throw new Error('integrity check failed');
        out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway
        return out.subarray(8);
    },
}));
/** Unsafe low-level internal methods. May change at any time. */
const unsafe = {
    expandKeyLE,
    expandKeyDecLE,
    encrypt: encrypt$4,
    decrypt: decrypt$4,
    encryptBlock,
    decryptBlock,
    ctrCounter,
    ctr32,
};

/**
 * @module crypto/cipher
 * @access private
 */
async function getLegacyCipher(algo) {
    switch (algo) {
        case enums.symmetric.aes128:
        case enums.symmetric.aes192:
        case enums.symmetric.aes256:
            throw new Error('Not a legacy cipher');
        case enums.symmetric.cast5:
        case enums.symmetric.blowfish:
        case enums.symmetric.twofish:
        case enums.symmetric.tripledes: {
            const { legacyCiphers } = await Promise.resolve().then(function () { return legacy_ciphers; });
            const algoName = enums.read(enums.symmetric, algo);
            const cipher = legacyCiphers.get(algoName);
            if (!cipher) {
                throw new Error('Unsupported cipher algorithm');
            }
            return cipher;
        }
        default:
            throw new Error('Unsupported cipher algorithm');
    }
}
/**
 * Get block size for given cipher algo
 * @param {module:enums.symmetric} algo - alrogithm identifier
 */
function getCipherBlockSize(algo) {
    switch (algo) {
        case enums.symmetric.aes128:
        case enums.symmetric.aes192:
        case enums.symmetric.aes256:
        case enums.symmetric.twofish:
            return 16;
        case enums.symmetric.blowfish:
        case enums.symmetric.cast5:
        case enums.symmetric.tripledes:
            return 8;
        default:
            throw new Error('Unsupported cipher');
    }
}
/**
 * Get key size for given cipher algo
 * @param {module:enums.symmetric} algo - alrogithm identifier
 */
function getCipherKeySize(algo) {
    switch (algo) {
        case enums.symmetric.aes128:
        case enums.symmetric.blowfish:
        case enums.symmetric.cast5:
            return 16;
        case enums.symmetric.aes192:
        case enums.symmetric.tripledes:
            return 24;
        case enums.symmetric.aes256:
        case enums.symmetric.twofish:
            return 32;
        default:
            throw new Error('Unsupported cipher');
    }
}
/**
 * Get block and key size for given cipher algo
 * @param {module:enums.symmetric} algo - alrogithm identifier
 */
function getCipherParams(algo) {
    return { keySize: getCipherKeySize(algo), blockSize: getCipherBlockSize(algo) };
}

// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2015-2016 Decentral
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions
 * @see module:crypto/public_key/elliptic/ecdh
 * @module crypto/aes_kw
 * @access private
 */
const webCrypto$6 = util.getWebCrypto();
/**
 * AES key wrap
 * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo
 * @param {Uint8Array} key - wrapping key
 * @param {Uint8Array} dataToWrap
 * @returns {Promise<Uint8Array>} wrapped key
 */
async function wrap(algo, key, dataToWrap) {
    const { keySize } = getCipherParams(algo);
    // sanity checks, since WebCrypto does not use the `algo` input
    if (!util.isAES(algo) || key.length !== keySize) {
        throw new Error('Unexpected algorithm or key size');
    }
    try {
        const wrappingKey = await webCrypto$6.importKey('raw', key, { name: 'AES-KW' }, false, ['wrapKey']);
        // Import data as HMAC key, as it has no key length requirements
        const keyToWrap = await webCrypto$6.importKey('raw', dataToWrap, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);
        const wrapped = await webCrypto$6.wrapKey('raw', keyToWrap, wrappingKey, { name: 'AES-KW' });
        return new Uint8Array(wrapped);
    }
    catch (err) {
        // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
        if (err.name !== 'NotSupportedError' &&
            !(key.length === 24 && err.name === 'OperationError')) {
            throw err;
        }
        util.printDebugError('Browser did not support operation: ' + err.message);
    }
    return aeskw(key).encrypt(dataToWrap);
}
/**
 * AES key unwrap
 * @param {enums.symmetric.aes128|enums.symmetric.aes256|enums.symmetric.aes192} algo - AES algo
 * @param {Uint8Array} key - wrapping key
 * @param {Uint8Array} wrappedData
 * @returns {Promise<Uint8Array>} unwrapped data
 */
async function unwrap(algo, key, wrappedData) {
    const { keySize } = getCipherParams(algo);
    // sanity checks, since WebCrypto does not use the `algo` input
    if (!util.isAES(algo) || key.length !== keySize) {
        throw new Error('Unexpected algorithm or key size');
    }
    let wrappingKey;
    try {
        wrappingKey = await webCrypto$6.importKey('raw', key, { name: 'AES-KW' }, false, ['unwrapKey']);
    }
    catch (err) {
        // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
        if (err.name !== 'NotSupportedError' &&
            !(key.length === 24 && err.name === 'OperationError')) {
            throw err;
        }
        util.printDebugError('Browser did not support operation: ' + err.message);
        return aeskw(key).decrypt(wrappedData);
    }
    try {
        const unwrapped = await webCrypto$6.unwrapKey('raw', wrappedData, wrappingKey, { name: 'AES-KW' }, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']);
        return new Uint8Array(await webCrypto$6.exportKey('raw', unwrapped));
    }
    catch (err) {
        if (err.name === 'OperationError') {
            throw new Error('Key Data Integrity failed');
        }
        throw err;
    }
}

/**
 * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API.
 * @module crypto/hkdf
 * @access private
 */
async function computeHKDF(hashAlgo, inputKey, salt, info, outLen) {
    const webCrypto = util.getWebCrypto();
    const hash = enums.read(enums.webHash, hashAlgo);
    if (!hash)
        throw new Error('Hash algo not supported with HKDF');
    const importedKey = await webCrypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']);
    const bits = await webCrypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8);
    return new Uint8Array(bits);
}

/**
 * @fileoverview Key encryption and decryption for RFC 6637 ECDH
 * @module crypto/public_key/elliptic/ecdh
 * @access private
 */
const HKDF_INFO = {
    x25519: util.encodeUTF8('OpenPGP X25519'),
    x448: util.encodeUTF8('OpenPGP X448')
};
/**
 * Generate ECDH key for Montgomery curves
 * @param {module:enums.publicKey} algo - Algorithm identifier
 * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>}
 */
async function generate$2(algo) {
    switch (algo) {
        case enums.publicKey.x25519:
            try {
                const webCrypto = util.getWebCrypto();
                const webCryptoKey = await webCrypto.generateKey('X25519', true, ['deriveKey', 'deriveBits'])
                    .catch(err => {
                    if (err.name === 'OperationError') { // Temporary (hopefully) fix for WebKit on Linux
                        const newErr = new Error('Unexpected key generation issue');
                        newErr.name = 'NotSupportedError';
                        throw newErr;
                    }
                    throw err;
                });
                const privateKey = await webCrypto.exportKey('jwk', webCryptoKey.privateKey);
                const publicKey = await webCrypto.exportKey('jwk', webCryptoKey.publicKey);
                if (privateKey.x !== publicKey.x) { // Weird issue with Webkit on Linux: https://bugs.webkit.org/show_bug.cgi?id=289693
                    const err = new Error('Unexpected mismatching public point');
                    err.name = 'NotSupportedError';
                    throw err;
                }
                return {
                    A: new Uint8Array(b64ToUint8Array(publicKey.x)),
                    k: b64ToUint8Array(privateKey.d)
                };
            }
            catch (err) {
                if (err.name !== 'NotSupportedError') {
                    throw err;
                }
                const { default: x25519 } = await Promise.resolve().then(function () { return naclFast; });
                // k stays in little-endian, unlike legacy ECDH over curve25519
                const { secretKey: k, publicKey: A } = x25519.box.keyPair();
                return { A, k };
            }
        case enums.publicKey.x448: {
            const x448 = await util.getNobleCurve(enums.publicKey.x448);
            const { secretKey: k, publicKey: A } = x448.keygen();
            return { A, k };
        }
        default:
            throw new Error('Unsupported ECDH algorithm');
    }
}
/**
* Validate ECDH parameters
* @param {module:enums.publicKey} algo - Algorithm identifier
* @param {Uint8Array} A - ECDH public point
* @param {Uint8Array} k - ECDH secret scalar
* @returns {Promise<Boolean>} Whether params are valid.
* @async
*/
async function validateParams$6(algo, A, k) {
    switch (algo) {
        case enums.publicKey.x25519:
            // Validation is typically not run for ECDH, since encryption subkeys are only validated
            // for gnu-dummy keys.
            // So, for simplicity, we do an encrypt-decrypt round even if WebCrypto support is not available
            try {
                const { ephemeralPublicKey, sharedSecret } = await generateEphemeralEncryptionMaterial(algo, A);
                const recomputedSharedSecret = await recomputeSharedSecret(algo, ephemeralPublicKey, A, k);
                return util.equalsUint8Array(sharedSecret, recomputedSharedSecret);
            }
            catch {
                return false;
            }
        case enums.publicKey.x448: {
            const x448 = await util.getNobleCurve(enums.publicKey.x448);
            /**
             * Derive public point A' from private key
             * and expect A == A'
             */
            const publicKey = x448.getPublicKey(k);
            return util.equalsUint8Array(A, publicKey);
        }
        default:
            return false;
    }
}
/**
 * Wrap and encrypt a session key
 *
 * @param {module:enums.publicKey} algo - Algorithm identifier
 * @param {Uint8Array} data - session key data to be encrypted
 * @param {Uint8Array} recipientA - Recipient public key (K_B)
 * @returns {Promise<{
 *  ephemeralPublicKey: Uint8Array,
 * wrappedKey: Uint8Array
 * }>} ephemeral public key (K_A) and encrypted key
 * @async
 */
async function encrypt$3(algo, data, recipientA) {
    const { ephemeralPublicKey, sharedSecret } = await generateEphemeralEncryptionMaterial(algo, recipientA);
    const hkdfInput = util.concatUint8Array([
        ephemeralPublicKey,
        recipientA,
        sharedSecret
    ]);
    switch (algo) {
        case enums.publicKey.x25519: {
            const cipherAlgo = enums.symmetric.aes128;
            const { keySize } = getCipherParams(cipherAlgo);
            const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);
            const wrappedKey = await wrap(cipherAlgo, encryptionKey, data);
            return { ephemeralPublicKey, wrappedKey };
        }
        case enums.publicKey.x448: {
            const cipherAlgo = enums.symmetric.aes256;
            const { keySize } = getCipherParams(enums.symmetric.aes256);
            const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize);
            const wrappedKey = await wrap(cipherAlgo, encryptionKey, data);
            return { ephemeralPublicKey, wrappedKey };
        }
        default:
            throw new Error('Unsupported ECDH algorithm');
    }
}
/**
 * Decrypt and unwrap the session key
 *
 * @param {module:enums.publicKey} algo - Algorithm identifier
 * @param {Uint8Array} ephemeralPublicKey - (K_A)
 * @param {Uint8Array} wrappedKey,
 * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF
 * @param {Uint8Array} k - Recipient secret key (b)
 * @returns {Promise<Uint8Array>} decrypted session key data
 * @async
 */
async function decrypt$3(algo, ephemeralPublicKey, wrappedKey, A, k) {
    const sharedSecret = await recomputeSharedSecret(algo, ephemeralPublicKey, A, k);
    const hkdfInput = util.concatUint8Array([
        ephemeralPublicKey,
        A,
        sharedSecret
    ]);
    switch (algo) {
        case enums.publicKey.x25519: {
            const cipherAlgo = enums.symmetric.aes128;
            const { keySize } = getCipherParams(cipherAlgo);
            const encryptionKey = await computeHKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);
            return unwrap(cipherAlgo, encryptionKey, wrappedKey);
        }
        case enums.publicKey.x448: {
            const cipherAlgo = enums.symmetric.aes256;
            const { keySize } = getCipherParams(enums.symmetric.aes256);
            const encryptionKey = await computeHKDF(enums.hash.sha512, hkdfInput, new Uint8Array(), HKDF_INFO.x448, keySize);
            return unwrap(cipherAlgo, encryptionKey, wrappedKey);
        }
        default:
            throw new Error('Unsupported ECDH algorithm');
    }
}
function getPayloadSize(algo) {
    switch (algo) {
        case enums.publicKey.x25519:
            return 32;
        case enums.publicKey.x448:
            return 56;
        default:
            throw new Error('Unsupported ECDH algorithm');
    }
}
/**
 * Generate shared secret and ephemeral public key for encryption
 * @returns {Promise<{ ephemeralPublicKey: Uint8Array, sharedSecret: Uint8Array }>} ephemeral public key (K_A) and shared secret
 * @async
 */
async function generateEphemeralEncryptionMaterial(algo, recipientA) {
    switch (algo) {
        case enums.publicKey.x25519:
            try {
                const webCrypto = util.getWebCrypto();
                const ephemeralKeyPair = await webCrypto.generateKey('X25519', true, ['deriveKey', 'deriveBits'])
                    .catch(err => {
                    if (err.name === 'OperationError') { // Temporary (hopefully) fix for WebKit on Linux
                        const newErr = new Error('Unexpected key generation issue');
                        newErr.name = 'NotSupportedError';
                        throw newErr;
                    }
                    throw err;
                });
                const ephemeralPublicKeyJwt = await webCrypto.exportKey('jwk', ephemeralKeyPair.publicKey);
                const ephemeralPrivateKeyJwt = await webCrypto.exportKey('jwk', ephemeralKeyPair.privateKey);
                if (ephemeralPrivateKeyJwt.x !== ephemeralPublicKeyJwt.x) { // Weird issue with Webkit on Linux: https://bugs.webkit.org/show_bug.cgi?id=289693
                    const err = new Error('Unexpected mismatching public point');
                    err.name = 'NotSupportedError';
                    throw err;
                }
                const jwk = publicKeyToJWK(algo, recipientA);
                const recipientPublicKey = await webCrypto.importKey('jwk', jwk, 'X25519', false, []);
                const sharedSecretBuffer = await webCrypto.deriveBits({ name: 'X25519', public: recipientPublicKey }, ephemeralKeyPair.privateKey, getPayloadSize(algo) * 8 // in bits
                );
                return {
                    sharedSecret: new Uint8Array(sharedSecretBuffer),
                    ephemeralPublicKey: new Uint8Array(b64ToUint8Array(ephemeralPublicKeyJwt.x))
                };
            }
            catch (err) {
                if (err.name !== 'NotSupportedError') {
                    throw err;
                }
                const { default: x25519 } = await Promise.resolve().then(function () { return naclFast; });
                const { secretKey: ephemeralSecretKey, publicKey: ephemeralPublicKey } = x25519.box.keyPair();
                const sharedSecret = x25519.scalarMult(ephemeralSecretKey, recipientA);
                assertNonZeroArray(sharedSecret);
                return { ephemeralPublicKey, sharedSecret };
            }
        case enums.publicKey.x448: {
            const x448 = await util.getNobleCurve(enums.publicKey.x448);
            const { secretKey: ephemeralSecretKey, publicKey: ephemeralPublicKey } = x448.keygen();
            const sharedSecret = x448.getSharedSecret(ephemeralSecretKey, recipientA);
            assertNonZeroArray(sharedSecret);
            return { ephemeralPublicKey, sharedSecret };
        }
        default:
            throw new Error('Unsupported ECDH algorithm');
    }
}
async function recomputeSharedSecret(algo, ephemeralPublicKey, A, k) {
    switch (algo) {
        case enums.publicKey.x25519:
            try {
                const webCrypto = util.getWebCrypto();
                const privateKeyJWK = privateKeyToJWK(algo, A, k);
                const ephemeralPublicKeyJWK = publicKeyToJWK(algo, ephemeralPublicKey);
                const privateKey = await webCrypto.importKey('jwk', privateKeyJWK, 'X25519', false, ['deriveKey', 'deriveBits']);
                const ephemeralPublicKeyReference = await webCrypto.importKey('jwk', ephemeralPublicKeyJWK, 'X25519', false, []);
                const sharedSecretBuffer = await webCrypto.deriveBits({ name: 'X25519', public: ephemeralPublicKeyReference }, privateKey, getPayloadSize(algo) * 8 // in bits
                );
                return new Uint8Array(sharedSecretBuffer);
            }
            catch (err) {
                if (err.name !== 'NotSupportedError') {
                    throw err;
                }
                const { default: x25519 } = await Promise.resolve().then(function () { return naclFast; });
                const sharedSecret = x25519.scalarMult(k, ephemeralPublicKey);
                assertNonZeroArray(sharedSecret);
                return sharedSecret;
            }
        case enums.publicKey.x448: {
            const x448 = await util.getNobleCurve(enums.publicKey.x448);
            const sharedSecret = x448.getSharedSecret(k, ephemeralPublicKey);
            assertNonZeroArray(sharedSecret);
            return sharedSecret;
        }
        default:
            throw new Error('Unsupported ECDH algorithm');
    }
}
/**
 * x25519 and x448 produce an all-zero value when given as input a point with small order.
 * This does not lead to a security issue in the context of ECDH, but it is still unexpected,
 * hence we throw.
 * @param {Uint8Array} sharedSecret
 */
function assertNonZeroArray(sharedSecret) {
    let acc = 0;
    for (let i = 0; i < sharedSecret.length; i++) {
        acc |= sharedSecret[i];
    }
    if (acc === 0) {
        throw new Error('Unexpected low order point');
    }
}
function publicKeyToJWK(algo, publicKey) {
    switch (algo) {
        case enums.publicKey.x25519: {
            const jwk = {
                kty: 'OKP',
                crv: 'X25519',
                x: uint8ArrayToB64(publicKey),
                ext: true
            };
            return jwk;
        }
        default:
            throw new Error('Unsupported ECDH algorithm');
    }
}
function privateKeyToJWK(algo, publicKey, privateKey) {
    switch (algo) {
        case enums.publicKey.x25519: {
            const jwk = publicKeyToJWK(algo, publicKey);
            jwk.d = uint8ArrayToB64(privateKey);
            return jwk;
        }
        default:
            throw new Error('Unsupported ECDH algorithm');
    }
}

var ecdh_x = /*#__PURE__*/Object.freeze({
  __proto__: null,
  decrypt: decrypt$3,
  encrypt: encrypt$3,
  generate: generate$2,
  generateEphemeralEncryptionMaterial: generateEphemeralEncryptionMaterial,
  getPayloadSize: getPayloadSize,
  recomputeSharedSecret: recomputeSharedSecret,
  validateParams: validateParams$6
});

// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2015-2016 Decentral
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview Wrapper of an instance of an Elliptic Curve
 * @module crypto/public_key/elliptic/curve
 * @access private
 */
const webCrypto$5 = util.getWebCrypto();
const nodeCrypto$5 = util.getNodeCrypto();
const webCurves = {
    [enums.curve.nistP256]: 'P-256',
    [enums.curve.nistP384]: 'P-384',
    [enums.curve.nistP521]: 'P-521'
};
const knownCurves = nodeCrypto$5 ? nodeCrypto$5.getCurves() : [];
const nodeCurves = nodeCrypto$5 ? {
    [enums.curve.secp256k1]: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,
    [enums.curve.nistP256]: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,
    [enums.curve.nistP384]: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,
    [enums.curve.nistP521]: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,
    [enums.curve.ed25519Legacy]: knownCurves.includes('ED25519') ? 'ED25519' : undefined,
    [enums.curve.curve25519Legacy]: knownCurves.includes('X25519') ? 'X25519' : undefined,
    [enums.curve.brainpoolP256r1]: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,
    [enums.curve.brainpoolP384r1]: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,
    [enums.curve.brainpoolP512r1]: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined
} : {};
const curves = {
    [enums.curve.nistP256]: {
        oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],
        keyType: enums.publicKey.ecdsa,
        hash: enums.hash.sha256,
        cipher: enums.symmetric.aes128,
        node: nodeCurves[enums.curve.nistP256],
        web: webCurves[enums.curve.nistP256],
        payloadSize: 32,
        sharedSize: 256,
        wireFormatLeadingByte: 0x04
    },
    [enums.curve.nistP384]: {
        oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],
        keyType: enums.publicKey.ecdsa,
        hash: enums.hash.sha384,
        cipher: enums.symmetric.aes192,
        node: nodeCurves[enums.curve.nistP384],
        web: webCurves[enums.curve.nistP384],
        payloadSize: 48,
        sharedSize: 384,
        wireFormatLeadingByte: 0x04
    },
    [enums.curve.nistP521]: {
        oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],
        keyType: enums.publicKey.ecdsa,
        hash: enums.hash.sha512,
        cipher: enums.symmetric.aes256,
        node: nodeCurves[enums.curve.nistP521],
        web: webCurves[enums.curve.nistP521],
        payloadSize: 66,
        sharedSize: 528,
        wireFormatLeadingByte: 0x04
    },
    [enums.curve.secp256k1]: {
        oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],
        keyType: enums.publicKey.ecdsa,
        hash: enums.hash.sha256,
        cipher: enums.symmetric.aes128,
        node: nodeCurves[enums.curve.secp256k1],
        payloadSize: 32,
        wireFormatLeadingByte: 0x04
    },
    [enums.curve.ed25519Legacy]: {
        oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],
        keyType: enums.publicKey.eddsaLegacy,
        hash: enums.hash.sha512,
        node: false, // nodeCurves.ed25519 TODO
        payloadSize: 32,
        wireFormatLeadingByte: 0x40
    },
    [enums.curve.curve25519Legacy]: {
        oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],
        keyType: enums.publicKey.ecdh,
        hash: enums.hash.sha256,
        cipher: enums.symmetric.aes128,
        node: false, // nodeCurves.curve25519 TODO
        payloadSize: 32,
        wireFormatLeadingByte: 0x40
    },
    [enums.curve.brainpoolP256r1]: {
        oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],
        keyType: enums.publicKey.ecdsa,
        hash: enums.hash.sha256,
        cipher: enums.symmetric.aes128,
        node: nodeCurves[enums.curve.brainpoolP256r1],
        payloadSize: 32,
        wireFormatLeadingByte: 0x04
    },
    [enums.curve.brainpoolP384r1]: {
        oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],
        keyType: enums.publicKey.ecdsa,
        hash: enums.hash.sha384,
        cipher: enums.symmetric.aes192,
        node: nodeCurves[enums.curve.brainpoolP384r1],
        payloadSize: 48,
        wireFormatLeadingByte: 0x04
    },
    [enums.curve.brainpoolP512r1]: {
        oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],
        keyType: enums.publicKey.ecdsa,
        hash: enums.hash.sha512,
        cipher: enums.symmetric.aes256,
        node: nodeCurves[enums.curve.brainpoolP512r1],
        payloadSize: 64,
        wireFormatLeadingByte: 0x04
    }
};
class CurveWithOID {
    constructor(oidOrName) {
        try {
            this.name = oidOrName instanceof OID ?
                oidOrName.getName() :
                enums.write(enums.curve, oidOrName);
        }
        catch {
            throw new UnsupportedError('Unknown curve');
        }
        const params = curves[this.name];
        this.keyType = params.keyType;
        this.oid = params.oid;
        this.hash = params.hash;
        this.cipher = params.cipher;
        this.node = params.node;
        this.web = params.web;
        this.payloadSize = params.payloadSize;
        this.sharedSize = params.sharedSize;
        this.wireFormatLeadingByte = params.wireFormatLeadingByte;
        if (this.web && util.getWebCrypto()) {
            this.type = 'web';
        }
        else if (this.node && util.getNodeCrypto()) {
            this.type = 'node';
        }
        else if (this.name === enums.curve.curve25519Legacy) {
            this.type = 'curve25519Legacy';
        }
        else if (this.name === enums.curve.ed25519Legacy) {
            this.type = 'ed25519Legacy';
        }
    }
    async genKeyPair() {
        switch (this.type) {
            case 'web':
                try {
                    return await webGenKeyPair(this.name, this.wireFormatLeadingByte);
                }
                catch (err) {
                    util.printDebugError('Browser did not support generating ec key ' + err.message);
                    return jsGenKeyPair(this.name);
                }
            case 'node':
                return nodeGenKeyPair(this.name);
            case 'curve25519Legacy': {
                // the private key must be stored in big endian and already clamped: https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#section-5.5.5.6.1.1-3
                const { k, A } = await generate$2(enums.publicKey.x25519);
                const privateKey = k.slice().reverse();
                privateKey[0] = (privateKey[0] & 127) | 64;
                privateKey[31] &= 248;
                const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]);
                return { publicKey, privateKey };
            }
            case 'ed25519Legacy': {
                const { seed: privateKey, A } = await generate$3(enums.publicKey.ed25519);
                const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]);
                return { publicKey, privateKey };
            }
            default:
                return jsGenKeyPair(this.name);
        }
    }
}
async function generate$1(curveName) {
    const curve = new CurveWithOID(curveName);
    const { oid, hash, cipher } = curve;
    const keyPair = await curve.genKeyPair();
    return {
        oid,
        Q: keyPair.publicKey,
        secret: util.leftPad(keyPair.privateKey, curve.payloadSize),
        hash,
        cipher
    };
}
/**
 * Get preferred hash algo to use with the given curve
 * @param {module:type/oid} oid - curve oid
 * @returns {enums.hash} hash algorithm
 */
function getPreferredHashAlgo$1(oid) {
    return curves[oid.getName()].hash;
}
/**
 * Validate ECDH and ECDSA parameters
 * Not suitable for EdDSA (different secret key format)
 * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves
 * @param {module:type/oid} oid - EC object identifier
 * @param {Uint8Array} Q - EC public point
 * @param {Uint8Array} d - EC secret scalar
 * @returns {Promise<Boolean>} Whether params are valid.
 * @async
 */
async function validateStandardParams(algo, oid, Q, d) {
    const supportedCurves = {
        [enums.curve.nistP256]: true,
        [enums.curve.nistP384]: true,
        [enums.curve.nistP521]: true,
        [enums.curve.secp256k1]: true,
        [enums.curve.curve25519Legacy]: algo === enums.publicKey.ecdh,
        [enums.curve.brainpoolP256r1]: true,
        [enums.curve.brainpoolP384r1]: true,
        [enums.curve.brainpoolP512r1]: true
    };
    // Check whether the given curve is supported
    const curveName = oid.getName();
    if (!supportedCurves[curveName]) {
        return false;
    }
    if (curveName === enums.curve.curve25519Legacy) {
        const dLittleEndian = d.slice().reverse();
        // First byte is relevant for encoding purposes only
        if (Q.length < 1 || Q[0] !== 0x40) {
            return false;
        }
        return validateParams$6(enums.publicKey.x25519, Q.subarray(1), dLittleEndian);
    }
    const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curveName); // excluding curve25519Legacy, ecdh and ecdsa use the same curves
    /*
     * Re-derive public point Q' = dG from private key
     * Expect Q == Q'
     */
    const dG = nobleCurve.getPublicKey(d, false);
    if (!util.equalsUint8Array(dG, Q)) {
        return false;
    }
    return true;
}
/**
 * Check whether the public point has a valid encoding.
 * NB: this function does not check e.g. whether the point belongs to the curve.
 */
function checkPublicPointEnconding(curve, V) {
    const { payloadSize, wireFormatLeadingByte, name: curveName } = curve;
    const pointSize = (curveName === enums.curve.curve25519Legacy || curveName === enums.curve.ed25519Legacy) ? payloadSize : payloadSize * 2;
    if (V[0] !== wireFormatLeadingByte || V.length !== pointSize + 1) {
        throw new Error('Invalid point encoding');
    }
}
//////////////////////////
//                      //
//   Helper functions   //
//                      //
//////////////////////////
async function jsGenKeyPair(name) {
    const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, name); // excluding curve25519Legacy, ecdh and ecdsa use the same curves
    const { secretKey: privateKey } = nobleCurve.keygen();
    const publicKey = nobleCurve.getPublicKey(privateKey, false);
    return { publicKey, privateKey };
}
async function webGenKeyPair(name, wireFormatLeadingByte) {
    // Note: keys generated with ECDSA and ECDH are structurally equivalent
    const webCryptoKey = await webCrypto$5.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);
    const privateKey = await webCrypto$5.exportKey('jwk', webCryptoKey.privateKey);
    const publicKey = await webCrypto$5.exportKey('jwk', webCryptoKey.publicKey);
    return {
        publicKey: jwkToRawPublic(publicKey, wireFormatLeadingByte),
        privateKey: b64ToUint8Array(privateKey.d)
    };
}
function nodeGenKeyPair(name) {
    // Note: ECDSA and ECDH key generation is structurally equivalent
    const ecdh = nodeCrypto$5.createECDH(nodeCurves[name]);
    ecdh.generateKeys();
    return {
        publicKey: new Uint8Array(ecdh.getPublicKey()),
        privateKey: new Uint8Array(ecdh.getPrivateKey())
    };
}
//////////////////////////
//                      //
//   Helper functions   //
//                      //
//////////////////////////
/**
 * @param {JsonWebKey} jwk - key for conversion
 *
 * @returns {Uint8Array} Raw public key.
 */
function jwkToRawPublic(jwk, wireFormatLeadingByte) {
    const bufX = b64ToUint8Array(jwk.x);
    const bufY = b64ToUint8Array(jwk.y);
    const publicKey = new Uint8Array(bufX.length + bufY.length + 1);
    publicKey[0] = wireFormatLeadingByte;
    publicKey.set(bufX, 1);
    publicKey.set(bufY, bufX.length + 1);
    return publicKey;
}
/**
 * @param {Integer} payloadSize - ec payload size
 * @param {String} name - curve name
 * @param {Uint8Array} publicKey - public key
 *
 * @returns {JsonWebKey} Public key in jwk format.
 */
function rawPublicToJWK(payloadSize, name, publicKey) {
    const len = payloadSize;
    const bufX = publicKey.slice(1, len + 1);
    const bufY = publicKey.slice(len + 1, len * 2 + 1);
    // https://www.rfc-editor.org/rfc/rfc7518.txt
    const jwk = {
        kty: 'EC',
        crv: name,
        x: uint8ArrayToB64(bufX),
        y: uint8ArrayToB64(bufY),
        ext: true
    };
    return jwk;
}
/**
 * @param {Integer} payloadSize - ec payload size
 * @param {String} name - curve name
 * @param {Uint8Array} publicKey - public key
 * @param {Uint8Array} privateKey - private key
 *
 * @returns {JsonWebKey} Private key in jwk format.
 */
function privateToJWK(payloadSize, name, publicKey, privateKey) {
    const jwk = rawPublicToJWK(payloadSize, name, publicKey);
    jwk.d = uint8ArrayToB64(privateKey);
    return jwk;
}

// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2015-2016 Decentral
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview Implementation of ECDSA following RFC6637 for Openpgpjs
 * @module crypto/public_key/elliptic/ecdsa
 * @access private
 */
const webCrypto$4 = util.getWebCrypto();
const nodeCrypto$4 = util.getNodeCrypto();
/**
 * Sign a message using the provided key
 * @param {module:type/oid} oid - Elliptic curve object identifier
 * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign
 * @param {Uint8Array} message - Message to sign
 * @param {Uint8Array} publicKey - Public key
 * @param {Uint8Array} privateKey - Private key used to sign the message
 * @param {Uint8Array} hashed - The hashed message
 * @returns {Promise<{
 *   r: Uint8Array,
 *   s: Uint8Array
 * }>} Signature of the message
 * @async
 */
async function sign$4(oid, hashAlgo, message, publicKey, privateKey, hashed) {
    const curve = new CurveWithOID(oid);
    checkPublicPointEnconding(curve, publicKey);
    if (message && !util.isStream(message)) {
        const keyPair = { publicKey, privateKey };
        switch (curve.type) {
            case 'web':
                // If browser doesn't support a curve, we'll catch it
                try {
                    // Need to await to make sure browser succeeds
                    return await webSign(curve, hashAlgo, message, keyPair);
                }
                catch (err) {
                    // We do not fallback if the error is related to key integrity
                    // Unfortunaley Safari does not support nistP521 and throws a DataError when using it
                    // So we need to always fallback for that curve
                    if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) {
                        throw err;
                    }
                    util.printDebugError('Browser did not support signing: ' + err.message);
                }
                break;
            case 'node':
                return nodeSign(curve, hashAlgo, message, privateKey);
        }
    }
    const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name);
    // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch
    const signature = nobleCurve.sign(hashed, privateKey, { lowS: false });
    return {
        r: bigIntToUint8Array(signature.r, 'be', curve.payloadSize),
        s: bigIntToUint8Array(signature.s, 'be', curve.payloadSize)
    };
}
/**
 * Verifies if a signature is valid for a message
 * @param {module:type/oid} oid - Elliptic curve object identifier
 * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature
 * @param  {{r: Uint8Array,
             s: Uint8Array}}   signature Signature to verify
 * @param {Uint8Array} message - Message to verify
 * @param {Uint8Array} publicKey - Public key used to verify the message
 * @param {Uint8Array} hashed - The hashed message
 * @returns {Promise<Boolean>}
 * @async
 */
async function verify$4(oid, hashAlgo, signature, message, publicKey, hashed) {
    const curve = new CurveWithOID(oid);
    checkPublicPointEnconding(curve, publicKey);
    // See https://github.com/openpgpjs/openpgpjs/pull/948.
    // NB: the impact was more likely limited to Brainpool curves, since thanks
    // to WebCrypto availability, NIST curve should not have been affected.
    // Similarly, secp256k1 should have been used rarely enough.
    // However, we implement the fix for all curves, since it's only needed in case of
    // verification failure, which is unexpected, hence a minor slowdown is acceptable.
    const tryFallbackVerificationForOldBug = async () => (hashed[0] === 0 ?
        jsVerify(curve, signature, hashed.subarray(1), publicKey) :
        false);
    if (message && !util.isStream(message)) {
        switch (curve.type) {
            case 'web':
                try {
                    // Need to await to make sure browser succeeds
                    const verified = await webVerify(curve, hashAlgo, signature, message, publicKey);
                    return verified || tryFallbackVerificationForOldBug();
                }
                catch (err) {
                    // We do not fallback if the error is related to key integrity
                    // Unfortunately Safari does not support nistP521 and throws a DataError when using it
                    // So we need to always fallback for that curve
                    if (curve.name !== 'nistP521' && (err.name === 'DataError' || err.name === 'OperationError')) {
                        throw err;
                    }
                    util.printDebugError('Browser did not support verifying: ' + err.message);
                }
                break;
            case 'node': {
                const verified = nodeVerify(curve, hashAlgo, signature, message, publicKey);
                return verified || tryFallbackVerificationForOldBug();
            }
        }
    }
    const verified = await jsVerify(curve, signature, hashed, publicKey);
    return verified || tryFallbackVerificationForOldBug();
}
/**
 * Validate ECDSA parameters
 * @param {module:type/oid} oid - Elliptic curve object identifier
 * @param {Uint8Array} Q - ECDSA public point
 * @param {Uint8Array} d - ECDSA secret scalar
 * @returns {Promise<Boolean>} Whether params are valid.
 * @async
 */
async function validateParams$5(oid, Q, d) {
    const curve = new CurveWithOID(oid);
    // Reject curves x25519 and ed25519
    if (curve.keyType !== enums.publicKey.ecdsa) {
        return false;
    }
    // To speed up the validation, we try to use node- or webcrypto when available
    // and sign + verify a random message
    switch (curve.type) {
        case 'web':
        case 'node': {
            const message = getRandomBytes(8);
            const hashAlgo = enums.hash.sha256;
            const hashed = await computeDigest(hashAlgo, message);
            try {
                const signature = await sign$4(oid, hashAlgo, message, Q, d, hashed);
                return await verify$4(oid, hashAlgo, signature, message, Q, hashed);
            }
            catch {
                return false;
            }
        }
        default:
            return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);
    }
}
//////////////////////////
//                      //
//   Helper functions   //
//                      //
//////////////////////////
/**
 * Fallback javascript implementation of ECDSA verification.
 * To be used if no native implementation is available for the given curve/operation.
 */
async function jsVerify(curve, signature, hashed, publicKey) {
    const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdsa, curve.name);
    // lowS: non-canonical sig: https://stackoverflow.com/questions/74338846/ecdsa-signature-verification-mismatch
    return nobleCurve.verify(util.concatUint8Array([signature.r, signature.s]), hashed, publicKey, { lowS: false });
}
async function webSign(curve, hashAlgo, message, keyPair) {
    const len = curve.payloadSize;
    const jwk = privateToJWK(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);
    const key = await webCrypto$4.importKey('jwk', jwk, {
        'name': 'ECDSA',
        'namedCurve': webCurves[curve.name],
        'hash': { name: enums.read(enums.webHash, curve.hash) }
    }, false, ['sign']);
    const signature = new Uint8Array(await webCrypto$4.sign({
        'name': 'ECDSA',
        'namedCurve': webCurves[curve.name],
        'hash': { name: enums.read(enums.webHash, hashAlgo) }
    }, key, message));
    return {
        r: signature.slice(0, len),
        s: signature.slice(len, len << 1)
    };
}
async function webVerify(curve, hashAlgo, { r, s }, message, publicKey) {
    const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);
    const key = await webCrypto$4.importKey('jwk', jwk, {
        'name': 'ECDSA',
        'namedCurve': webCurves[curve.name],
        'hash': { name: enums.read(enums.webHash, curve.hash) }
    }, false, ['verify']);
    const signature = util.concatUint8Array([r, s]).buffer;
    return webCrypto$4.verify({
        'name': 'ECDSA',
        'namedCurve': webCurves[curve.name],
        'hash': { name: enums.read(enums.webHash, hashAlgo) }
    }, key, signature, message);
}
function nodeSign(curve, hashAlgo, message, privateKey) {
    // JWT encoding cannot be used for now, as Brainpool curves are not supported
    const ecKeyUtils = util.nodeRequire('eckey-utils');
    const nodeBuffer = util.getNodeBuffer();
    const { privateKey: derPrivateKey } = ecKeyUtils.generateDer({
        curveName: nodeCurves[curve.name],
        privateKey: nodeBuffer.from(privateKey)
    });
    const sign = nodeCrypto$4.createSign(enums.read(enums.hash, hashAlgo));
    sign.write(message);
    sign.end();
    const signature = new Uint8Array(sign.sign({ key: derPrivateKey, format: 'der', type: 'sec1', dsaEncoding: 'ieee-p1363' }));
    const len = curve.payloadSize;
    return {
        r: signature.subarray(0, len),
        s: signature.subarray(len, len << 1)
    };
}
function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) {
    const ecKeyUtils = util.nodeRequire('eckey-utils');
    const nodeBuffer = util.getNodeBuffer();
    const { publicKey: derPublicKey } = ecKeyUtils.generateDer({
        curveName: nodeCurves[curve.name],
        publicKey: nodeBuffer.from(publicKey)
    });
    const verify = nodeCrypto$4.createVerify(enums.read(enums.hash, hashAlgo));
    verify.write(message);
    verify.end();
    const signature = util.concatUint8Array([r, s]);
    try {
        return verify.verify({ key: derPublicKey, format: 'der', type: 'spki', dsaEncoding: 'ieee-p1363' }, signature);
    }
    catch {
        return false;
    }
}

var ecdsa$1 = /*#__PURE__*/Object.freeze({
  __proto__: null,
  sign: sign$4,
  validateParams: validateParams$5,
  verify: verify$4
});

// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2018 Proton Technologies AG
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview Implementation of legacy EdDSA following RFC4880bis-03 for OpenPGP.
 * This key type has been deprecated by the crypto-refresh RFC.
 * @module crypto/public_key/elliptic/eddsa_legacy
 * @access private
 */
/**
 * Sign a message using the provided legacy EdDSA key
 * @param {module:type/oid} oid - Elliptic curve object identifier
 * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)
 * @param {Uint8Array} message - Message to sign
 * @param {Uint8Array} publicKey - Public key
 * @param {Uint8Array} privateKey - Private key used to sign the message
 * @param {Uint8Array} hashed - The hashed message
 * @returns {Promise<{
 *   r: Uint8Array,
 *   s: Uint8Array
 * }>} Signature of the message
 * @async
 */
async function sign$3(oid, hashAlgo, message, publicKey, privateKey, hashed) {
    const curve = new CurveWithOID(oid);
    checkPublicPointEnconding(curve, publicKey);
    if (getHashByteLength(hashAlgo) < getHashByteLength(enums.hash.sha256)) {
        // Enforce digest sizes, since the constraint was already present in RFC4880bis:
        // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2
        // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3
        throw new Error('Hash algorithm too weak for EdDSA.');
    }
    const { RS: signature } = await sign$5(enums.publicKey.ed25519, hashAlgo, message, publicKey.subarray(1), privateKey, hashed);
    // EdDSA signature params are returned in little-endian format
    return {
        r: signature.subarray(0, 32),
        s: signature.subarray(32)
    };
}
/**
 * Verifies if a legacy EdDSA signature is valid for a message
 * @param {module:type/oid} oid - Elliptic curve object identifier
 * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature
 * @param  {{r: Uint8Array,
             s: Uint8Array}}   signature Signature to verify the message
 * @param {Uint8Array} m - Message to verify
 * @param {Uint8Array} publicKey - Public key used to verify the message
 * @param {Uint8Array} hashed - The hashed message
 * @returns {Boolean}
 * @async
 */
// eslint-disable-next-line @typescript-eslint/require-await
async function verify$3(oid, hashAlgo, { r, s }, m, publicKey, hashed) {
    const curve = new CurveWithOID(oid);
    checkPublicPointEnconding(curve, publicKey);
    if (getHashByteLength(hashAlgo) < getHashByteLength(enums.hash.sha256)) {
        // Enforce digest sizes, since the constraint was already present in RFC4880bis:
        // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2
        // and https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3
        throw new Error('Hash algorithm too weak for EdDSA.');
    }
    const RS = util.concatUint8Array([r, s]);
    return verify$5(enums.publicKey.ed25519, hashAlgo, { RS }, m, publicKey.subarray(1), hashed);
}
/**
 * Validate legacy EdDSA parameters
 * @param {module:type/oid} oid - Elliptic curve object identifier
 * @param {Uint8Array} Q - EdDSA public point
 * @param {Uint8Array} k - EdDSA secret seed
 * @returns {Promise<Boolean>} Whether params are valid.
 * @async
 */
async function validateParams$4(oid, Q, k) {
    // Check whether the given curve is supported
    if (oid.getName() !== enums.curve.ed25519Legacy) {
        return false;
    }
    // First byte is relevant for encoding purposes only
    if (Q.length < 1 || Q[0] !== 0x40) {
        return false;
    }
    return validateParams$7(enums.publicKey.ed25519, Q.subarray(1), k);
}

var eddsa_legacy = /*#__PURE__*/Object.freeze({
  __proto__: null,
  sign: sign$3,
  validateParams: validateParams$4,
  verify: verify$3
});

// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2015-2016 Decentral
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview Functions to add and remove PKCS5 padding
 * @see PublicKeyEncryptedSessionKeyPacket
 * @module crypto/pkcs5
 * @access private
 */
/**
 * Add pkcs5 padding to a message
 * @param {Uint8Array} message - message to pad
 * @returns {Uint8Array} Padded message.
 */
function encode(message) {
    const c = 8 - (message.length % 8);
    const padded = new Uint8Array(message.length + c).fill(c);
    padded.set(message);
    return padded;
}
/**
 * Remove pkcs5 padding from a message
 * @param {Uint8Array} message - message to remove padding from
 * @returns {Uint8Array} Message without padding.
 */
function decode(message) {
    const len = message.length;
    if (len > 0) {
        const c = message[len - 1];
        if (c >= 1) {
            const provided = message.subarray(len - c);
            const computed = new Uint8Array(c).fill(c);
            if (util.equalsUint8Array(provided, computed)) {
                return message.subarray(0, len - c);
            }
        }
    }
    throw new Error('Invalid padding');
}

// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2015-2016 Decentral
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview Key encryption and decryption for RFC 6637 ECDH
 * @module crypto/public_key/elliptic/ecdh
 * @access private
 */
/**
 * Validate ECDH parameters
 * @param {module:type/oid} oid - Elliptic curve object identifier
 * @param {Uint8Array} Q - ECDH public point
 * @param {Uint8Array} d - ECDH secret scalar
 * @returns {Promise<Boolean>} Whether params are valid.
 * @async
 */
async function validateParams$3(oid, Q, d) {
    return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);
}
// Build Param for ECDH algorithm (RFC 6637)
function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {
    return util.concatUint8Array([
        oid.write(),
        new Uint8Array([public_algo]),
        kdfParams.write(),
        util.stringToUint8Array('Anonymous Sender    '),
        fingerprint
    ]);
}
// Key Derivation Function (RFC 6637)
async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {
    // Note: X is little endian for Curve25519, big-endian for all others.
    // This is not ideal, but the RFC's are unclear
    // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
    let i;
    if (stripLeading) {
        // Work around old go crypto bug
        for (i = 0; i < X.length && X[i] === 0; i++)
            ;
        X = X.subarray(i);
    }
    if (stripTrailing) {
        // Work around old OpenPGP.js bug
        for (i = X.length - 1; i >= 0 && X[i] === 0; i--)
            ;
        X = X.subarray(0, i + 1);
    }
    const digest = await computeDigest(hashAlgo, util.concatUint8Array([
        new Uint8Array([0, 0, 0, 1]),
        X,
        param
    ]));
    return digest.subarray(0, length);
}
/**
 * Generate ECDHE ephemeral key and secret from public key
 *
 * @param {CurveWithOID} curve - Elliptic curve object
 * @param {Uint8Array} Q - Recipient public key
 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
 * @async
 */
async function genPublicEphemeralKey(curve, Q) {
    switch (curve.type) {
        case 'curve25519Legacy': {
            const { sharedSecret: sharedKey, ephemeralPublicKey } = await generateEphemeralEncryptionMaterial(enums.publicKey.x25519, Q.subarray(1));
            const publicKey = util.concatUint8Array([new Uint8Array([curve.wireFormatLeadingByte]), ephemeralPublicKey]);
            return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
        }
        case 'web':
            if (curve.web && util.getWebCrypto()) {
                try {
                    return await webPublicEphemeralKey(curve, Q);
                }
                catch (err) {
                    util.printDebugError(err);
                    return jsPublicEphemeralKey(curve, Q);
                }
            }
            break;
        case 'node':
            return nodePublicEphemeralKey(curve, Q);
        default:
            return jsPublicEphemeralKey(curve, Q);
    }
}
/**
 * Encrypt and wrap a session key
 *
 * @param {module:type/oid} oid - Elliptic curve object identifier
 * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use
 * @param {Uint8Array} data - Unpadded session key data
 * @param {Uint8Array} Q - Recipient public key
 * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version
 * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}
 * @async
 */
async function encrypt$2(oid, kdfParams, data, Q, fingerprint) {
    const m = encode(data);
    const curve = new CurveWithOID(oid);
    checkPublicPointEnconding(curve, Q);
    const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);
    const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);
    const { keySize } = getCipherParams(kdfParams.cipher);
    const Z = await kdf(kdfParams.hash, sharedKey, keySize, param);
    const wrappedKey = await wrap(kdfParams.cipher, Z, m);
    return { publicKey, wrappedKey };
}
/**
 * Generate ECDHE secret from private key and public part of ephemeral key
 *
 * @param {CurveWithOID} curve - Elliptic curve object
 * @param {Uint8Array} V - Public part of ephemeral key
 * @param {Uint8Array} Q - Recipient public key
 * @param {Uint8Array} d - Recipient private key
 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
 * @async
 */
async function genPrivateEphemeralKey(curve, V, Q, d) {
    if (d.length !== curve.payloadSize) {
        const privateKey = new Uint8Array(curve.payloadSize);
        privateKey.set(d, curve.payloadSize - d.length);
        d = privateKey;
    }
    switch (curve.type) {
        case 'curve25519Legacy': {
            const secretKey = d.slice().reverse();
            const sharedKey = await recomputeSharedSecret(enums.publicKey.x25519, V.subarray(1), Q.subarray(1), secretKey);
            return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
        }
        case 'web':
            if (curve.web && util.getWebCrypto()) {
                try {
                    return await webPrivateEphemeralKey(curve, V, Q, d);
                }
                catch (err) {
                    util.printDebugError(err);
                    return jsPrivateEphemeralKey(curve, V, d);
                }
            }
            break;
        case 'node':
            return nodePrivateEphemeralKey(curve, V, d);
        default:
            return jsPrivateEphemeralKey(curve, V, d);
    }
}
/**
 * Decrypt and unwrap the value derived from session key
 *
 * @param {module:type/oid} oid - Elliptic curve object identifier
 * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use
 * @param {Uint8Array} V - Public part of ephemeral key
 * @param {Uint8Array} C - Encrypted and wrapped value derived from session key
 * @param {Uint8Array} Q - Recipient public key
 * @param {Uint8Array} d - Recipient private key
 * @param {Uint8Array} fingerprint - Recipient fingerprint, already truncated depending on the key version
 * @returns {Promise<Uint8Array>} Value derived from session key.
 * @async
 */
async function decrypt$2(oid, kdfParams, V, C, Q, d, fingerprint) {
    const curve = new CurveWithOID(oid);
    checkPublicPointEnconding(curve, Q);
    checkPublicPointEnconding(curve, V);
    const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);
    const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);
    const { keySize } = getCipherParams(kdfParams.cipher);
    let err;
    for (let i = 0; i < 3; i++) {
        try {
            // Work around old go crypto bug and old OpenPGP.js bug, respectively.
            const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2);
            return decode(await unwrap(kdfParams.cipher, Z, C));
        }
        catch (e) {
            err = e;
        }
    }
    throw err;
}
async function jsPrivateEphemeralKey(curve, V, d) {
    const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name);
    // The output includes parity byte
    const sharedSecretWithParity = nobleCurve.getSharedSecret(d, V);
    const sharedKey = sharedSecretWithParity.subarray(1);
    return { secretKey: d, sharedKey };
}
async function jsPublicEphemeralKey(curve, Q) {
    const nobleCurve = await util.getNobleCurve(enums.publicKey.ecdh, curve.name);
    const { publicKey: V, privateKey: v } = await curve.genKeyPair();
    // The output includes parity byte
    const sharedSecretWithParity = nobleCurve.getSharedSecret(v, Q);
    const sharedKey = sharedSecretWithParity.subarray(1);
    return { publicKey: V, sharedKey };
}
/**
 * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto
 *
 * @param {CurveWithOID} curve - Elliptic curve object
 * @param {Uint8Array} V - Public part of ephemeral key
 * @param {Uint8Array} Q - Recipient public key
 * @param {Uint8Array} d - Recipient private key
 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
 * @async
 */
async function webPrivateEphemeralKey(curve, V, Q, d) {
    const webCrypto = util.getWebCrypto();
    const recipient = privateToJWK(curve.payloadSize, curve.web, Q, d);
    let privateKey = webCrypto.importKey('jwk', recipient, {
        name: 'ECDH',
        namedCurve: curve.web
    }, true, ['deriveKey', 'deriveBits']);
    const jwk = rawPublicToJWK(curve.payloadSize, curve.web, V);
    let sender = webCrypto.importKey('jwk', jwk, {
        name: 'ECDH',
        namedCurve: curve.web
    }, true, []);
    [privateKey, sender] = await Promise.all([privateKey, sender]);
    let S = webCrypto.deriveBits({
        name: 'ECDH',
        namedCurve: curve.web,
        public: sender
    }, privateKey, curve.sharedSize);
    let secret = webCrypto.exportKey('jwk', privateKey);
    [S, secret] = await Promise.all([S, secret]);
    const sharedKey = new Uint8Array(S);
    const secretKey = b64ToUint8Array(secret.d);
    return { secretKey, sharedKey };
}
/**
 * Generate ECDHE ephemeral key and secret from public key using webCrypto
 *
 * @param {CurveWithOID} curve - Elliptic curve object
 * @param {Uint8Array} Q - Recipient public key
 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
 * @async
 */
async function webPublicEphemeralKey(curve, Q) {
    const webCrypto = util.getWebCrypto();
    const jwk = rawPublicToJWK(curve.payloadSize, curve.web, Q);
    let keyPair = webCrypto.generateKey({
        name: 'ECDH',
        namedCurve: curve.web
    }, true, ['deriveKey', 'deriveBits']);
    let recipient = webCrypto.importKey('jwk', jwk, {
        name: 'ECDH',
        namedCurve: curve.web
    }, false, []);
    [keyPair, recipient] = await Promise.all([keyPair, recipient]);
    let s = webCrypto.deriveBits({
        name: 'ECDH',
        namedCurve: curve.web,
        public: recipient
    }, keyPair.privateKey, curve.sharedSize);
    let p = webCrypto.exportKey('jwk', keyPair.publicKey);
    [s, p] = await Promise.all([s, p]);
    const sharedKey = new Uint8Array(s);
    const publicKey = new Uint8Array(jwkToRawPublic(p, curve.wireFormatLeadingByte));
    return { publicKey, sharedKey };
}
/**
 * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto
 *
 * @param {CurveWithOID} curve - Elliptic curve object
 * @param {Uint8Array} V - Public part of ephemeral key
 * @param {Uint8Array} d - Recipient private key
 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
 * @async
 */
function nodePrivateEphemeralKey(curve, V, d) {
    const nodeCrypto = util.getNodeCrypto();
    const recipient = nodeCrypto.createECDH(curve.node);
    recipient.setPrivateKey(d);
    const sharedKey = new Uint8Array(recipient.computeSecret(V));
    const secretKey = new Uint8Array(recipient.getPrivateKey());
    return { secretKey, sharedKey };
}
/**
 * Generate ECDHE ephemeral key and secret from public key using nodeCrypto
 *
 * @param {CurveWithOID} curve - Elliptic curve object
 * @param {Uint8Array} Q - Recipient public key
 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
 * @async
 */
function nodePublicEphemeralKey(curve, Q) {
    const nodeCrypto = util.getNodeCrypto();
    const sender = nodeCrypto.createECDH(curve.node);
    sender.generateKeys();
    const sharedKey = new Uint8Array(sender.computeSecret(Q));
    const publicKey = new Uint8Array(sender.getPublicKey());
    return { publicKey, sharedKey };
}

var ecdh$1 = /*#__PURE__*/Object.freeze({
  __proto__: null,
  decrypt: decrypt$2,
  encrypt: encrypt$2,
  validateParams: validateParams$3
});

// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2015-2016 Decentral
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview Functions to access Elliptic Curve Cryptography
 * @see module:crypto/public_key/elliptic/curve
 * @see module:crypto/public_key/elliptic/ecdh
 * @see module:crypto/public_key/elliptic/ecdsa
 * @see module:crypto/public_key/elliptic/eddsa
 * @module crypto/public_key/elliptic
 * @access private
 */

var elliptic = /*#__PURE__*/Object.freeze({
  __proto__: null,
  CurveWithOID: CurveWithOID,
  ecdh: ecdh$1,
  ecdhX: ecdh_x,
  ecdsa: ecdsa$1,
  eddsa: eddsa$1,
  eddsaLegacy: eddsa_legacy,
  generate: generate$1,
  getPreferredHashAlgo: getPreferredHashAlgo$1
});

// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview A Digital signature algorithm implementation
 * @module crypto/public_key/dsa
 * @access private
 */
/*
  TODO regarding the hash function, read:
   https://tools.ietf.org/html/rfc4880#section-13.6
   https://tools.ietf.org/html/rfc4880#section-14
*/
const _0n$7 = BigInt(0);
const _1n$8 = BigInt(1);
/**
 * DSA Sign function
 * @param {Integer} hashAlgo
 * @param {Uint8Array} hashed
 * @param {Uint8Array} g
 * @param {Uint8Array} p
 * @param {Uint8Array} q
 * @param {Uint8Array} x
 * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}
 * @async
 */
// eslint-disable-next-line @typescript-eslint/require-await
async function sign$2(hashAlgo, hashed, g, p, q, x) {
    const _0n = BigInt(0);
    p = uint8ArrayToBigInt(p);
    q = uint8ArrayToBigInt(q);
    g = uint8ArrayToBigInt(g);
    x = uint8ArrayToBigInt(x);
    let k;
    let r;
    let s;
    let t;
    g = mod$1(g, p);
    x = mod$1(x, q);
    // If the output size of the chosen hash is larger than the number of
    // bits of q, the hash result is truncated to fit by taking the number
    // of leftmost bits equal to the number of bits of q.  This (possibly
    // truncated) hash function result is treated as a number and used
    // directly in the DSA signature algorithm.
    const h = mod$1(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q);
    // FIPS-186-4, section 4.6:
    // The values of r and s shall be checked to determine if r = 0 or s = 0.
    // If either r = 0 or s = 0, a new value of k shall be generated, and the
    // signature shall be recalculated. It is extremely unlikely that r = 0
    // or s = 0 if signatures are generated properly.
    while (true) {
        // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
        k = getRandomBigInteger(_1n$8, q); // returns in [1, q-1]
        r = mod$1(modExp(g, k, p), q); // (g**k mod p) mod q
        if (r === _0n) {
            continue;
        }
        const xr = mod$1(x * r, q);
        t = mod$1(h + xr, q); // H(m) + x*r mod q
        s = mod$1(modInv(k, q) * t, q); // k**-1 * (H(m) + x*r) mod q
        if (s === _0n) {
            continue;
        }
        break;
    }
    return {
        r: bigIntToUint8Array(r, 'be', byteLength(p)),
        s: bigIntToUint8Array(s, 'be', byteLength(p))
    };
}
/**
 * DSA Verify function
 * @param {Integer} hashAlgo
 * @param {Uint8Array} r
 * @param {Uint8Array} s
 * @param {Uint8Array} hashed
 * @param {Uint8Array} g
 * @param {Uint8Array} p
 * @param {Uint8Array} q
 * @param {Uint8Array} y
 * @returns {boolean}
 * @async
 */
// eslint-disable-next-line @typescript-eslint/require-await
async function verify$2(hashAlgo, r, s, hashed, g, p, q, y) {
    r = uint8ArrayToBigInt(r);
    s = uint8ArrayToBigInt(s);
    p = uint8ArrayToBigInt(p);
    q = uint8ArrayToBigInt(q);
    g = uint8ArrayToBigInt(g);
    y = uint8ArrayToBigInt(y);
    if (r <= _0n$7 || r >= q ||
        s <= _0n$7 || s >= q) {
        util.printDebug('invalid DSA Signature');
        return false;
    }
    const h = mod$1(uint8ArrayToBigInt(hashed.subarray(0, byteLength(q))), q);
    const w = modInv(s, q); // s**-1 mod q
    if (w === _0n$7) {
        util.printDebug('invalid DSA Signature');
        return false;
    }
    g = mod$1(g, p);
    y = mod$1(y, p);
    const u1 = mod$1(h * w, q); // H(m) * w mod q
    const u2 = mod$1(r * w, q); // r * w mod q
    const t1 = modExp(g, u1, p); // g**u1 mod p
    const t2 = modExp(y, u2, p); // y**u2 mod p
    const v = mod$1(mod$1(t1 * t2, p), q); // (g**u1 * y**u2 mod p) mod q
    return v === r;
}
/**
 * Validate DSA parameters
 * @param {Uint8Array} pBytes - DSA prime
 * @param {Uint8Array} qBytes - DSA group order
 * @param {Uint8Array} gBytes - DSA sub-group generator
 * @param {Uint8Array} yBytes - DSA public key
 * @param {Uint8Array} xBytes - DSA private key
 * @returns {Promise<Boolean>} Whether params are valid.
 * @async
 */
// eslint-disable-next-line @typescript-eslint/require-await
async function validateParams$2(pBytes, qBytes, gBytes, yBytes, xBytes) {
    const p = uint8ArrayToBigInt(pBytes);
    const q = uint8ArrayToBigInt(qBytes);
    const g = uint8ArrayToBigInt(gBytes);
    const y = uint8ArrayToBigInt(yBytes);
    // Check that 1 < g < p
    if (g <= _1n$8 || g >= p) {
        return false;
    }
    /**
     * Check that subgroup order q divides p-1
     */
    if (mod$1(p - _1n$8, q) !== _0n$7) {
        return false;
    }
    /**
     * g has order q
     * Check that g ** q = 1 mod p
     */
    if (modExp(g, q, p) !== _1n$8) {
        return false;
    }
    /**
     * Check q is large and probably prime (we mainly want to avoid small factors)
     */
    const qSize = BigInt(bitLength(q));
    const _150n = BigInt(150);
    if (qSize < _150n || !isProbablePrime(q, null, 32)) {
        return false;
    }
    /**
     * Re-derive public key y' = g ** x mod p
     * Expect y == y'
     *
     * Blinded exponentiation computes g**{rq + x} to compare to y
     */
    const x = uint8ArrayToBigInt(xBytes);
    const _2n = BigInt(2);
    const r = getRandomBigInteger(_2n << (qSize - _1n$8), _2n << qSize); // draw r of same size as q
    const rqx = q * r + x;
    if (y !== modExp(g, rqx, p)) {
        return false;
    }
    return true;
}

// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2015-2016 Decentral
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Encoded symmetric key for ECDH (incl. legacy x25519)
 *
 * @module type/ecdh_symkey
 * @access private
 */
class ECDHSymmetricKey {
    constructor(data) {
        if (data) {
            this.data = data;
        }
    }
    /**
     * Read an ECDHSymmetricKey from an Uint8Array:
     * - 1 octect for the length `l`
     * - `l` octects of encoded session key data
     * @param {Uint8Array} bytes
     * @returns {Number} Number of read bytes.
     */
    read(bytes) {
        if (bytes.length >= 1) {
            const length = bytes[0];
            if (bytes.length >= 1 + length) {
                this.data = bytes.subarray(1, 1 + length);
                return 1 + this.data.length;
            }
        }
        throw new Error('Invalid symmetric key');
    }
    /**
     * Write an ECDHSymmetricKey as an Uint8Array
     * @returns  {Uint8Array} Serialised data
     */
    write() {
        return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);
    }
}

/** @access private */
// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2015-2016 Decentral
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Implementation of type KDF parameters
 *
 * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:
 * A key derivation function (KDF) is necessary to implement the EC
 * encryption.  The Concatenation Key Derivation Function (Approved
 * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is
 * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.
 * @access private
 */
class KDFParams {
    /**
     * @param {enums.hash} hash - Hash algorithm
     * @param {enums.symmetric} cipher - Symmetric algorithm
     */
    constructor(data) {
        if (data) {
            const { hash, cipher } = data;
            this.hash = hash;
            this.cipher = cipher;
        }
        else {
            this.hash = null;
            this.cipher = null;
        }
    }
    /**
     * Read KDFParams from an Uint8Array
     * @param {Uint8Array} input - Where to read the KDFParams from
     * @returns {Number} Number of read bytes.
     */
    read(input) {
        if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {
            throw new UnsupportedError('Cannot read KDFParams');
        }
        this.hash = input[2];
        this.cipher = input[3];
        return 4;
    }
    /**
     * Write KDFParams to an Uint8Array
     * @returns  {Uint8Array}  Array with the KDFParams value
     */
    write() {
        return new Uint8Array([3, 1, this.hash, this.cipher]);
    }
}

/**
 * Encoded symmetric key for x25519 and x448
 * The payload format varies for v3 and v6 PKESK:
 * the former includes an algorithm byte preceeding the encrypted session key.
 *
 * @module type/x25519x448_symkey
 * @access private
 */
class ECDHXSymmetricKey {
    static fromObject({ wrappedKey, algorithm }) {
        const instance = new ECDHXSymmetricKey();
        instance.wrappedKey = wrappedKey;
        instance.algorithm = algorithm;
        return instance;
    }
    /**
     * - 1 octect for the length `l`
     * - `l` octects of encoded session key data (with optional leading algorithm byte)
     * @param {Uint8Array} bytes
     * @returns {Number} Number of read bytes.
     */
    read(bytes) {
        let read = 0;
        let followLength = bytes[read++];
        this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even
        followLength -= followLength % 2;
        this.wrappedKey = util.readExactSubarray(bytes, read, read + followLength);
        read += followLength;
    }
    /**
     * Write an MontgomerySymmetricKey as an Uint8Array
     * @returns  {Uint8Array} Serialised data
     */
    write() {
        return util.concatUint8Array([
            this.algorithm ?
                new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) :
                new Uint8Array([this.wrappedKey.length]),
            this.wrappedKey
        ]);
    }
}

// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// The GPG4Browsers crypto interface
/**
 * @fileoverview Provides functions for asymmetric encryption and decryption as
 * well as key generation and parameter handling for all public-key cryptosystems.
 * @module crypto/crypto
 * @access private
 */
/**
 * Encrypts data using specified algorithm and public key parameters.
 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.
 * @param {module:enums.publicKey} keyAlgo - Public key algorithm
 * @param {module:enums.symmetric|null} symmetricAlgo - Cipher algorithm (v3 only)
 * @param {Object} publicParams - Algorithm-specific public key parameters
 * @param {Uint8Array} data - Session key data to be encrypted
 * @param {Uint8Array} fingerprint - Recipient fingerprint
 * @returns {Promise<Object>} Encrypted session key parameters.
 * @async
 */
async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) {
    switch (keyAlgo) {
        case enums.publicKey.rsaEncrypt:
        case enums.publicKey.rsaEncryptSign: {
            const { n, e } = publicParams;
            const c = await encrypt$6(data, n, e);
            return { c };
        }
        case enums.publicKey.elgamal: {
            const { p, g, y } = publicParams;
            return encrypt$5(data, p, g, y);
        }
        case enums.publicKey.ecdh: {
            const { oid, Q, kdfParams } = publicParams;
            const { publicKey: V, wrappedKey: C } = await encrypt$2(oid, kdfParams, data, Q, fingerprint);
            return { V, C: new ECDHSymmetricKey(C) };
        }
        case enums.publicKey.x25519:
        case enums.publicKey.x448: {
            if (symmetricAlgo && !util.isAES(symmetricAlgo)) {
                // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276
                throw new Error('X25519 and X448 keys can only encrypt AES session keys');
            }
            const { A } = publicParams;
            const { ephemeralPublicKey, wrappedKey } = await encrypt$3(keyAlgo, data, A);
            const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey });
            return { ephemeralPublicKey, C };
        }
        default:
            return [];
    }
}
/**
 * Decrypts data using specified algorithm and private key parameters.
 * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}
 * @param {module:enums.publicKey} algo - Public key algorithm
 * @param {Object} publicKeyParams - Algorithm-specific public key parameters
 * @param {Object} privateKeyParams - Algorithm-specific private key parameters
 * @param {Object} sessionKeyParams - Encrypted session key parameters
 * @param {Uint8Array} fingerprint - Recipient fingerprint
 * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing
 *                                    (needed for constant-time processing in RSA and ElGamal)
 * @returns {Promise<Uint8Array>} Decrypted data.
 * @throws {Error} on sensitive decryption error, unless `randomPayload` is given
 * @async
 */
async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) {
    switch (algo) {
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.rsaEncrypt: {
            const { c } = sessionKeyParams;
            const { n, e } = publicKeyParams;
            const { d, p, q, u } = privateKeyParams;
            return decrypt$6(c, n, e, d, p, q, u, randomPayload);
        }
        case enums.publicKey.elgamal: {
            const { c1, c2 } = sessionKeyParams;
            const p = publicKeyParams.p;
            const x = privateKeyParams.x;
            return decrypt$5(c1, c2, p, x, randomPayload);
        }
        case enums.publicKey.ecdh: {
            const { oid, Q, kdfParams } = publicKeyParams;
            const { d } = privateKeyParams;
            const { V, C } = sessionKeyParams;
            return decrypt$2(oid, kdfParams, V, C.data, Q, d, fingerprint);
        }
        case enums.publicKey.x25519:
        case enums.publicKey.x448: {
            const { A } = publicKeyParams;
            const { k } = privateKeyParams;
            const { ephemeralPublicKey, C } = sessionKeyParams;
            if (C.algorithm !== null && !util.isAES(C.algorithm)) {
                throw new Error('AES session key expected');
            }
            return decrypt$3(algo, ephemeralPublicKey, C.wrappedKey, A, k);
        }
        default:
            throw new Error('Unknown public key encryption algorithm.');
    }
}
/**
 * Parse public key material in binary form to get the key parameters
 * @param {module:enums.publicKey} algo - The key algorithm
 * @param {Uint8Array} bytes - The key material to parse
 * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.
 */
function parsePublicKeyParams(algo, bytes) {
    let read = 0;
    switch (algo) {
        case enums.publicKey.rsaEncrypt:
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.rsaSign: {
            const n = util.readMPI(bytes.subarray(read));
            read += n.length + 2;
            const e = util.readMPI(bytes.subarray(read));
            read += e.length + 2;
            return { read, publicParams: { n, e } };
        }
        case enums.publicKey.dsa: {
            const p = util.readMPI(bytes.subarray(read));
            read += p.length + 2;
            const q = util.readMPI(bytes.subarray(read));
            read += q.length + 2;
            const g = util.readMPI(bytes.subarray(read));
            read += g.length + 2;
            const y = util.readMPI(bytes.subarray(read));
            read += y.length + 2;
            return { read, publicParams: { p, q, g, y } };
        }
        case enums.publicKey.elgamal: {
            const p = util.readMPI(bytes.subarray(read));
            read += p.length + 2;
            const g = util.readMPI(bytes.subarray(read));
            read += g.length + 2;
            const y = util.readMPI(bytes.subarray(read));
            read += y.length + 2;
            return { read, publicParams: { p, g, y } };
        }
        case enums.publicKey.ecdsa: {
            const oid = new OID();
            read += oid.read(bytes);
            checkSupportedCurve(oid);
            const Q = util.readMPI(bytes.subarray(read));
            read += Q.length + 2;
            return { read: read, publicParams: { oid, Q } };
        }
        case enums.publicKey.eddsaLegacy: {
            const oid = new OID();
            read += oid.read(bytes);
            checkSupportedCurve(oid);
            if (oid.getName() !== enums.curve.ed25519Legacy) {
                throw new Error('Unexpected OID for eddsaLegacy');
            }
            let Q = util.readMPI(bytes.subarray(read));
            read += Q.length + 2;
            Q = util.leftPad(Q, 33);
            return { read: read, publicParams: { oid, Q } };
        }
        case enums.publicKey.ecdh: {
            const oid = new OID();
            read += oid.read(bytes);
            checkSupportedCurve(oid);
            const Q = util.readMPI(bytes.subarray(read));
            read += Q.length + 2;
            const kdfParams = new KDFParams();
            read += kdfParams.read(bytes.subarray(read));
            return { read: read, publicParams: { oid, Q, kdfParams } };
        }
        case enums.publicKey.ed25519:
        case enums.publicKey.ed448:
        case enums.publicKey.x25519:
        case enums.publicKey.x448: {
            const A = util.readExactSubarray(bytes, read, read + getCurvePayloadSize(algo));
            read += A.length;
            return { read, publicParams: { A } };
        }
        default:
            throw new UnsupportedError('Unknown public key encryption algorithm.');
    }
}
/**
 * Parse private key material in binary form to get the key parameters
 * @param {module:enums.publicKey} algo - The key algorithm
 * @param {Uint8Array} bytes - The key material to parse
 * @param {Object} publicParams - (ECC only) public params, needed to format some private params
 * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.
 */
function parsePrivateKeyParams(algo, bytes, publicParams) {
    let read = 0;
    switch (algo) {
        case enums.publicKey.rsaEncrypt:
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.rsaSign: {
            const d = util.readMPI(bytes.subarray(read));
            read += d.length + 2;
            const p = util.readMPI(bytes.subarray(read));
            read += p.length + 2;
            const q = util.readMPI(bytes.subarray(read));
            read += q.length + 2;
            const u = util.readMPI(bytes.subarray(read));
            read += u.length + 2;
            return { read, privateParams: { d, p, q, u } };
        }
        case enums.publicKey.dsa:
        case enums.publicKey.elgamal: {
            const x = util.readMPI(bytes.subarray(read));
            read += x.length + 2;
            return { read, privateParams: { x } };
        }
        case enums.publicKey.ecdsa:
        case enums.publicKey.ecdh: {
            const payloadSize = getCurvePayloadSize(algo, publicParams.oid);
            let d = util.readMPI(bytes.subarray(read));
            read += d.length + 2;
            d = util.leftPad(d, payloadSize);
            return { read, privateParams: { d } };
        }
        case enums.publicKey.eddsaLegacy: {
            const payloadSize = getCurvePayloadSize(algo, publicParams.oid);
            if (publicParams.oid.getName() !== enums.curve.ed25519Legacy) {
                throw new Error('Unexpected OID for eddsaLegacy');
            }
            let seed = util.readMPI(bytes.subarray(read));
            read += seed.length + 2;
            seed = util.leftPad(seed, payloadSize);
            return { read, privateParams: { seed } };
        }
        case enums.publicKey.ed25519:
        case enums.publicKey.ed448: {
            const payloadSize = getCurvePayloadSize(algo);
            const seed = util.readExactSubarray(bytes, read, read + payloadSize);
            read += seed.length;
            return { read, privateParams: { seed } };
        }
        case enums.publicKey.x25519:
        case enums.publicKey.x448: {
            const payloadSize = getCurvePayloadSize(algo);
            const k = util.readExactSubarray(bytes, read, read + payloadSize);
            read += k.length;
            return { read, privateParams: { k } };
        }
        default:
            throw new UnsupportedError('Unknown public key encryption algorithm.');
    }
}
/** Returns the types comprising the encrypted session key of an algorithm
 * @param {module:enums.publicKey} algo - The key algorithm
 * @param {Uint8Array} bytes - The key material to parse
 * @returns {Object} The session key parameters referenced by name.
 */
function parseEncSessionKeyParams(algo, bytes) {
    let read = 0;
    switch (algo) {
        //   Algorithm-Specific Fields for RSA encrypted session keys:
        //       - MPI of RSA encrypted value m**e mod n.
        case enums.publicKey.rsaEncrypt:
        case enums.publicKey.rsaEncryptSign: {
            const c = util.readMPI(bytes.subarray(read));
            return { c };
        }
        //   Algorithm-Specific Fields for Elgamal encrypted session keys:
        //       - MPI of Elgamal value g**k mod p
        //       - MPI of Elgamal value m * y**k mod p
        case enums.publicKey.elgamal: {
            const c1 = util.readMPI(bytes.subarray(read));
            read += c1.length + 2;
            const c2 = util.readMPI(bytes.subarray(read));
            return { c1, c2 };
        }
        //   Algorithm-Specific Fields for ECDH encrypted session keys:
        //       - MPI containing the ephemeral key used to establish the shared secret
        //       - ECDH Symmetric Key
        case enums.publicKey.ecdh: {
            const V = util.readMPI(bytes.subarray(read));
            read += V.length + 2;
            const C = new ECDHSymmetricKey();
            C.read(bytes.subarray(read));
            return { V, C };
        }
        //   Algorithm-Specific Fields for X25519 or X448 encrypted session keys:
        //       - 32 octets representing an ephemeral X25519 public key (or 57 octets for X448).
        //       - A one-octet size of the following fields.
        //       - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet).
        //       - The encrypted session key.
        case enums.publicKey.x25519:
        case enums.publicKey.x448: {
            const pointSize = getCurvePayloadSize(algo);
            const ephemeralPublicKey = util.readExactSubarray(bytes, read, read + pointSize);
            read += ephemeralPublicKey.length;
            const C = new ECDHXSymmetricKey();
            C.read(bytes.subarray(read));
            return { ephemeralPublicKey, C };
        }
        default:
            throw new UnsupportedError('Unknown public key encryption algorithm.');
    }
}
/**
 * Convert params to MPI and serializes them in the proper order
 * @param {module:enums.publicKey} algo - The public key algorithm
 * @param {Object} params - The key parameters indexed by name
 * @returns {Uint8Array} The array containing the MPIs.
 */
function serializeParams(algo, params) {
    // Some algorithms do not rely on MPIs to store the binary params
    const algosWithNativeRepresentation = new Set([
        enums.publicKey.ed25519,
        enums.publicKey.x25519,
        enums.publicKey.ed448,
        enums.publicKey.x448
    ]);
    const orderedParams = Object.keys(params).map(name => {
        const param = params[name];
        if (!util.isUint8Array(param))
            return param.write();
        return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param);
    });
    return util.concatUint8Array(orderedParams);
}
/**
 * Generate algorithm-specific key parameters
 * @param {module:enums.publicKey} algo - The public key algorithm
 * @param {Integer} bits - Bit length for RSA keys
 * @param {module:type/oid} oid - Object identifier for ECC keys
 * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.
 * @async
 */
function generateParams(algo, bits, oid) {
    switch (algo) {
        case enums.publicKey.rsaEncrypt:
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.rsaSign:
            return generate$4(bits, 65537).then(({ n, e, d, p, q, u }) => ({
                privateParams: { d, p, q, u },
                publicParams: { n, e }
            }));
        case enums.publicKey.ecdsa:
            return generate$1(oid).then(({ oid, Q, secret }) => ({
                privateParams: { d: secret },
                publicParams: { oid: new OID(oid), Q }
            }));
        case enums.publicKey.eddsaLegacy:
            return generate$1(oid).then(({ oid, Q, secret }) => ({
                privateParams: { seed: secret },
                publicParams: { oid: new OID(oid), Q }
            }));
        case enums.publicKey.ecdh:
            return generate$1(oid).then(({ oid, Q, secret, hash, cipher }) => ({
                privateParams: { d: secret },
                publicParams: {
                    oid: new OID(oid),
                    Q,
                    kdfParams: new KDFParams({ hash, cipher })
                }
            }));
        case enums.publicKey.ed25519:
        case enums.publicKey.ed448:
            return generate$3(algo).then(({ A, seed }) => ({
                privateParams: { seed },
                publicParams: { A }
            }));
        case enums.publicKey.x25519:
        case enums.publicKey.x448:
            return generate$2(algo).then(({ A, k }) => ({
                privateParams: { k },
                publicParams: { A }
            }));
        case enums.publicKey.dsa:
        case enums.publicKey.elgamal:
            throw new Error('Unsupported algorithm for key generation.');
        default:
            throw new Error('Unknown public key algorithm.');
    }
}
/**
 * Validate algorithm-specific key parameters
 * @param {module:enums.publicKey} algo - The public key algorithm
 * @param {Object} publicParams - Algorithm-specific public key parameters
 * @param {Object} privateParams - Algorithm-specific private key parameters
 * @returns {Promise<Boolean>} Whether the parameters are valid.
 * @async
 */
async function validateParams$1(algo, publicParams, privateParams) {
    if (!publicParams || !privateParams) {
        throw new Error('Missing key parameters');
    }
    switch (algo) {
        case enums.publicKey.rsaEncrypt:
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.rsaSign: {
            const { n, e } = publicParams;
            const { d, p, q, u } = privateParams;
            return validateParams$9(n, e, d, p, q, u);
        }
        case enums.publicKey.dsa: {
            const { p, q, g, y } = publicParams;
            const { x } = privateParams;
            return validateParams$2(p, q, g, y, x);
        }
        case enums.publicKey.elgamal: {
            const { p, g, y } = publicParams;
            const { x } = privateParams;
            return validateParams$8(p, g, y, x);
        }
        case enums.publicKey.ecdsa:
        case enums.publicKey.ecdh: {
            const algoModule = elliptic[enums.read(enums.publicKey, algo)];
            const { oid, Q } = publicParams;
            const { d } = privateParams;
            return algoModule.validateParams(oid, Q, d);
        }
        case enums.publicKey.eddsaLegacy: {
            const { Q, oid } = publicParams;
            const { seed } = privateParams;
            return validateParams$4(oid, Q, seed);
        }
        case enums.publicKey.ed25519:
        case enums.publicKey.ed448: {
            const { A } = publicParams;
            const { seed } = privateParams;
            return validateParams$7(algo, A, seed);
        }
        case enums.publicKey.x25519:
        case enums.publicKey.x448: {
            const { A } = publicParams;
            const { k } = privateParams;
            return validateParams$6(algo, A, k);
        }
        default:
            throw new Error('Unknown public key algorithm.');
    }
}
/**
 * Generating a session key for the specified symmetric algorithm
 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
 * @param {module:enums.symmetric} algo - Symmetric encryption algorithm
 * @returns {Uint8Array} Random bytes as a string to be used as a key.
 */
function generateSessionKey$1(algo) {
    const { keySize } = getCipherParams(algo);
    return getRandomBytes(keySize);
}
/**
 * Check whether the given curve OID is supported
 * @param {module:type/oid} oid - EC object identifier
 * @throws {UnsupportedError} if curve is not supported
 */
function checkSupportedCurve(oid) {
    try {
        oid.getName();
    }
    catch {
        throw new UnsupportedError('Unknown curve OID');
    }
}
/**
 * Get encoded secret size for a given elliptic algo
 * @param {module:enums.publicKey} algo - alrogithm identifier
 * @param {module:type/oid} [oid] - curve OID if needed by algo
 */
function getCurvePayloadSize(algo, oid) {
    switch (algo) {
        case enums.publicKey.ecdsa:
        case enums.publicKey.ecdh:
        case enums.publicKey.eddsaLegacy:
            return new CurveWithOID(oid).payloadSize;
        case enums.publicKey.ed25519:
        case enums.publicKey.ed448:
            return getPayloadSize$1(algo);
        case enums.publicKey.x25519:
        case enums.publicKey.x448:
            return getPayloadSize(algo);
        default:
            throw new Error('Unknown elliptic algo');
    }
}
/**
 * Get preferred signing hash algo for a given elliptic algo
 * @param {module:enums.publicKey} algo - alrogithm identifier
 * @param {module:type/oid} [oid] - curve OID if needed by algo
 */
function getPreferredCurveHashAlgo(algo, oid) {
    switch (algo) {
        case enums.publicKey.ecdsa:
        case enums.publicKey.eddsaLegacy:
            return getPreferredHashAlgo$1(oid);
        case enums.publicKey.ed25519:
        case enums.publicKey.ed448:
            return getPreferredHashAlgo$2(algo);
        default:
            throw new Error('Unknown elliptic signing algo');
    }
}

// Modified by ProtonTech AG
// Modified by Recurity Labs GmbH
// modified version of https://www.hanewin.net/encrypt/PGdecode.js:
/* OpenPGP encryption using RSA/AES
 * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de
 * version 2.0, check www.haneWIN.de for the latest version

 * This software is provided as-is, without express or implied warranty.
 * Permission to use, copy, modify, distribute or sell this software, with or
 * without fee, for any purpose and by any individual or organization, is hereby
 * granted, provided that the above copyright notice and this paragraph appear
 * in all copies. Distribution as a part of an application or binary must
 * include the above copyright notice in the documentation and/or other
 * materials provided with the application or distribution.
 */
/**
 * @module crypto/mode/cfb
 * @access private
 */
const webCrypto$3 = util.getWebCrypto();
const nodeCrypto$3 = util.getNodeCrypto();
const knownAlgos = nodeCrypto$3 ? nodeCrypto$3.getCiphers() : [];
const nodeAlgos = {
    idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */
    tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,
    cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,
    blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,
    aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,
    aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,
    aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined
    /* twofish is not implemented in OpenSSL */
};
/**
 * Generates a random byte prefix for the specified algorithm
 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
 * @param {module:enums.symmetric} algo - Symmetric encryption algorithm
 * @returns {Promise<Uint8Array>} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.
 */
function getPrefixRandom(algo) {
    const { blockSize } = getCipherParams(algo);
    const prefixrandom = getRandomBytes(blockSize);
    const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);
    return util.concat([prefixrandom, repeat]);
}
/**
 * CFB encryption
 * @param {enums.symmetric} algo - block cipher algorithm
 * @param {Uint8Array} key
 * @param {MaybeStream<Uint8Array>} plaintext
 * @param {Uint8Array} iv
 * @param {Object} config - full configuration, defaults to openpgp.config
 * @returns MaybeStream<Uint8Array>
 */
async function encrypt$1(algo, key, plaintext, iv, config) {
    const algoName = enums.read(enums.symmetric, algo);
    if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.
        return nodeEncrypt(algo, key, plaintext, iv);
    }
    if (util.isAES(algo)) {
        return aesEncrypt(algo, key, plaintext, iv);
    }
    const LegacyCipher = await getLegacyCipher(algo);
    const cipherfn = new LegacyCipher(key);
    const block_size = cipherfn.blockSize;
    const blockc = iv.slice();
    let pt = new Uint8Array();
    const process = chunk => {
        if (chunk) {
            pt = util.concatUint8Array([pt, chunk]);
        }
        const ciphertext = new Uint8Array(pt.length);
        let i;
        let j = 0;
        while (chunk ? pt.length >= block_size : pt.length) {
            const encblock = cipherfn.encrypt(blockc);
            for (i = 0; i < block_size; i++) {
                blockc[i] = pt[i] ^ encblock[i];
                ciphertext[j++] = blockc[i];
            }
            pt = pt.subarray(block_size);
        }
        return ciphertext.subarray(0, j);
    };
    return transform(plaintext, process, process);
}
/**
 * CFB decryption
 * @param {enums.symmetric} algo - block cipher algorithm
 * @param {Uint8Array} key
 * @param {MaybeStream<Uint8Array>} ciphertext
 * @param {Uint8Array} iv
 * @returns MaybeStream<Uint8Array>
 */
async function decrypt$1(algo, key, ciphertext, iv) {
    const algoName = enums.read(enums.symmetric, algo);
    if (nodeCrypto$3 && nodeAlgos[algoName]) { // Node crypto library.
        return nodeDecrypt(algo, key, ciphertext, iv);
    }
    if (util.isAES(algo)) {
        return aesDecrypt(algo, key, ciphertext, iv);
    }
    const LegacyCipher = await getLegacyCipher(algo);
    const cipherfn = new LegacyCipher(key);
    const block_size = cipherfn.blockSize;
    let blockp = iv;
    let ct = new Uint8Array();
    const process = chunk => {
        if (chunk) {
            ct = util.concatUint8Array([ct, chunk]);
        }
        const plaintext = new Uint8Array(ct.length);
        let i;
        let j = 0;
        while (chunk ? ct.length >= block_size : ct.length) {
            const decblock = cipherfn.encrypt(blockp);
            blockp = ct.subarray(0, block_size);
            for (i = 0; i < block_size; i++) {
                plaintext[j++] = blockp[i] ^ decblock[i];
            }
            ct = ct.subarray(block_size);
        }
        return plaintext.subarray(0, j);
    };
    return transform(ciphertext, process, process);
}
class WebCryptoEncryptor {
    constructor(algo, key, iv) {
        const { blockSize } = getCipherParams(algo);
        this.key = key;
        this.iv = iv;
        this.prevBlock = iv.slice();
        this.nextBlock = new Uint8Array(blockSize);
        this.i = 0; // pointer inside next block
        this.blockSize = blockSize;
        this.zeroBlock = new Uint8Array(this.blockSize);
    }
    /**
     * @returns {Promise<boolean>}
     */
    static isSupported(algo) {
        const { keySize } = getCipherParams(algo);
        return webCrypto$3.importKey('raw', new Uint8Array(keySize), 'aes-cbc', false, ['encrypt'])
            .then(() => true, () => false);
    }
    async _runCBC(plaintext, nonZeroIV) {
        const mode = 'AES-CBC';
        this.keyRef = this.keyRef || await webCrypto$3.importKey('raw', this.key, mode, false, ['encrypt']);
        const ciphertext = await webCrypto$3.encrypt({ name: mode, iv: nonZeroIV || this.zeroBlock }, this.keyRef, plaintext);
        return new Uint8Array(ciphertext).subarray(0, plaintext.length);
    }
    async encryptChunk(value) {
        const missing = this.nextBlock.length - this.i;
        const added = value.subarray(0, missing);
        this.nextBlock.set(added, this.i);
        if ((this.i + value.length) >= (2 * this.blockSize)) {
            const leftover = (value.length - missing) % this.blockSize;
            const plaintext = util.concatUint8Array([
                this.nextBlock,
                value.subarray(missing, value.length - leftover)
            ]);
            const toEncrypt = util.concatUint8Array([
                this.prevBlock,
                plaintext.subarray(0, plaintext.length - this.blockSize) // stop one block "early", since we only need to xor the plaintext and pass it over as prevBlock
            ]);
            const encryptedBlocks = await this._runCBC(toEncrypt);
            xorMut$1(encryptedBlocks, plaintext);
            this.prevBlock = encryptedBlocks.slice(-this.blockSize);
            // take care of leftover data
            if (leftover > 0)
                this.nextBlock.set(value.subarray(-leftover));
            this.i = leftover;
            return encryptedBlocks;
        }
        this.i += added.length;
        let encryptedBlock;
        if (this.i === this.nextBlock.length) { // block ready to be encrypted
            const curBlock = this.nextBlock;
            encryptedBlock = await this._runCBC(this.prevBlock);
            xorMut$1(encryptedBlock, curBlock);
            this.prevBlock = encryptedBlock.slice();
            this.i = 0;
            const remaining = value.subarray(added.length);
            this.nextBlock.set(remaining, this.i);
            this.i += remaining.length;
        }
        else {
            encryptedBlock = new Uint8Array();
        }
        return encryptedBlock;
    }
    async finish() {
        let result;
        if (this.i === 0) { // nothing more to encrypt
            result = new Uint8Array();
        }
        else {
            this.nextBlock = this.nextBlock.subarray(0, this.i);
            const curBlock = this.nextBlock;
            const encryptedBlock = await this._runCBC(this.prevBlock);
            xorMut$1(encryptedBlock, curBlock);
            result = encryptedBlock.subarray(0, curBlock.length);
        }
        this.clearSensitiveData();
        return result;
    }
    clearSensitiveData() {
        this.nextBlock.fill(0);
        this.prevBlock.fill(0);
        this.keyRef = null;
        this.key = null;
    }
    async encrypt(plaintext) {
        // plaintext is internally padded to block length before encryption
        const encryptedWithPadding = await this._runCBC(util.concatUint8Array([new Uint8Array(this.blockSize), plaintext]), this.iv);
        // drop encrypted padding
        const ct = encryptedWithPadding.subarray(0, plaintext.length);
        xorMut$1(ct, plaintext);
        this.clearSensitiveData();
        return ct;
    }
}
class NobleStreamProcessor {
    constructor(forEncryption, algo, key, iv) {
        this.forEncryption = forEncryption;
        const { blockSize } = getCipherParams(algo);
        this.key = unsafe.expandKeyLE(key);
        if (iv.byteOffset % 4 !== 0)
            iv = iv.slice(); // aligned arrays required by noble-ciphers
        this.prevBlock = getUint32Array(iv);
        this.nextBlock = new Uint8Array(blockSize);
        this.i = 0; // pointer inside next block
        this.blockSize = blockSize;
    }
    _runCFB(src) {
        const src32 = getUint32Array(src);
        const dst = new Uint8Array(src.length);
        const dst32 = getUint32Array(dst);
        for (let i = 0; i + 4 <= dst32.length; i += 4) {
            const { s0: e0, s1: e1, s2: e2, s3: e3 } = unsafe.encrypt(this.key, this.prevBlock[0], this.prevBlock[1], this.prevBlock[2], this.prevBlock[3]);
            dst32[i + 0] = src32[i + 0] ^ e0;
            dst32[i + 1] = src32[i + 1] ^ e1;
            dst32[i + 2] = src32[i + 2] ^ e2;
            dst32[i + 3] = src32[i + 3] ^ e3;
            this.prevBlock = (this.forEncryption ? dst32 : src32).slice(i, i + 4);
        }
        return dst;
    }
    // eslint-disable-next-line @typescript-eslint/require-await
    async processChunk(value) {
        const missing = this.nextBlock.length - this.i;
        const added = value.subarray(0, missing);
        this.nextBlock.set(added, this.i);
        if ((this.i + value.length) >= (2 * this.blockSize)) {
            const leftover = (value.length - missing) % this.blockSize;
            const toProcess = util.concatUint8Array([
                this.nextBlock,
                value.subarray(missing, value.length - leftover)
            ]);
            const processedBlocks = this._runCFB(toProcess);
            // take care of leftover data
            if (leftover > 0)
                this.nextBlock.set(value.subarray(-leftover));
            this.i = leftover;
            return processedBlocks;
        }
        this.i += added.length;
        let processedBlock;
        if (this.i === this.nextBlock.length) { // block ready to be encrypted
            processedBlock = this._runCFB(this.nextBlock);
            this.i = 0;
            const remaining = value.subarray(added.length);
            this.nextBlock.set(remaining, this.i);
            this.i += remaining.length;
        }
        else {
            processedBlock = new Uint8Array();
        }
        return processedBlock;
    }
    // eslint-disable-next-line @typescript-eslint/require-await
    async finish() {
        let result;
        if (this.i === 0) { // nothing more to encrypt
            result = new Uint8Array();
        }
        else {
            const processedBlock = this._runCFB(this.nextBlock);
            result = processedBlock.subarray(0, this.i);
        }
        this.clearSensitiveData();
        return result;
    }
    clearSensitiveData() {
        this.nextBlock.fill(0);
        this.prevBlock.fill(0);
        this.key.fill(0);
    }
}
async function aesEncrypt(algo, key, pt, iv) {
    if (webCrypto$3 && await WebCryptoEncryptor.isSupported(algo)) { // Chromium does not implement AES with 192-bit keys
        const cfb = new WebCryptoEncryptor(algo, key, iv);
        return util.isStream(pt) ? transformAsync(pt, value => cfb.encryptChunk(value), () => cfb.finish()) : cfb.encrypt(pt);
    }
    else if (util.isStream(pt)) { // async callbacks are not accepted by streamTransform unless the input is a stream
        const cfb = new NobleStreamProcessor(true, algo, key, iv);
        return transformAsync(pt, value => cfb.processChunk(value), () => cfb.finish());
    }
    return cfb(key, iv).encrypt(pt);
}
function aesDecrypt(algo, key, ct, iv) {
    if (util.isStream(ct)) {
        const cfb = new NobleStreamProcessor(false, algo, key, iv);
        return transformAsync(ct, value => cfb.processChunk(value), () => cfb.finish());
    }
    return cfb(key, iv).decrypt(ct);
}
function xorMut$1(a, b) {
    const aLength = Math.min(a.length, b.length);
    for (let i = 0; i < aLength; i++) {
        a[i] = a[i] ^ b[i];
    }
}
const getUint32Array = arr => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
function nodeEncrypt(algo, key, pt, iv) {
    const algoName = enums.read(enums.symmetric, algo);
    const cipherObj = new nodeCrypto$3.createCipheriv(nodeAlgos[algoName], key, iv);
    return transform(pt, value => new Uint8Array(cipherObj.update(value)));
}
function nodeDecrypt(algo, key, ct, iv) {
    const algoName = enums.read(enums.symmetric, algo);
    const decipherObj = new nodeCrypto$3.createDecipheriv(nodeAlgos[algoName], key, iv);
    return transform(ct, value => new Uint8Array(decipherObj.update(value)));
}

/**
 * @fileoverview This module implements AES-CMAC on top of
 * native AES-CBC using either the WebCrypto API or Node.js' crypto API.
 * @module crypto/cmac
 * @access private
 */
const webCrypto$2 = util.getWebCrypto();
const nodeCrypto$2 = util.getNodeCrypto();
/**
 * This implementation of CMAC is based on the description of OMAC in
 * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that
 * document:
 *
 * We have made a small modification to the OMAC algorithm as it was
 * originally presented, changing one of its two constants.
 * Specifically, the constant 4 at line 85 was the constant 1/2 (the
 * multiplicative inverse of 2) in the original definition of OMAC [14].
 * The OMAC authors indicate that they will promulgate this modification
 * [15], which slightly simplifies implementations.
 */
const blockLength$3 = 16;
/**
 * xor `padding` into the end of `data`. This function implements "the
 * operation xor→ [which] xors the shorter string into the end of longer
 * one". Since data is always as least as long as padding, we can
 * simplify the implementation.
 * @param {Uint8Array} data
 * @param {Uint8Array} padding
 */
function rightXORMut(data, padding) {
    const offset = data.length - blockLength$3;
    for (let i = 0; i < blockLength$3; i++) {
        data[i + offset] ^= padding[i];
    }
    return data;
}
function pad(data, padding, padding2) {
    // if |M| in {n, 2n, 3n, ...}
    if (data.length && data.length % blockLength$3 === 0) {
        // then return M xor→ B,
        return rightXORMut(data, padding);
    }
    // else return (M || 10^(n−1−(|M| mod n))) xor→ P
    const padded = new Uint8Array(data.length + (blockLength$3 - (data.length % blockLength$3)));
    padded.set(data);
    padded[data.length] = 0b10000000;
    return rightXORMut(padded, padding2);
}
const zeroBlock$1 = new Uint8Array(blockLength$3);
async function CMAC(key) {
    const cbc = await CBC(key);
    // L ← E_K(0^n); B ← 2L; P ← 4L
    const padding = util.double(await cbc(zeroBlock$1));
    const padding2 = util.double(padding);
    return async function (data) {
        // return CBC_K(pad(M; B, P))
        return (await cbc(pad(data, padding, padding2))).subarray(-blockLength$3);
    };
}
async function CBC(key) {
    if (util.getNodeCrypto()) { // Node crypto library
        // eslint-disable-next-line @typescript-eslint/require-await
        return async function (pt) {
            const en = new nodeCrypto$2.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock$1);
            const ct = en.update(pt);
            return new Uint8Array(ct);
        };
    }
    if (util.getWebCrypto()) {
        try {
            key = await webCrypto$2.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);
            return async function (pt) {
                const ct = await webCrypto$2.encrypt({ name: 'AES-CBC', iv: zeroBlock$1, length: blockLength$3 * 8 }, key, pt);
                return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength$3);
            };
        }
        catch (err) {
            // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
            if (err.name !== 'NotSupportedError' &&
                !(key.length === 24 && err.name === 'OperationError')) {
                throw err;
            }
            util.printDebugError('Browser did not support operation: ' + err.message);
        }
    }
    // eslint-disable-next-line @typescript-eslint/require-await
    return async function (pt) {
        return cbc(key, zeroBlock$1, { disablePadding: true }).encrypt(pt);
    };
}

// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2018 ProtonTech AG
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview This module implements AES-EAX en/decryption on top of
 * native AES-CTR using either the WebCrypto API or Node.js' crypto API.
 * @module crypto/mode/eax
 * @access private
 */
const webCrypto$1 = util.getWebCrypto();
const nodeCrypto$1 = util.getNodeCrypto();
const Buffer$2 = util.getNodeBuffer();
const blockLength$2 = 16;
const ivLength$2 = blockLength$2;
const tagLength$2 = blockLength$2;
const zero = new Uint8Array(blockLength$2);
const one$1 = new Uint8Array(blockLength$2);
one$1[blockLength$2 - 1] = 1;
const two = new Uint8Array(blockLength$2);
two[blockLength$2 - 1] = 2;
async function OMAC(key) {
    const cmac = await CMAC(key);
    return function (t, message) {
        return cmac(util.concatUint8Array([t, message]));
    };
}
async function CTR(key) {
    if (util.getNodeCrypto()) { // Node crypto library
        // eslint-disable-next-line @typescript-eslint/require-await
        return async function (pt, iv) {
            const en = new nodeCrypto$1.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);
            const ct = Buffer$2.concat([en.update(pt), en.final()]);
            return new Uint8Array(ct);
        };
    }
    if (util.getWebCrypto()) {
        try {
            const keyRef = await webCrypto$1.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);
            return async function (pt, iv) {
                const ct = await webCrypto$1.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$2 * 8 }, keyRef, pt);
                return new Uint8Array(ct);
            };
        }
        catch (err) {
            // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
            if (err.name !== 'NotSupportedError' &&
                !(key.length === 24 && err.name === 'OperationError')) {
                throw err;
            }
            util.printDebugError('Browser did not support operation: ' + err.message);
        }
    }
    // eslint-disable-next-line @typescript-eslint/require-await
    return async function (pt, iv) {
        return ctr(key, iv).encrypt(pt);
    };
}
/**
 * Class to en/decrypt using EAX mode.
 * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use
 * @param {Uint8Array} key - The encryption key
 */
async function EAX(cipher, key) {
    if (cipher !== enums.symmetric.aes128 &&
        cipher !== enums.symmetric.aes192 &&
        cipher !== enums.symmetric.aes256) {
        throw new Error('EAX mode supports only AES cipher');
    }
    const [omac, ctr] = await Promise.all([
        OMAC(key),
        CTR(key)
    ]);
    return {
        /**
         * Encrypt plaintext input.
         * @param {Uint8Array} plaintext - The cleartext input to be encrypted
         * @param {Uint8Array} nonce - The nonce (16 bytes)
         * @param {Uint8Array} adata - Associated data to sign
         * @returns {Promise<Uint8Array>} The ciphertext output.
         */
        encrypt: async function (plaintext, nonce, adata) {
            const [omacNonce, omacAdata] = await Promise.all([
                omac(zero, nonce),
                omac(one$1, adata)
            ]);
            const ciphered = await ctr(plaintext, omacNonce);
            const omacCiphered = await omac(two, ciphered);
            const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
            for (let i = 0; i < tagLength$2; i++) {
                tag[i] ^= omacAdata[i] ^ omacNonce[i];
            }
            return util.concatUint8Array([ciphered, tag]);
        },
        /**
         * Decrypt ciphertext input.
         * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted
         * @param {Uint8Array} nonce - The nonce (16 bytes)
         * @param {Uint8Array} adata - Associated data to verify
         * @returns {Promise<Uint8Array>} The plaintext output.
         */
        decrypt: async function (ciphertext, nonce, adata) {
            if (ciphertext.length < tagLength$2)
                throw new Error('Invalid EAX ciphertext');
            const ciphered = ciphertext.subarray(0, -tagLength$2);
            const ctTag = ciphertext.subarray(-tagLength$2);
            const [omacNonce, omacAdata, omacCiphered] = await Promise.all([
                omac(zero, nonce),
                omac(one$1, adata),
                omac(two, ciphered)
            ]);
            const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
            for (let i = 0; i < tagLength$2; i++) {
                tag[i] ^= omacAdata[i] ^ omacNonce[i];
            }
            if (!util.timingSafeEqualsUint8Array(ctTag, tag))
                throw new Error('Authentication tag mismatch');
            const plaintext = await ctr(ciphered, omacNonce);
            return plaintext;
        }
    };
}
/**
 * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}.
 * @param {Uint8Array} iv - The initialization vector (16 bytes)
 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
 */
EAX.getNonce = function (iv, chunkIndex) {
    const nonce = iv.slice();
    for (let i = 0; i < chunkIndex.length; i++) {
        nonce[8 + i] ^= chunkIndex[i];
    }
    return nonce;
};
EAX.blockLength = blockLength$2;
EAX.ivLength = ivLength$2;
EAX.tagLength = tagLength$2;

// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2018 ProtonTech AG
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview This module implements AES-OCB en/decryption.
 * @module crypto/mode/ocb
 * @access private
 */
const blockLength$1 = 16;
const ivLength$1 = 15;
// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:
// While OCB [RFC7253] allows the authentication tag length to be of any
// number up to 128 bits long, this document requires a fixed
// authentication tag length of 128 bits (16 octets) for simplicity.
const tagLength$1 = 16;
function ntz(n) {
    let ntz = 0;
    for (let i = 1; (n & i) === 0; i <<= 1) {
        ntz++;
    }
    return ntz;
}
function xorMut(S, T) {
    for (let i = 0; i < S.length; i++) {
        S[i] ^= T[i];
    }
    return S;
}
function xor(S, T) {
    return xorMut(S.slice(), T);
}
const zeroBlock = new Uint8Array(blockLength$1);
const one = new Uint8Array([1]);
/**
 * Class to en/decrypt using OCB mode.
 * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use
 * @param {Uint8Array} key - The encryption key
 */
// eslint-disable-next-line @typescript-eslint/require-await
async function OCB(cipher, key) {
    const { keySize } = getCipherParams(cipher);
    // sanity checks
    if (!util.isAES(cipher) || key.length !== keySize) {
        throw new Error('Unexpected algorithm or key size');
    }
    let maxNtz = 0;
    // `encipher` and `decipher` cannot be async, since `crypt` shares state across calls,
    // hence its execution cannot be broken up.
    // As a result, WebCrypto cannot currently be used for `encipher`.
    const encipher = block => cbc(key, zeroBlock, { disablePadding: true }).encrypt(block);
    const decipher = block => cbc(key, zeroBlock, { disablePadding: true }).decrypt(block);
    let mask;
    constructKeyVariables();
    function constructKeyVariables() {
        const mask_x = encipher(zeroBlock);
        const mask_$ = util.double(mask_x);
        mask = [];
        mask[0] = util.double(mask_$);
        mask.x = mask_x;
        mask.$ = mask_$;
    }
    function extendKeyVariables(text, adata) {
        const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$1 | 0) - 1;
        for (let i = maxNtz + 1; i <= newMaxNtz; i++) {
            mask[i] = util.double(mask[i - 1]);
        }
        maxNtz = newMaxNtz;
    }
    function hash(adata) {
        if (!adata.length) {
            // Fast path
            return zeroBlock;
        }
        //
        // Consider A as a sequence of 128-bit blocks
        //
        const m = adata.length / blockLength$1 | 0;
        const offset = new Uint8Array(blockLength$1);
        const sum = new Uint8Array(blockLength$1);
        for (let i = 0; i < m; i++) {
            xorMut(offset, mask[ntz(i + 1)]);
            xorMut(sum, encipher(xor(offset, adata)));
            adata = adata.subarray(blockLength$1);
        }
        //
        // Process any final partial block; compute final hash value
        //
        if (adata.length) {
            xorMut(offset, mask.x);
            const cipherInput = new Uint8Array(blockLength$1);
            cipherInput.set(adata, 0);
            cipherInput[adata.length] = 0b10000000;
            xorMut(cipherInput, offset);
            xorMut(sum, encipher(cipherInput));
        }
        return sum;
    }
    /**
     * Encrypt/decrypt data.
     * @param {encipher|decipher} fn - Encryption/decryption block cipher function
     * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input
     * @param {Uint8Array} nonce - The nonce (15 bytes)
     * @param {Uint8Array} adata - Associated data to sign
     * @returns {Promise<Uint8Array>} The ciphertext or plaintext output, with tag appended in both cases.
     */
    function crypt(fn, text, nonce, adata) {
        //
        // Consider P as a sequence of 128-bit blocks
        //
        const m = text.length / blockLength$1 | 0;
        //
        // Key-dependent variables
        //
        extendKeyVariables(text, adata);
        //
        // Nonce-dependent and per-encryption variables
        //
        //    Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N
        // Note: We assume here that tagLength mod 16 == 0.
        const paddedNonce = util.concatUint8Array([zeroBlock.subarray(0, ivLength$1 - nonce.length), one, nonce]);
        //    bottom = str2num(Nonce[123..128])
        const bottom = paddedNonce[blockLength$1 - 1] & 0b111111;
        //    Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))
        paddedNonce[blockLength$1 - 1] &= 0b11000000;
        const kTop = encipher(paddedNonce);
        //    Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])
        const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);
        //    Offset_0 = Stretch[1+bottom..128+bottom]
        const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);
        //    Checksum_0 = zeros(128)
        const checksum = new Uint8Array(blockLength$1);
        const ct = new Uint8Array(text.length + tagLength$1);
        //
        // Process any whole blocks
        //
        let i;
        let pos = 0;
        for (i = 0; i < m; i++) {
            // Offset_i = Offset_{i-1} xor L_{ntz(i)}
            xorMut(offset, mask[ntz(i + 1)]);
            // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)
            // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)
            ct.set(xorMut(fn(xor(offset, text)), offset), pos);
            // Checksum_i = Checksum_{i-1} xor P_i
            xorMut(checksum, fn === encipher ? text : ct.subarray(pos));
            text = text.subarray(blockLength$1);
            pos += blockLength$1;
        }
        //
        // Process any final partial block and compute raw tag
        //
        if (text.length) {
            // Offset_* = Offset_m xor L_*
            xorMut(offset, mask.x);
            // Pad = ENCIPHER(K, Offset_*)
            const padding = encipher(offset);
            // C_* = P_* xor Pad[1..bitlen(P_*)]
            ct.set(xor(text, padding), pos);
            // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))
            const xorInput = new Uint8Array(blockLength$1);
            xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0);
            xorInput[text.length] = 0b10000000;
            xorMut(checksum, xorInput);
            pos += text.length;
        }
        // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)
        const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata));
        //
        // Assemble ciphertext
        //
        // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]
        ct.set(tag, pos);
        return ct;
    }
    return {
        /**
         * Encrypt plaintext input.
         * @param {Uint8Array} plaintext - The cleartext input to be encrypted
         * @param {Uint8Array} nonce - The nonce (15 bytes)
         * @param {Uint8Array} adata - Associated data to sign
         * @returns {Promise<Uint8Array>} The ciphertext output.
         */
        encrypt: async function (plaintext, nonce, adata) {
            return crypt(encipher, plaintext, nonce, adata);
        },
        /**
         * Decrypt ciphertext input.
         * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted
         * @param {Uint8Array} nonce - The nonce (15 bytes)
         * @param {Uint8Array} adata - Associated data to sign
         * @returns {Promise<Uint8Array>} The ciphertext output.
         */
        // eslint-disable-next-line @typescript-eslint/require-await
        decrypt: async function (ciphertext, nonce, adata) {
            if (ciphertext.length < tagLength$1)
                throw new Error('Invalid OCB ciphertext');
            const tag = ciphertext.subarray(-tagLength$1);
            ciphertext = ciphertext.subarray(0, -tagLength$1);
            const crypted = crypt(decipher, ciphertext, nonce, adata);
            // if (Tag[1..TAGLEN] == T)
            if (util.timingSafeEqualsUint8Array(tag, crypted.subarray(-tagLength$1))) {
                return crypted.subarray(0, -tagLength$1);
            }
            throw new Error('Authentication tag mismatch');
        }
    };
}
/**
 * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}.
 * @param {Uint8Array} iv - The initialization vector (15 bytes)
 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
 */
OCB.getNonce = function (iv, chunkIndex) {
    const nonce = iv.slice();
    for (let i = 0; i < chunkIndex.length; i++) {
        nonce[7 + i] ^= chunkIndex[i];
    }
    return nonce;
};
OCB.blockLength = blockLength$1;
OCB.ivLength = ivLength$1;
OCB.tagLength = tagLength$1;

// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2016 Tankred Hase
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * @fileoverview This module wraps native AES-GCM en/decryption for both
 * the WebCrypto api as well as node.js' crypto api.
 * @module crypto/mode/gcm
 * @access private
 */
const webCrypto = util.getWebCrypto();
const nodeCrypto = util.getNodeCrypto();
const Buffer$1 = util.getNodeBuffer();
const blockLength = 16;
const ivLength = 12; // size of the IV in bytes
const tagLength = 16; // size of the tag in bytes
const ALGO = 'AES-GCM';
/**
 * Class to en/decrypt using GCM mode.
 * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use
 * @param {Uint8Array} key - The encryption key
 */
async function GCM(cipher, key) {
    if (cipher !== enums.symmetric.aes128 &&
        cipher !== enums.symmetric.aes192 &&
        cipher !== enums.symmetric.aes256) {
        throw new Error('GCM mode supports only AES cipher');
    }
    if (util.getNodeCrypto()) { // Node crypto library
        return {
            // eslint-disable-next-line @typescript-eslint/require-await
            encrypt: async function (pt, iv, adata = new Uint8Array()) {
                const en = new nodeCrypto.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);
                en.setAAD(adata);
                const ct = Buffer$1.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext
                return new Uint8Array(ct);
            },
            // eslint-disable-next-line @typescript-eslint/require-await
            decrypt: async function (ct, iv, adata = new Uint8Array()) {
                const de = new nodeCrypto.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);
                de.setAAD(adata);
                de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext
                const pt = Buffer$1.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]);
                return new Uint8Array(pt);
            }
        };
    }
    if (util.getWebCrypto()) {
        try {
            const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);
            // Safari 13 and Safari iOS 14 does not support GCM-en/decrypting empty messages
            const webcryptoEmptyMessagesUnsupported = navigator.userAgent.match(/Version\/13\.\d(\.\d)* Safari/) ||
                navigator.userAgent.match(/Version\/(13|14)\.\d(\.\d)* Mobile\/\S* Safari/);
            return {
                encrypt: async function (pt, iv, adata = new Uint8Array()) {
                    if (webcryptoEmptyMessagesUnsupported && !pt.length) {
                        return gcm(key, iv, adata).encrypt(pt);
                    }
                    const ct = await webCrypto.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);
                    return new Uint8Array(ct);
                },
                decrypt: async function (ct, iv, adata = new Uint8Array()) {
                    if (webcryptoEmptyMessagesUnsupported && ct.length === tagLength) {
                        return gcm(key, iv, adata).decrypt(ct);
                    }
                    try {
                        const pt = await webCrypto.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);
                        return new Uint8Array(pt);
                    }
                    catch (e) {
                        if (e.name === 'OperationError') {
                            throw new Error('Authentication tag mismatch');
                        }
                    }
                }
            };
        }
        catch (err) {
            // no 192 bit support in Chromium, which throws `OperationError`, see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
            if (err.name !== 'NotSupportedError' &&
                !(key.length === 24 && err.name === 'OperationError')) {
                throw err;
            }
            util.printDebugError('Browser did not support operation: ' + err.message);
        }
    }
    return {
        // eslint-disable-next-line @typescript-eslint/require-await
        encrypt: async function (pt, iv, adata) {
            return gcm(key, iv, adata).encrypt(pt);
        },
        // eslint-disable-next-line @typescript-eslint/require-await
        decrypt: async function (ct, iv, adata) {
            return gcm(key, iv, adata).decrypt(ct);
        }
    };
}
/**
 * Get GCM nonce. Note: this operation is not defined by the standard.
 * A future version of the standard may define GCM mode differently,
 * hopefully under a different ID (we use Private/Experimental algorithm
 * ID 100) so that we can maintain backwards compatibility.
 * @param {Uint8Array} iv - The initialization vector (12 bytes)
 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
 */
GCM.getNonce = function (iv, chunkIndex) {
    const nonce = iv.slice();
    for (let i = 0; i < chunkIndex.length; i++) {
        nonce[4 + i] ^= chunkIndex[i];
    }
    return nonce;
};
GCM.blockLength = blockLength;
GCM.ivLength = ivLength;
GCM.tagLength = tagLength;

/**
 * @fileoverview Cipher modes
 * @module crypto/cipherMode
 * @access private
 */
/**
* Get implementation of the given AEAD mode
* @param {enums.aead} algo
* @param {Boolean} [acceptExperimentalGCM] - whether to allow the non-standard, legacy `experimentalGCM` algo
* @returns {Object}
* @throws {Error} on invalid algo
*/
function getAEADMode(algo, acceptExperimentalGCM = false) {
    switch (algo) {
        case enums.aead.eax:
            return EAX;
        case enums.aead.ocb:
            return OCB;
        case enums.aead.gcm:
            return GCM;
        case enums.aead.experimentalGCM:
            if (!acceptExperimentalGCM) {
                throw new Error('Unexpected non-standard `experimentalGCM` AEAD algorithm provided in `config.preferredAEADAlgorithm`: use `gcm` instead');
            }
            return GCM;
        default:
            throw new Error('Unsupported AEAD mode');
    }
}

/**
 * @fileoverview Provides functions for asymmetric signing and signature verification
 * @module crypto/signature
 * @access private
 */
/**
 * Parse signature in binary form to get the parameters.
 * The returned values are only padded for EdDSA, since in the other cases their expected length
 * depends on the key params, hence we delegate the padding to the signature verification function.
 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
 * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}
 * @param {module:enums.publicKey} algo - Public key algorithm
 * @param {Uint8Array} signature - Data for which the signature was created
 * @returns {Promise<Object>} True if signature is valid.
 * @async
 */
function parseSignatureParams(algo, signature) {
    let read = 0;
    switch (algo) {
        // Algorithm-Specific Fields for RSA signatures:
        // -  MPI of RSA signature value m**d mod n.
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.rsaEncrypt:
        case enums.publicKey.rsaSign: {
            const s = util.readMPI(signature.subarray(read));
            read += s.length + 2;
            // The signature needs to be the same length as the public key modulo n.
            // We pad s on signature verification, where we have access to n.
            return { read, signatureParams: { s } };
        }
        // Algorithm-Specific Fields for DSA or ECDSA signatures:
        // -  MPI of DSA or ECDSA value r.
        // -  MPI of DSA or ECDSA value s.
        case enums.publicKey.dsa:
        case enums.publicKey.ecdsa:
            {
                // If the signature payload sizes are unexpected, we will throw on verification,
                // where we also have access to the OID curve from the key.
                const r = util.readMPI(signature.subarray(read));
                read += r.length + 2;
                const s = util.readMPI(signature.subarray(read));
                read += s.length + 2;
                return { read, signatureParams: { r, s } };
            }
        // Algorithm-Specific Fields for legacy EdDSA signatures:
        // -  MPI of an EC point r.
        // -  EdDSA value s, in MPI, in the little endian representation
        case enums.publicKey.eddsaLegacy: {
            // Only Curve25519Legacy is supported (no Curve448Legacy), but the relevant checks are done on key parsing and signature
            // verification: if the signature payload sizes are unexpected, we will throw on verification,
            // where we also have access to the OID curve from the key.
            const r = util.readMPI(signature.subarray(read));
            read += r.length + 2;
            const s = util.readMPI(signature.subarray(read));
            read += s.length + 2;
            return { read, signatureParams: { r, s } };
        }
        // Algorithm-Specific Fields for Ed25519 signatures:
        // - 64 octets of the native signature
        // Algorithm-Specific Fields for Ed448 signatures:
        // - 114 octets of the native signature
        case enums.publicKey.ed25519:
        case enums.publicKey.ed448: {
            const rsSize = 2 * getPayloadSize$1(algo);
            const RS = util.readExactSubarray(signature, read, read + rsSize);
            read += RS.length;
            return { read, signatureParams: { RS } };
        }
        default:
            throw new UnsupportedError('Unknown signature algorithm.');
    }
}
/**
 * Verifies the signature provided for data using specified algorithms and public key parameters.
 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
 * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
 * for public key and hash algorithms.
 * @param {module:enums.publicKey} algo - Public key algorithm
 * @param {module:enums.hash} hashAlgo - Hash algorithm
 * @param {Object} signature - Named algorithm-specific signature parameters
 * @param {Object} publicParams - Algorithm-specific public key parameters
 * @param {Uint8Array} data - Data for which the signature was created
 * @param {Uint8Array} hashed - The hashed data
 * @returns {Promise<Boolean>} True if signature is valid.
 * @async
 */
async function verify$1(algo, hashAlgo, signature, publicParams, data, hashed) {
    switch (algo) {
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.rsaEncrypt:
        case enums.publicKey.rsaSign: {
            const { n, e } = publicParams;
            const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto
            return verify$6(hashAlgo, data, s, n, e, hashed);
        }
        case enums.publicKey.dsa: {
            const { g, p, q, y } = publicParams;
            const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers
            return verify$2(hashAlgo, r, s, hashed, g, p, q, y);
        }
        case enums.publicKey.ecdsa: {
            const { oid, Q } = publicParams;
            const curveSize = new CurveWithOID(oid).payloadSize;
            // padding needed for webcrypto
            const r = util.leftPad(signature.r, curveSize);
            const s = util.leftPad(signature.s, curveSize);
            return verify$4(oid, hashAlgo, { r, s }, data, Q, hashed);
        }
        case enums.publicKey.eddsaLegacy: {
            const { oid, Q } = publicParams;
            const curveSize = new CurveWithOID(oid).payloadSize;
            // When dealing little-endian MPI data, we always need to left-pad it, as done with big-endian values:
            // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9
            const r = util.leftPad(signature.r, curveSize);
            const s = util.leftPad(signature.s, curveSize);
            return verify$3(oid, hashAlgo, { r, s }, data, Q, hashed);
        }
        case enums.publicKey.ed25519:
        case enums.publicKey.ed448: {
            const { A } = publicParams;
            return verify$5(algo, hashAlgo, signature, data, A, hashed);
        }
        default:
            throw new Error('Unknown signature algorithm.');
    }
}
/**
 * Creates a signature on data using specified algorithms and private key parameters.
 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
 * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
 * for public key and hash algorithms.
 * @param {module:enums.publicKey} algo - Public key algorithm
 * @param {module:enums.hash} hashAlgo - Hash algorithm
 * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters
 * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters
 * @param {Uint8Array} data - Data to be signed
 * @param {Uint8Array} hashed - The hashed data
 * @returns {Promise<Object>} Signature                      Object containing named signature parameters.
 * @async
 */
async function sign$1(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {
    if (!publicKeyParams || !privateKeyParams) {
        throw new Error('Missing key parameters');
    }
    switch (algo) {
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.rsaEncrypt:
        case enums.publicKey.rsaSign: {
            const { n, e } = publicKeyParams;
            const { d, p, q, u } = privateKeyParams;
            const s = await sign$6(hashAlgo, data, n, e, d, p, q, u, hashed);
            return { s };
        }
        case enums.publicKey.dsa: {
            const { g, p, q } = publicKeyParams;
            const { x } = privateKeyParams;
            return sign$2(hashAlgo, hashed, g, p, q, x);
        }
        case enums.publicKey.elgamal:
            throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');
        case enums.publicKey.ecdsa: {
            const { oid, Q } = publicKeyParams;
            const { d } = privateKeyParams;
            return sign$4(oid, hashAlgo, data, Q, d, hashed);
        }
        case enums.publicKey.eddsaLegacy: {
            const { oid, Q } = publicKeyParams;
            const { seed } = privateKeyParams;
            return sign$3(oid, hashAlgo, data, Q, seed, hashed);
        }
        case enums.publicKey.ed25519:
        case enums.publicKey.ed448: {
            const { A } = publicKeyParams;
            const { seed } = privateKeyParams;
            return sign$5(algo, hashAlgo, data, A, seed, hashed);
        }
        default:
            throw new Error('Unknown signature algorithm.');
    }
}

/** @access private */
const ARGON2_TYPE = 0x02; // id
const ARGON2_VERSION = 0x13;
const ARGON2_SALT_SIZE = 16;
// Max exponent supported, that applies regardless of `config.maxArgon2MemoryExponent`;
// the argon2 lib in principle supports a larger value, but this is already unrealistically large,
// and it enables us to use bitwise operations.
const ARGON2_MAX_ENCODEDM = 30;
class Argon2OutOfMemoryError extends Error {
    constructor(...params) {
        super(...params);
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, Argon2OutOfMemoryError);
        }
        this.name = 'Argon2OutOfMemoryError';
    }
}
// cache argon wasm module
let loadArgonWasmModule;
let argon2Promise;
// reload wasm module above this treshold, to deallocated used memory
const ARGON2_WASM_MEMORY_THRESHOLD_RELOAD = 2 << 19;
/** @access private */
class Argon2S2K {
    /**
    * @param {Object} [config] - Full configuration, defaults to openpgp.config
    */
    constructor(config$1 = config) {
        const { passes, parallelism, memoryExponent } = config$1.s2kArgon2Params;
        this.type = 'argon2';
        /**
         * 16 bytes of salt
         * @type {Uint8Array}
         */
        this.salt = null;
        /**
         * number of passes
         * @type {Integer}
         */
        this.t = passes;
        /**
         * degree of parallelism (lanes)
         * @type {Integer}
         */
        this.p = parallelism;
        /**
         * exponent indicating memory size
         * @type {Integer}
         */
        this.encodedM = memoryExponent;
    }
    generateSalt() {
        this.salt = getRandomBytes(ARGON2_SALT_SIZE);
    }
    /**
    * Parsing function for argon2 string-to-key specifier.
    * @param {Uint8Array} bytes - Payload of argon2 string-to-key specifier
    * @returns {Integer} Actual length of the object.
    */
    read(bytes) {
        let i = 0;
        this.salt = bytes.subarray(i, i + 16);
        i += 16;
        this.t = bytes[i++];
        this.p = bytes[i++];
        this.encodedM = bytes[i++]; // memory size exponent, one-octect
        return i;
    }
    /**
    * Serializes s2k information
    * @returns {Uint8Array} Binary representation of s2k.
    */
    write() {
        const arr = [
            new Uint8Array([enums.write(enums.s2k, this.type)]),
            this.salt,
            new Uint8Array([this.t, this.p, this.encodedM])
        ];
        return util.concatUint8Array(arr);
    }
    /**
    * Produces a key using the specified passphrase and the defined
    * hashAlgorithm
    * @param {String} passphrase - Passphrase containing user input
    * @param {Number} keySize
    * @param {Object} config
    * @returns {Promise<Uint8Array>} Produced key with a length corresponding to `keySize`
    * @throws {Argon2OutOfMemoryError|Errors}
    * @async
    */
    async produceKey(passphrase, keySize, config) {
        if (config.maxArgon2MemoryExponent > ARGON2_MAX_ENCODEDM) {
            throw new Argon2OutOfMemoryError(`'config.maxArgon2MemoryExponent' exceeds the max allowed value of ${ARGON2_MAX_ENCODEDM}`);
        }
        if (this.encodedM > config.maxArgon2MemoryExponent) {
            throw new Argon2OutOfMemoryError('Argon2 required memory exceeds `config.maxArgon2MemoryExponent`');
        }
        const decodedM = 1 << this.encodedM;
        try {
            // on first load, the argon2 lib is imported and the WASM module is initialized.
            // the two steps need to be atomic to avoid race conditions causing multiple wasm modules
            // being loaded when `argon2Promise` is not initialized.
            loadArgonWasmModule = loadArgonWasmModule || (await Promise.resolve().then(function () { return index$2; })).default;
            argon2Promise = argon2Promise || loadArgonWasmModule();
            // important to keep local ref to argon2 in case the module is reloaded by another instance
            const argon2 = await argon2Promise;
            const passwordBytes = util.encodeUTF8(passphrase);
            const hash = argon2({
                version: ARGON2_VERSION,
                type: ARGON2_TYPE,
                password: passwordBytes,
                salt: this.salt,
                tagLength: keySize,
                memorySize: decodedM,
                parallelism: this.p,
                passes: this.t
            });
            // a lot of memory was used, reload to deallocate
            if (decodedM > ARGON2_WASM_MEMORY_THRESHOLD_RELOAD) {
                // it will be awaited if needed at the next `produceKey` invocation
                argon2Promise = loadArgonWasmModule();
                argon2Promise.catch(() => { });
            }
            return hash;
        }
        catch (e) {
            if (e.message && (e.message.includes('Unable to grow instance memory') || // Chrome
                e.message.includes('failed to grow memory') || // Firefox
                e.message.includes('WebAssembly.Memory.grow') || // Safari
                e.message.includes('Out of memory') // Safari iOS
            )) {
                throw new Argon2OutOfMemoryError('Could not allocate required memory for Argon2');
            }
            else {
                throw e;
            }
        }
    }
}

/** @access private */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Implementation of the String-to-key specifier
 *
 * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}:
 * String-to-key (S2K) specifiers are used to convert passphrase strings
 * into symmetric-key encryption/decryption keys.  They are used in two
 * places, currently: to encrypt the secret part of private keys in the
 * private keyring, and to convert passphrases to encryption keys for
 * symmetrically encrypted messages.
 * @access private
 */
class GenericS2K {
    /**
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     */
    constructor(s2kType, config$1 = config) {
        /**
         * Hash function identifier, or 0 for gnu-dummy keys
         * @type {module:enums.hash | 0}
         */
        this.algorithm = enums.hash.sha256;
        /**
         * enums.s2k identifier or 'gnu-dummy'
         * @type {String}
         */
        this.type = enums.read(enums.s2k, s2kType);
        /** @type {Integer} */
        this.c = config$1.s2kIterationCountByte;
        /** Eight bytes of salt in a binary string.
         * @type {Uint8Array}
         */
        this.salt = null;
    }
    generateSalt() {
        switch (this.type) {
            case 'salted':
            case 'iterated':
                this.salt = getRandomBytes(8);
        }
    }
    getCount() {
        // Exponent bias, defined in RFC4880
        const expbias = 6;
        return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);
    }
    /**
     * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).
     * @param {Uint8Array} bytes - Payload of string-to-key specifier
     * @returns {Integer} Actual length of the object.
     */
    read(bytes) {
        let i = 0;
        this.algorithm = bytes[i++];
        switch (this.type) {
            case 'simple':
                break;
            case 'salted':
                this.salt = bytes.subarray(i, i + 8);
                i += 8;
                break;
            case 'iterated':
                this.salt = bytes.subarray(i, i + 8);
                i += 8;
                // Octet 10: count, a one-octet, coded value
                this.c = bytes[i++];
                break;
            case 'gnu':
                if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {
                    i += 3; // GNU
                    const gnuExtType = 1000 + bytes[i++];
                    if (gnuExtType === 1001) {
                        this.type = 'gnu-dummy';
                        // GnuPG extension mode 1001 -- don't write secret key at all
                    }
                    else {
                        throw new UnsupportedError('Unknown s2k gnu protection mode.');
                    }
                }
                else {
                    throw new UnsupportedError('Unknown s2k type.');
                }
                break;
            default:
                throw new UnsupportedError('Unknown s2k type.'); // unreachable
        }
        return i;
    }
    /**
     * Serializes s2k information
     * @returns {Uint8Array} Binary representation of s2k.
     */
    write() {
        if (this.type === 'gnu-dummy') {
            return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);
        }
        const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])];
        switch (this.type) {
            case 'simple':
                break;
            case 'salted':
                arr.push(this.salt);
                break;
            case 'iterated':
                arr.push(this.salt);
                arr.push(new Uint8Array([this.c]));
                break;
            case 'gnu':
                throw new Error('GNU s2k type not supported.');
            default:
                throw new Error('Unknown s2k type.');
        }
        return util.concatUint8Array(arr);
    }
    /**
     * Produces a key using the specified passphrase and the defined
     * hashAlgorithm
     * @param {String} passphrase - Passphrase containing user input
     * @returns {Promise<Uint8Array>} Produced key with a length corresponding to.
     * hashAlgorithm hash length
     * @async
     */
    async produceKey(passphrase, numBytes, _config) {
        passphrase = util.encodeUTF8(passphrase);
        const arr = [];
        let rlength = 0;
        let prefixlen = 0;
        while (rlength < numBytes) {
            let toHash;
            switch (this.type) {
                case 'simple':
                    toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);
                    break;
                case 'salted':
                    toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);
                    break;
                case 'iterated': {
                    const data = util.concatUint8Array([this.salt, passphrase]);
                    let datalen = data.length;
                    const count = Math.max(this.getCount(), datalen);
                    toHash = new Uint8Array(prefixlen + count);
                    toHash.set(data, prefixlen);
                    for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {
                        toHash.copyWithin(pos, prefixlen, pos);
                    }
                    break;
                }
                case 'gnu':
                    throw new Error('GNU s2k type not supported.');
                default:
                    throw new Error('Unknown s2k type.');
            }
            const result = await computeDigest(this.algorithm, toHash);
            arr.push(result);
            rlength += result.length;
            prefixlen++;
        }
        return util.concatUint8Array(arr).subarray(0, numBytes);
    }
}

/**
 * @module type/s2k
 * @access private
 */
const allowedS2KTypesForEncryption = new Set([enums.s2k.argon2, enums.s2k.iterated]);
/**
 * Instantiate a new S2K instance of the given type
 * @param {module:enums.s2k} type
 * @param {Object} [config]
 * @returns {Object} New s2k object
 * @throws {Error} for unknown or unsupported types

 */
function newS2KFromType(type, config$1 = config) {
    switch (type) {
        case enums.s2k.argon2:
            return new Argon2S2K(config$1);
        case enums.s2k.iterated:
        case enums.s2k.gnu:
        case enums.s2k.salted:
        case enums.s2k.simple:
            return new GenericS2K(type, config$1);
        default:
            throw new UnsupportedError('Unsupported S2K type');
    }
}
/**
 * Instantiate a new S2K instance based on the config settings
 * @oaram {Object} config
 * @returns {Object} New s2k object
 * @throws {Error} for unknown or unsupported types
 */
function newS2KFromConfig(config) {
    const { s2kType } = config;
    if (!allowedS2KTypesForEncryption.has(s2kType)) {
        throw new Error('The provided `config.s2kType` value is not allowed');
    }
    return newS2KFromType(s2kType, config);
}

var require$1 = createRequire('/');
// DEFLATE is a complex format; to read this code, you should probably check the RFC first:
// https://tools.ietf.org/html/rfc1951
// You may also wish to take a look at the guide I made about this program:
// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad
// Some of the following code is similar to that of UZIP.js:
// https://github.com/photopea/UZIP.js
// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.
// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint
// is better for memory in most engines (I *think*).
var _a;
// Mediocre shim
var Worker;
var isMarkedAsUntransferable;
try {
    (_a = require$1('worker_threads'), Worker = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable);
}
catch (e) {
}

// aliases for shorter compressed code (most minifers don't do this)
var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;
// fixed length extra bits
var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);
// fixed distance extra bits
var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);
// code length index map
var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
// get base, reverse index map from extra bits
var freb = function (eb, start) {
    var b = new u16(31);
    for (var i = 0; i < 31; ++i) {
        b[i] = start += 1 << eb[i - 1];
    }
    // numbers here are at max 18 bits
    var r = new i32(b[30]);
    for (var i = 1; i < 30; ++i) {
        for (var j = b[i]; j < b[i + 1]; ++j) {
            r[j] = ((j - b[i]) << 5) | i;
        }
    }
    return { b: b, r: r };
};
var _a = freb(fleb, 2), fl = _a.b, revfl = _a.r;
// we can ignore the fact that the other numbers are wrong; they never happen anyway
fl[28] = 258, revfl[258] = 28;
var _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r;
// map of value to reverse (assuming 16 bits)
var rev = new u16(32768);
for (var i = 0; i < 32768; ++i) {
    // reverse table algorithm from SO
    var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1);
    x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2);
    x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4);
    rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1;
}
// create huffman tree from u8 "map": index -> code length for code index
// mb (max bits) must be at most 15
// TODO: optimize/split up?
var hMap = (function (cd, mb, r) {
    var s = cd.length;
    // index
    var i = 0;
    // u16 "map": index -> # of codes with bit length = index
    var l = new u16(mb);
    // length of cd must be 288 (total # of codes)
    for (; i < s; ++i) {
        if (cd[i])
            ++l[cd[i] - 1];
    }
    // u16 "map": index -> minimum code for bit length = index
    var le = new u16(mb);
    for (i = 1; i < mb; ++i) {
        le[i] = (le[i - 1] + l[i - 1]) << 1;
    }
    var co;
    if (r) {
        // u16 "map": index -> number of actual bits, symbol for code
        co = new u16(1 << mb);
        // bits to remove for reverser
        var rvb = 15 - mb;
        for (i = 0; i < s; ++i) {
            // ignore 0 lengths
            if (cd[i]) {
                // num encoding both symbol and bits read
                var sv = (i << 4) | cd[i];
                // free bits
                var r_1 = mb - cd[i];
                // start value
                var v = le[cd[i] - 1]++ << r_1;
                // m is end value
                for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {
                    // every 16 bit value starting with the code yields the same result
                    co[rev[v] >> rvb] = sv;
                }
            }
        }
    }
    else {
        co = new u16(s);
        for (i = 0; i < s; ++i) {
            if (cd[i]) {
                co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]);
            }
        }
    }
    return co;
});
// fixed length tree
var flt = new u8(288);
for (var i = 0; i < 144; ++i)
    flt[i] = 8;
for (var i = 144; i < 256; ++i)
    flt[i] = 9;
for (var i = 256; i < 280; ++i)
    flt[i] = 7;
for (var i = 280; i < 288; ++i)
    flt[i] = 8;
// fixed distance tree
var fdt = new u8(32);
for (var i = 0; i < 32; ++i)
    fdt[i] = 5;
// fixed length map
var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);
// fixed distance map
var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
// find max of array
var max = function (a) {
    var m = a[0];
    for (var i = 1; i < a.length; ++i) {
        if (a[i] > m)
            m = a[i];
    }
    return m;
};
// read d, starting at bit p and mask with m
var bits = function (d, p, m) {
    var o = (p / 8) | 0;
    return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;
};
// read d, starting at bit p continuing for at least 16 bits
var bits16 = function (d, p) {
    var o = (p / 8) | 0;
    return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));
};
// get end of byte
var shft = function (p) { return ((p + 7) / 8) | 0; };
// typed array slice - allows garbage collector to free original reference,
// while being more compatible than .slice
var slc = function (v, s, e) {
    if (s == null || s < 0)
        s = 0;
    if (e == null || e > v.length)
        e = v.length;
    // can't use .constructor in case user-supplied
    return new u8(v.subarray(s, e));
};
// error codes
var ec = [
    'unexpected EOF',
    'invalid block type',
    'invalid length/literal',
    'invalid distance',
    'stream finished',
    'no stream handler',
    , // determined by compression function
    'no callback',
    'invalid UTF-8 data',
    'extra field too long',
    'date not in range 1980-2099',
    'filename too long',
    'stream finishing',
    'invalid zip data'
    // determined by unknown compression method
];
var err = function (ind, msg, nt) {
    var e = new Error(msg || ec[ind]);
    e.code = ind;
    if (Error.captureStackTrace)
        Error.captureStackTrace(e, err);
    if (!nt)
        throw e;
    return e;
};
// expands raw DEFLATE data
var inflt = function (dat, st, buf, dict) {
    // source length       dict length
    var sl = dat.length, dl = 0;
    if (!sl || st.f && !st.l)
        return buf || new u8(0);
    var noBuf = !buf;
    // have to estimate size
    var resize = noBuf || st.i != 2;
    // no state
    var noSt = st.i;
    // Assumes roughly 33% compression ratio average
    if (noBuf)
        buf = new u8(sl * 3);
    // ensure buffer can fit at least l elements
    var cbuf = function (l) {
        var bl = buf.length;
        // need to increase size to fit
        if (l > bl) {
            // Double or set to necessary, whichever is greater
            var nbuf = new u8(Math.max(bl * 2, l));
            nbuf.set(buf);
            buf = nbuf;
        }
    };
    //  last chunk         bitpos           bytes
    var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
    // total bits
    var tbts = sl * 8;
    do {
        if (!lm) {
            // BFINAL - this is only 1 when last chunk is next
            final = bits(dat, pos, 1);
            // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman
            var type = bits(dat, pos + 1, 3);
            pos += 3;
            if (!type) {
                // go to end of byte boundary
                var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;
                if (t > sl) {
                    if (noSt)
                        err(0);
                    break;
                }
                // ensure size
                if (resize)
                    cbuf(bt + l);
                // Copy over uncompressed data
                buf.set(dat.subarray(s, t), bt);
                // Get new bitpos, update byte count
                st.b = bt += l, st.p = pos = t * 8, st.f = final;
                continue;
            }
            else if (type == 1)
                lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
            else if (type == 2) {
                //  literal                            lengths
                var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
                var tl = hLit + bits(dat, pos + 5, 31) + 1;
                pos += 14;
                // length+distance tree
                var ldt = new u8(tl);
                // code length tree
                var clt = new u8(19);
                for (var i = 0; i < hcLen; ++i) {
                    // use index map to get real code
                    clt[clim[i]] = bits(dat, pos + i * 3, 7);
                }
                pos += hcLen * 3;
                // code lengths bits
                var clb = max(clt), clbmsk = (1 << clb) - 1;
                // code lengths map
                var clm = hMap(clt, clb, 1);
                for (var i = 0; i < tl;) {
                    var r = clm[bits(dat, pos, clbmsk)];
                    // bits read
                    pos += r & 15;
                    // symbol
                    var s = r >> 4;
                    // code length to copy
                    if (s < 16) {
                        ldt[i++] = s;
                    }
                    else {
                        //  copy   count
                        var c = 0, n = 0;
                        if (s == 16)
                            n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
                        else if (s == 17)
                            n = 3 + bits(dat, pos, 7), pos += 3;
                        else if (s == 18)
                            n = 11 + bits(dat, pos, 127), pos += 7;
                        while (n--)
                            ldt[i++] = c;
                    }
                }
                //    length tree                 distance tree
                var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
                // max length bits
                lbt = max(lt);
                // max dist bits
                dbt = max(dt);
                lm = hMap(lt, lbt, 1);
                dm = hMap(dt, dbt, 1);
            }
            else
                err(1);
            if (pos > tbts) {
                if (noSt)
                    err(0);
                break;
            }
        }
        // Make sure the buffer can hold this + the largest possible addition
        // Maximum chunk size (practically, theoretically infinite) is 2^17
        if (resize)
            cbuf(bt + 131072);
        var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
        var lpos = pos;
        for (;; lpos = pos) {
            // bits read, code
            var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
            pos += c & 15;
            if (pos > tbts) {
                if (noSt)
                    err(0);
                break;
            }
            if (!c)
                err(2);
            if (sym < 256)
                buf[bt++] = sym;
            else if (sym == 256) {
                lpos = pos, lm = null;
                break;
            }
            else {
                var add = sym - 254;
                // no extra bits needed if less
                if (sym > 264) {
                    // index
                    var i = sym - 257, b = fleb[i];
                    add = bits(dat, pos, (1 << b) - 1) + fl[i];
                    pos += b;
                }
                // dist
                var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
                if (!d)
                    err(3);
                pos += d & 15;
                var dt = fd[dsym];
                if (dsym > 3) {
                    var b = fdeb[dsym];
                    dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
                }
                if (pos > tbts) {
                    if (noSt)
                        err(0);
                    break;
                }
                if (resize)
                    cbuf(bt + 131072);
                var end = bt + add;
                if (bt < dt) {
                    var shift = dl - dt, dend = Math.min(dt, end);
                    if (shift + bt < 0)
                        err(3);
                    for (; bt < dend; ++bt)
                        buf[bt] = dict[shift + bt];
                }
                for (; bt < end; ++bt)
                    buf[bt] = buf[bt - dt];
            }
        }
        st.l = lm, st.p = lpos, st.b = bt, st.f = final;
        if (lm)
            final = 1, st.m = lbt, st.d = dm, st.n = dbt;
    } while (!final);
    // don't reallocate for streams or user buffers
    return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
};
// starting at p, write the minimum number of bits that can hold v to d
var wbits = function (d, p, v) {
    v <<= p & 7;
    var o = (p / 8) | 0;
    d[o] |= v;
    d[o + 1] |= v >> 8;
};
// starting at p, write the minimum number of bits (>8) that can hold v to d
var wbits16 = function (d, p, v) {
    v <<= p & 7;
    var o = (p / 8) | 0;
    d[o] |= v;
    d[o + 1] |= v >> 8;
    d[o + 2] |= v >> 16;
};
// creates code lengths from a frequency table
var hTree = function (d, mb) {
    // Need extra info to make a tree
    var t = [];
    for (var i = 0; i < d.length; ++i) {
        if (d[i])
            t.push({ s: i, f: d[i] });
    }
    var s = t.length;
    var t2 = t.slice();
    if (!s)
        return { t: et, l: 0 };
    if (s == 1) {
        var v = new u8(t[0].s + 1);
        v[t[0].s] = 1;
        return { t: v, l: 1 };
    }
    t.sort(function (a, b) { return a.f - b.f; });
    // after i2 reaches last ind, will be stopped
    // freq must be greater than largest possible number of symbols
    t.push({ s: -1, f: 25001 });
    var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;
    t[0] = { s: -1, f: l.f + r.f, l: l, r: r };
    // efficient algorithm from UZIP.js
    // i0 is lookbehind, i2 is lookahead - after processing two low-freq
    // symbols that combined have high freq, will start processing i2 (high-freq,
    // non-composite) symbols instead
    // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/
    while (i1 != s - 1) {
        l = t[t[i0].f < t[i2].f ? i0++ : i2++];
        r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
        t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };
    }
    var maxSym = t2[0].s;
    for (var i = 1; i < s; ++i) {
        if (t2[i].s > maxSym)
            maxSym = t2[i].s;
    }
    // code lengths
    var tr = new u16(maxSym + 1);
    // max bits in tree
    var mbt = ln(t[i1 - 1], tr, 0);
    if (mbt > mb) {
        // more algorithms from UZIP.js
        // TODO: find out how this code works (debt)
        //  ind    debt
        var i = 0, dt = 0;
        //    left            cost
        var lft = mbt - mb, cst = 1 << lft;
        t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });
        for (; i < s; ++i) {
            var i2_1 = t2[i].s;
            if (tr[i2_1] > mb) {
                dt += cst - (1 << (mbt - tr[i2_1]));
                tr[i2_1] = mb;
            }
            else
                break;
        }
        dt >>= lft;
        while (dt > 0) {
            var i2_2 = t2[i].s;
            if (tr[i2_2] < mb)
                dt -= 1 << (mb - tr[i2_2]++ - 1);
            else
                ++i;
        }
        for (; i >= 0 && dt; --i) {
            var i2_3 = t2[i].s;
            if (tr[i2_3] == mb) {
                --tr[i2_3];
                ++dt;
            }
        }
        mbt = mb;
    }
    return { t: new u8(tr), l: mbt };
};
// get the max length and assign length codes
var ln = function (n, l, d) {
    return n.s == -1
        ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))
        : (l[n.s] = d);
};
// length codes generation
var lc = function (c) {
    var s = c.length;
    // Note that the semicolon was intentional
    while (s && !c[--s])
        ;
    var cl = new u16(++s);
    //  ind      num         streak
    var cli = 0, cln = c[0], cls = 1;
    var w = function (v) { cl[cli++] = v; };
    for (var i = 1; i <= s; ++i) {
        if (c[i] == cln && i != s)
            ++cls;
        else {
            if (!cln && cls > 2) {
                for (; cls > 138; cls -= 138)
                    w(32754);
                if (cls > 2) {
                    w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);
                    cls = 0;
                }
            }
            else if (cls > 3) {
                w(cln), --cls;
                for (; cls > 6; cls -= 6)
                    w(8304);
                if (cls > 2)
                    w(((cls - 3) << 5) | 8208), cls = 0;
            }
            while (cls--)
                w(cln);
            cls = 1;
            cln = c[i];
        }
    }
    return { c: cl.subarray(0, cli), n: s };
};
// calculate the length of output from tree, code lengths
var clen = function (cf, cl) {
    var l = 0;
    for (var i = 0; i < cl.length; ++i)
        l += cf[i] * cl[i];
    return l;
};
// writes a fixed block
// returns the new bit pos
var wfblk = function (out, pos, dat) {
    // no need to write 00 as type: TypedArray defaults to 0
    var s = dat.length;
    var o = shft(pos + 2);
    out[o] = s & 255;
    out[o + 1] = s >> 8;
    out[o + 2] = out[o] ^ 255;
    out[o + 3] = out[o + 1] ^ 255;
    for (var i = 0; i < s; ++i)
        out[o + i + 4] = dat[i];
    return (o + 4 + s) * 8;
};
// writes a block
var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
    wbits(out, p++, final);
    ++lf[256];
    var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l;
    var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l;
    var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
    var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
    var lcfreq = new u16(19);
    for (var i = 0; i < lclt.length; ++i)
        ++lcfreq[lclt[i] & 31];
    for (var i = 0; i < lcdt.length; ++i)
        ++lcfreq[lcdt[i] & 31];
    var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
    var nlcc = 19;
    for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
        ;
    var flen = (bl + 5) << 3;
    var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
    var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
    if (bs >= 0 && flen <= ftlen && flen <= dtlen)
        return wfblk(out, p, dat.subarray(bs, bs + bl));
    var lm, ll, dm, dl;
    wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
    if (dtlen < ftlen) {
        lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
        var llm = hMap(lct, mlcb, 0);
        wbits(out, p, nlc - 257);
        wbits(out, p + 5, ndc - 1);
        wbits(out, p + 10, nlcc - 4);
        p += 14;
        for (var i = 0; i < nlcc; ++i)
            wbits(out, p + 3 * i, lct[clim[i]]);
        p += 3 * nlcc;
        var lcts = [lclt, lcdt];
        for (var it = 0; it < 2; ++it) {
            var clct = lcts[it];
            for (var i = 0; i < clct.length; ++i) {
                var len = clct[i] & 31;
                wbits(out, p, llm[len]), p += lct[len];
                if (len > 15)
                    wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12;
            }
        }
    }
    else {
        lm = flm, ll = flt, dm = fdm, dl = fdt;
    }
    for (var i = 0; i < li; ++i) {
        var sym = syms[i];
        if (sym > 255) {
            var len = (sym >> 18) & 31;
            wbits16(out, p, lm[len + 257]), p += ll[len + 257];
            if (len > 7)
                wbits(out, p, (sym >> 23) & 31), p += fleb[len];
            var dst = sym & 31;
            wbits16(out, p, dm[dst]), p += dl[dst];
            if (dst > 3)
                wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst];
        }
        else {
            wbits16(out, p, lm[sym]), p += ll[sym];
        }
    }
    wbits16(out, p, lm[256]);
    return p + ll[256];
};
// deflate options (nice << 13) | chain
var deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
// empty
var et = /*#__PURE__*/ new u8(0);
// compresses data into a raw DEFLATE buffer
var dflt = function (dat, lvl, plvl, pre, post, st) {
    var s = st.z || dat.length;
    var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);
    // writing to this writes to the output buffer
    var w = o.subarray(pre, o.length - post);
    var lst = st.l;
    var pos = (st.r || 0) & 7;
    if (lvl) {
        if (pos)
            w[0] = st.r >> 3;
        var opt = deo[lvl - 1];
        var n = opt >> 13, c = opt & 8191;
        var msk_1 = (1 << plvl) - 1;
        //    prev 2-byte val map    curr 2-byte val map
        var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
        var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
        var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };
        // 24576 is an arbitrary number of maximum symbols per block
        // 424 buffer for last block
        var syms = new i32(25000);
        // length/literal freq   distance freq
        var lf = new u16(288), df = new u16(32);
        //  l/lcnt  exbits  index          l/lind  waitdx          blkpos
        var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
        for (; i + 2 < s; ++i) {
            // hash value
            var hv = hsh(i);
            // index mod 32768    previous index mod
            var imod = i & 32767, pimod = head[hv];
            prev[imod] = pimod;
            head[hv] = imod;
            // We always should modify head and prev, but only add symbols if
            // this data is not yet processed ("wait" for wait index)
            if (wi <= i) {
                // bytes remaining
                var rem = s - i;
                if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {
                    pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
                    li = lc_1 = eb = 0, bs = i;
                    for (var j = 0; j < 286; ++j)
                        lf[j] = 0;
                    for (var j = 0; j < 30; ++j)
                        df[j] = 0;
                }
                //  len    dist   chain
                var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
                if (rem > 2 && hv == hsh(i - dif)) {
                    var maxn = Math.min(n, rem) - 1;
                    var maxd = Math.min(32767, i);
                    // max possible length
                    // not capped at dif because decompressors implement "rolling" index population
                    var ml = Math.min(258, rem);
                    while (dif <= maxd && --ch_1 && imod != pimod) {
                        if (dat[i + l] == dat[i + l - dif]) {
                            var nl = 0;
                            for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)
                                ;
                            if (nl > l) {
                                l = nl, d = dif;
                                // break out early when we reach "nice" (we are satisfied enough)
                                if (nl > maxn)
                                    break;
                                // now, find the rarest 2-byte sequence within this
                                // length of literals and search for that instead.
                                // Much faster than just using the start
                                var mmd = Math.min(dif, nl - 2);
                                var md = 0;
                                for (var j = 0; j < mmd; ++j) {
                                    var ti = i - dif + j & 32767;
                                    var pti = prev[ti];
                                    var cd = ti - pti & 32767;
                                    if (cd > md)
                                        md = cd, pimod = ti;
                                }
                            }
                        }
                        // check the previous match
                        imod = pimod, pimod = prev[imod];
                        dif += imod - pimod & 32767;
                    }
                }
                // d will be nonzero only when a match was found
                if (d) {
                    // store both dist and len data in one int32
                    // Make sure this is recognized as a len/dist with 28th bit (2^28)
                    syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];
                    var lin = revfl[l] & 31, din = revfd[d] & 31;
                    eb += fleb[lin] + fdeb[din];
                    ++lf[257 + lin];
                    ++df[din];
                    wi = i + l;
                    ++lc_1;
                }
                else {
                    syms[li++] = dat[i];
                    ++lf[dat[i]];
                }
            }
        }
        for (i = Math.max(i, wi); i < s; ++i) {
            syms[li++] = dat[i];
            ++lf[dat[i]];
        }
        pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
        if (!lst) {
            st.r = (pos & 7) | w[(pos / 8) | 0] << 3;
            // shft(pos) now 1 less if pos & 7 != 0
            pos -= 7;
            st.h = head, st.p = prev, st.i = i, st.w = wi;
        }
    }
    else {
        for (var i = st.w || 0; i < s + lst; i += 65535) {
            // end
            var e = i + 65535;
            if (e >= s) {
                // write final block
                w[(pos / 8) | 0] = lst;
                e = s;
            }
            pos = wfblk(w, pos + 1, dat.subarray(i, e));
        }
        st.i = s;
    }
    return slc(o, 0, pre + shft(pos) + post);
};
// Adler32
var adler = function () {
    var a = 1, b = 0;
    return {
        p: function (d) {
            // closures have awful performance
            var n = a, m = b;
            var l = d.length | 0;
            for (var i = 0; i != l;) {
                var e = Math.min(i + 2655, l);
                for (; i < e; ++i)
                    m += n += d[i];
                n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);
            }
            a = n, b = m;
        },
        d: function () {
            a %= 65521, b %= 65521;
            return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8);
        }
    };
};
// deflate with opts
var dopt = function (dat, opt, pre, post, st) {
    if (!st) {
        st = { l: 1 };
        if (opt.dictionary) {
            var dict = opt.dictionary.subarray(-32768);
            var newDat = new u8(dict.length + dat.length);
            newDat.set(dict);
            newDat.set(dat, dict.length);
            dat = newDat;
            st.w = dict.length;
        }
    }
    return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st);
};
// write bytes
var wbytes = function (d, b, v) {
    for (; v; ++b)
        d[b] = v, v >>>= 8;
};
// zlib header
var zlh = function (c, o) {
    var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
    c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32);
    c[1] |= 31 - ((c[0] << 8) | c[1]) % 31;
    if (o.dictionary) {
        var h = adler();
        h.p(o.dictionary);
        wbytes(c, 2, h.d());
    }
};
// zlib start
var zls = function (d, dict) {
    if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31))
        err(6, 'invalid zlib data');
    if ((d[1] >> 5 & 1) == +!dict)
        err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary');
    return (d[1] >> 3 & 4) + 2;
};
/**
 * Streaming DEFLATE compression
 */
var Deflate = /*#__PURE__*/ (function () {
    function Deflate(opts, cb) {
        if (typeof opts == 'function')
            cb = opts, opts = {};
        this.ondata = cb;
        this.o = opts || {};
        this.s = { l: 0, i: 32768, w: 32768, z: 32768 };
        // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev
        // 98304 = 32768 (lookback) + 65536 (common chunk size)
        this.b = new u8(98304);
        if (this.o.dictionary) {
            var dict = this.o.dictionary.subarray(-32768);
            this.b.set(dict, 32768 - dict.length);
            this.s.i = 32768 - dict.length;
        }
    }
    Deflate.prototype.p = function (c, f) {
        this.ondata(dopt(c, this.o, 0, 0, this.s), f);
    };
    /**
     * Pushes a chunk to be deflated
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    Deflate.prototype.push = function (chunk, final) {
        if (!this.ondata)
            err(5);
        if (this.s.l)
            err(4);
        var endLen = chunk.length + this.s.z;
        if (endLen > this.b.length) {
            if (endLen > 2 * this.b.length - 32768) {
                var newBuf = new u8(endLen & -32768);
                newBuf.set(this.b.subarray(0, this.s.z));
                this.b = newBuf;
            }
            var split = this.b.length - this.s.z;
            this.b.set(chunk.subarray(0, split), this.s.z);
            this.s.z = this.b.length;
            this.p(this.b, false);
            this.b.set(this.b.subarray(-32768));
            this.b.set(chunk.subarray(split), 32768);
            this.s.z = chunk.length - split + 32768;
            this.s.i = 32766, this.s.w = 32768;
        }
        else {
            this.b.set(chunk, this.s.z);
            this.s.z += chunk.length;
        }
        this.s.l = final & 1;
        if (this.s.z > this.s.w + 8191 || final) {
            this.p(this.b, final || false);
            this.s.w = this.s.i, this.s.i -= 2;
        }
        if (final) {
            // cleanup unneeded buffers/state to reduce memory usage
            this.s = this.o = {};
            this.b = et;
        }
    };
    /**
     * Flushes buffered uncompressed data. Useful to immediately retrieve the
     * deflated output for small inputs.
     * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5
     *             extra bytes, but guarantees all pushed data is immediately
     *             decompressible. A separate DEFLATE stream may be concatenated
     *             with the current output after a sync flush.
     */
    Deflate.prototype.flush = function (sync) {
        if (!this.ondata)
            err(5);
        if (this.s.l)
            err(4);
        this.p(this.b, false);
        this.s.w = this.s.i, this.s.i -= 2;
        // could technically skip writing the type-0 block for (this.s.r & 7) == 0,
        // but the deterministic trailer (00 00 FF FF) is useful in some situations
        if (sync) {
            var c = new u8(6);
            c[0] = this.s.r >> 3;
            // write empty, non-final type-0 block
            var ep = wfblk(c, this.s.r, et);
            this.s.r = 0;
            this.ondata(c.subarray(0, ep >> 3), false);
        }
    };
    return Deflate;
}());
/**
 * Streaming DEFLATE decompression
 */
var Inflate = /*#__PURE__*/ (function () {
    function Inflate(opts, cb) {
        // no StrmOpt here to avoid adding to workerizer
        if (typeof opts == 'function')
            cb = opts, opts = {};
        this.ondata = cb;
        var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);
        this.s = { i: 0, b: dict ? dict.length : 0 };
        this.o = new u8(32768);
        this.p = new u8(0);
        if (dict)
            this.o.set(dict);
    }
    Inflate.prototype.e = function (c) {
        if (!this.ondata)
            err(5);
        if (this.d)
            err(4);
        if (!this.p.length)
            this.p = c;
        else if (c.length) {
            var n = new u8(this.p.length + c.length);
            n.set(this.p), n.set(c, this.p.length), this.p = n;
        }
    };
    Inflate.prototype.c = function (final) {
        this.s.i = +(this.d = final || false);
        var bts = this.s.b;
        var dt = inflt(this.p, this.s, this.o);
        this.ondata(slc(dt, bts, this.s.b), this.d);
        this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
        this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;
    };
    /**
     * Pushes a chunk to be inflated
     * @param chunk The chunk to push
     * @param final Whether this is the final chunk
     */
    Inflate.prototype.push = function (chunk, final) {
        this.e(chunk), this.c(final);
    };
    return Inflate;
}());
/**
 * Streaming Zlib compression
 */
var Zlib = /*#__PURE__*/ (function () {
    function Zlib(opts, cb) {
        this.c = adler();
        this.v = 1;
        Deflate.call(this, opts, cb);
    }
    /**
     * Pushes a chunk to be zlibbed
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    Zlib.prototype.push = function (chunk, final) {
        this.c.p(chunk);
        Deflate.prototype.push.call(this, chunk, final);
    };
    Zlib.prototype.p = function (c, f) {
        var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s);
        if (this.v)
            zlh(raw, this.o), this.v = 0;
        if (f)
            wbytes(raw, raw.length - 4, this.c.d());
        this.ondata(raw, f);
    };
    /**
     * Flushes buffered uncompressed data. Useful to immediately retrieve the
     * zlibbed output for small inputs.
     * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5
     *             extra bytes, but guarantees all pushed data is immediately
     *             decompressible.
     */
    Zlib.prototype.flush = function (sync) {
        Deflate.prototype.flush.call(this, sync);
    };
    return Zlib;
}());
/**
 * Streaming Zlib decompression
 */
var Unzlib = /*#__PURE__*/ (function () {
    function Unzlib(opts, cb) {
        Inflate.call(this, opts, cb);
        this.v = opts && opts.dictionary ? 2 : 1;
    }
    /**
     * Pushes a chunk to be unzlibbed
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    Unzlib.prototype.push = function (chunk, final) {
        Inflate.prototype.e.call(this, chunk);
        if (this.v) {
            if (this.p.length < 6 && !final)
                return;
            this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0;
        }
        if (final) {
            if (this.p.length < 4)
                err(6, 'invalid zlib data');
            this.p = this.p.subarray(0, -4);
        }
        // necessary to prevent TS from using the closure value
        // This allows for workerization to function correctly
        Inflate.prototype.c.call(this, final);
    };
    return Unzlib;
}());
// text decoder
var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();
// text decoder stream
var tds = 0;
try {
    td.decode(et, { stream: true });
    tds = 1;
}
catch (e) { }

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Implementation of the Literal Data Packet (Tag 11)
 *
 * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:
 * A Literal Data packet contains the body of a message; data that is not to be
 * further interpreted.
 */
class LiteralDataPacket {
    static get tag() {
        return enums.packet.literalData;
    }
    /**
     * @param {Date} date - The creation date of the literal package
     */
    constructor(date = new Date()) {
        this.format = enums.literal.utf8; // default format for literal data packets
        this.date = util.normalizeDate(date);
        this.text = null; // textual data representation
        this.data = null; // literal data representation
        this.filename = '';
    }
    /**
     * Set the packet data to a javascript native string, end of line
     * will be normalized to \r\n and by default text is converted to UTF8
     * @param {String | ReadableStream<String>} text - Any native javascript string
     * @param {enums.literal} [format] - The format of the string of bytes
     */
    setText(text, format = enums.literal.utf8) {
        this.format = format;
        this.text = text;
        this.data = null;
    }
    /**
     * Returns literal data packets as native JavaScript string
     * with normalized end of line to \n
     * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again
     * @returns {String | ReadableStream<String>} Literal data as text.
     */
    getText(clone = false) {
        if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read
            this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));
        }
        return this.text;
    }
    /**
     * Set the packet data to value represented by the provided string of bytes.
     * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - The string of bytes
     * @param {enums.literal} format - The format of the string of bytes
     */
    setBytes(bytes, format) {
        this.format = format;
        this.data = bytes;
        this.text = null;
    }
    /**
     * Get the byte sequence representing the literal packet data
     * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again
     * @returns {Uint8Array | ReadableStream<Uint8Array>} A sequence of bytes.
     */
    getBytes(clone = false) {
        if (this.data === null) {
            // encode UTF8 and normalize EOL to \r\n
            this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));
        }
        if (clone) {
            return passiveClone(this.data);
        }
        return this.data;
    }
    /**
     * Sets the filename of the literal packet data
     * @param {String} filename - Any native javascript string
     */
    setFilename(filename) {
        this.filename = filename;
    }
    /**
     * Get the filename of the literal packet data
     * @returns {String} Filename.
     */
    getFilename() {
        return this.filename;
    }
    /**
     * Parsing function for a literal data packet (tag 11).
     *
     * @param {Uint8Array | ReadableStream<Uint8Array>} input - Payload of a tag 11 packet
     * @returns {Promise<LiteralDataPacket>} Object representation.
     * @async
     */
    async read(bytes) {
        await parse(bytes, async (reader) => {
            // - A one-octet field that describes how the data is formatted.
            const format = await reader.readByte(); // enums.literal
            const filename_len = await reader.readByte();
            this.filename = util.decodeUTF8(await reader.readBytes(filename_len));
            this.date = util.readDate(await reader.readBytes(4));
            let data = reader.remainder();
            if (isArrayStream(data))
                data = await readToEnd(data);
            this.setBytes(data, format);
        });
    }
    /**
     * Creates a Uint8Array representation of the packet, excluding the data
     *
     * @returns {Uint8Array} Uint8Array representation of the packet.
     */
    writeHeader() {
        const filename = util.encodeUTF8(this.filename);
        const filename_length = new Uint8Array([filename.length]);
        const format = new Uint8Array([this.format]);
        const date = util.writeDate(this.date);
        return util.concatUint8Array([format, filename_length, filename, date]);
    }
    /**
     * Creates a Uint8Array representation of the packet
     *
     * @returns {Uint8Array | ReadableStream<Uint8Array>} Uint8Array representation of the packet.
     */
    write() {
        const header = this.writeHeader();
        const data = this.getBytes();
        return util.concat([header, data]);
    }
}

/** @access private */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Implementation of type key id
 *
 * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:
 * A Key ID is an eight-octet scalar that identifies a key.
 * Implementations SHOULD NOT assume that Key IDs are unique.  The
 * section "Enhanced Key Formats" below describes how Key IDs are
 * formed.
 * @access private
 */
class KeyID {
    constructor() {
        this.bytes = '';
    }
    /**
     * Parsing method for a key id
     * @param {Uint8Array} bytes - Input to read the key id from
     */
    read(bytes) {
        this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));
        return this.bytes.length;
    }
    /**
     * Serializes the Key ID
     * @returns {Uint8Array} Key ID as a Uint8Array.
     */
    write() {
        return util.stringToUint8Array(this.bytes);
    }
    /**
     * Returns the Key ID represented as a hexadecimal string
     * @returns {String} Key ID as a hexadecimal string.
     */
    toHex() {
        return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));
    }
    /**
     * Checks equality of Key ID's
     * @param {KeyID} keyID
     * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard
     */
    equals(keyID, matchWildcard = false) {
        return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;
    }
    /**
     * Checks to see if the Key ID is unset
     * @returns {Boolean} True if the Key ID is null.
     */
    isNull() {
        return this.bytes === '';
    }
    /**
     * Checks to see if the Key ID is a "wildcard" Key ID (all zeros)
     * @returns {Boolean} True if this is a wildcard Key ID.
     */
    isWildcard() {
        return /^0+$/.test(this.toHex());
    }
    static mapToHex(keyID) {
        return keyID.toHex();
    }
    static fromID(hex) {
        const keyID = new KeyID();
        keyID.read(util.hexToUint8Array(hex));
        return keyID;
    }
    static wildcard() {
        const keyID = new KeyID();
        keyID.read(new Uint8Array(8));
        return keyID;
    }
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.
const verified = Symbol('verified');
// A salt notation is used to randomize signatures.
// This is to protect EdDSA signatures in particular, which are known to be vulnerable to fault attacks
// leading to secret key extraction if two signatures over the same data can be collected (see https://github.com/jedisct1/libsodium/issues/170).
// For simplicity, we add the salt to all algos, as it may also serve as protection in case of weaknesses in the hash algo, potentially hindering e.g.
// some chosen-prefix attacks.
// v6 signatures do not need to rely on this notation, as they already include a separate, built-in salt.
const SALT_NOTATION_NAME = 'salt@notations.openpgpjs.org';
// GPG puts the Issuer and Signature subpackets in the unhashed area.
// Tampering with those invalidates the signature, so we still trust them and parse them.
// All other unhashed subpackets are ignored.
const allowedUnhashedSubpackets = new Set([
    enums.signatureSubpacket.issuerKeyID,
    enums.signatureSubpacket.issuerFingerprint,
    enums.signatureSubpacket.embeddedSignature
]);
/**
 * Implementation of the Signature Packet (Tag 2)
 *
 * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:
 * A Signature packet describes a binding between some public key and
 * some data.  The most common signatures are a signature of a file or a
 * block of text, and a signature that is a certification of a User ID.
 */
class SignaturePacket {
    static get tag() {
        return enums.packet.signature;
    }
    constructor() {
        this.version = null;
        /** @type {enums.signature} */
        this.signatureType = null;
        /** @type {enums.hash} */
        this.hashAlgorithm = null;
        /** @type {enums.publicKey} */
        this.publicKeyAlgorithm = null;
        this.signatureData = null;
        this.unhashedSubpackets = [];
        this.unknownSubpackets = [];
        this.signedHashValue = null;
        this.salt = null;
        this.created = null;
        this.signatureExpirationTime = null;
        this.signatureNeverExpires = true;
        this.exportable = null;
        this.trustLevel = null;
        this.trustAmount = null;
        this.regularExpression = null;
        this.revocable = null;
        this.keyExpirationTime = null;
        this.keyNeverExpires = null;
        this.preferredSymmetricAlgorithms = null;
        this.revocationKeyClass = null;
        this.revocationKeyAlgorithm = null;
        this.revocationKeyFingerprint = null;
        this.issuerKeyID = new KeyID();
        this.rawNotations = [];
        this.notations = {};
        this.preferredHashAlgorithms = null;
        this.preferredCompressionAlgorithms = null;
        this.keyServerPreferences = null;
        this.preferredKeyServer = null;
        this.isPrimaryUserID = null;
        this.policyURI = null;
        this.keyFlags = null;
        this.signersUserID = null;
        this.reasonForRevocationFlag = null;
        /** @type {String | null} */
        this.reasonForRevocationString = null;
        this.features = null;
        this.signatureTargetPublicKeyAlgorithm = null;
        this.signatureTargetHashAlgorithm = null;
        this.signatureTargetHash = null;
        this.embeddedSignature = null;
        this.issuerKeyVersion = null;
        this.issuerFingerprint = null;
        this.preferredAEADAlgorithms = null;
        this.preferredCipherSuites = null;
        this.revoked = null;
        this[verified] = null;
    }
    /**
     * parsing function for a signature packet (tag 2).
     * @param {String} bytes - Payload of a tag 2 packet
     * @returns {SignaturePacket} Object representation.
     */
    read(bytes, config$1 = config) {
        let i = 0;
        this.version = bytes[i++];
        if (this.version === 5 && !config$1.enableParsingV5Entities) {
            throw new UnsupportedError('Support for v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed');
        }
        if (this.version !== 4 && this.version !== 5 && this.version !== 6) {
            throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);
        }
        this.signatureType = bytes[i++];
        this.publicKeyAlgorithm = bytes[i++];
        this.hashAlgorithm = bytes[i++];
        // hashed subpackets
        i += this.readSubPackets(bytes.subarray(i, bytes.length), true);
        if (!this.created) {
            throw new Error('Missing signature creation time subpacket.');
        }
        // A V4 signature hashes the packet body
        // starting from its first field, the version number, through the end
        // of the hashed subpacket data.  Thus, the fields hashed are the
        // signature version, the signature type, the public-key algorithm, the
        // hash algorithm, the hashed subpacket length, and the hashed
        // subpacket body.
        this.signatureData = bytes.subarray(0, i);
        // unhashed subpackets
        i += this.readSubPackets(bytes.subarray(i, bytes.length), false);
        // Two-octet field holding left 16 bits of signed hash value.
        this.signedHashValue = bytes.subarray(i, i + 2);
        i += 2;
        // Only for v6 signatures, a variable-length field containing:
        if (this.version === 6) {
            // A one-octet salt size. The value MUST match the value defined
            // for the hash algorithm as specified in Table 23 (Hash algorithm registry).
            // To allow parsing unknown hash algos, we only check the expected salt length when verifying.
            const saltLength = bytes[i++];
            // The salt; a random value value of the specified size.
            this.salt = bytes.subarray(i, i + saltLength);
            i += saltLength;
        }
        const signatureMaterial = bytes.subarray(i, bytes.length);
        const { read, signatureParams } = parseSignatureParams(this.publicKeyAlgorithm, signatureMaterial);
        if (read < signatureMaterial.length) {
            throw new Error('Error reading MPIs');
        }
        this.params = signatureParams;
    }
    /**
     * @returns {Uint8Array | ReadableStream<Uint8Array>}
     */
    writeParams() {
        if (this.params instanceof Promise) {
            return fromAsync(async () => serializeParams(this.publicKeyAlgorithm, await this.params));
        }
        return serializeParams(this.publicKeyAlgorithm, this.params);
    }
    write() {
        const arr = [];
        arr.push(this.signatureData);
        arr.push(this.writeUnhashedSubPackets());
        arr.push(this.signedHashValue);
        if (this.version === 6) {
            arr.push(new Uint8Array([this.salt.length]));
            arr.push(this.salt);
        }
        arr.push(this.writeParams());
        return util.concat(arr);
    }
    /**
     * Signs provided data. This needs to be done prior to serialization.
     * @param {SecretKeyPacket} key - Private key used to sign the message.
     * @param {Object} data - Contains packets to be signed.
     * @param {Date} [date] - The signature creation time.
     * @param {Boolean} [detached] - Whether to create a detached signature
     * @throws {Error} if signing failed
     * @async
     */
    async sign(key, data, date = new Date(), detached = false, config) {
        this.version = key.version;
        this.created = util.normalizeDate(date);
        this.issuerKeyVersion = key.version;
        this.issuerFingerprint = key.getFingerprintBytes();
        this.issuerKeyID = key.getKeyID();
        const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])];
        // add randomness to the signature
        if (this.version === 6) {
            const saltLength = saltLengthForHash(this.hashAlgorithm);
            if (this.salt === null) {
                this.salt = getRandomBytes(saltLength);
            }
            else if (saltLength !== this.salt.length) {
                throw new Error('Provided salt does not have the required length');
            }
        }
        else if (config.nonDeterministicSignaturesViaNotation) {
            const saltNotations = this.rawNotations.filter(({ name }) => (name === SALT_NOTATION_NAME));
            // since re-signing the same object is not supported, it's not expected to have multiple salt notations,
            // but we guard against it as a sanity check
            if (saltNotations.length === 0) {
                const saltValue = getRandomBytes(saltLengthForHash(this.hashAlgorithm));
                this.rawNotations.push({
                    name: SALT_NOTATION_NAME,
                    value: saltValue,
                    humanReadable: false,
                    critical: false
                });
            }
            else {
                throw new Error('Unexpected existing salt notation');
            }
        }
        // Add hashed subpackets
        arr.push(this.writeHashedSubPackets());
        // Remove unhashed subpackets, in case some allowed unhashed
        // subpackets existed, in order not to duplicate them (in both
        // the hashed and unhashed subpackets) when re-signing.
        this.unhashedSubpackets = [];
        this.signatureData = util.concat(arr);
        const toHash = this.toHash(this.signatureType, data, detached);
        const hash = await this.hash(this.signatureType, data, toHash, detached);
        this.signedHashValue = slice(clone(hash), 0, 2);
        const signed = async () => sign$1(this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await readToEnd(hash));
        if (util.isStream(hash)) {
            this.params = signed();
        }
        else {
            this.params = await signed();
            // Store the fact that this signature is valid, e.g. for when we call `await
            // getLatestValidSignature(this.revocationSignatures, key, data)` later.
            // Note that this only holds up if the key and data passed to verify are the
            // same as the ones passed to sign.
            this[verified] = true;
        }
    }
    /**
     * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets
     * @returns {Uint8Array} Subpacket data.
     */
    writeHashedSubPackets() {
        const sub = enums.signatureSubpacket;
        const arr = [];
        let bytes;
        if (this.created === null) {
            throw new Error('Missing signature creation time');
        }
        arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created)));
        if (this.signatureExpirationTime !== null) {
            arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4)));
        }
        if (this.exportable !== null) {
            arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0])));
        }
        if (this.trustLevel !== null) {
            bytes = new Uint8Array([this.trustLevel, this.trustAmount]);
            arr.push(writeSubPacket(sub.trustSignature, true, bytes));
        }
        if (this.regularExpression !== null) {
            arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression));
        }
        if (this.revocable !== null) {
            arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0])));
        }
        if (this.keyExpirationTime !== null) {
            arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4)));
        }
        if (this.preferredSymmetricAlgorithms !== null) {
            bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));
            arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes));
        }
        if (this.revocationKeyClass !== null) {
            bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);
            bytes = util.concat([bytes, this.revocationKeyFingerprint]);
            arr.push(writeSubPacket(sub.revocationKey, false, bytes));
        }
        if (!this.issuerKeyID.isNull() && this.issuerKeyVersion < 5) {
            // If the version of [the] key is greater than 4, this subpacket
            // MUST NOT be included in the signature.
            // Note: making this critical breaks RPM <=4.16.
            // See: https://github.com/ProtonMail/go-crypto/issues/263
            arr.push(writeSubPacket(sub.issuerKeyID, false, this.issuerKeyID.write()));
        }
        this.rawNotations.forEach(({ name, value, humanReadable, critical }) => {
            bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];
            const encodedName = util.encodeUTF8(name);
            // 2 octets of name length
            bytes.push(util.writeNumber(encodedName.length, 2));
            // 2 octets of value length
            bytes.push(util.writeNumber(value.length, 2));
            bytes.push(encodedName);
            bytes.push(value);
            bytes = util.concat(bytes);
            arr.push(writeSubPacket(sub.notationData, critical, bytes));
        });
        if (this.preferredHashAlgorithms !== null) {
            bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));
            arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes));
        }
        if (this.preferredCompressionAlgorithms !== null) {
            bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));
            arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes));
        }
        if (this.keyServerPreferences !== null) {
            bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));
            arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes));
        }
        if (this.preferredKeyServer !== null) {
            arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer)));
        }
        if (this.isPrimaryUserID !== null) {
            arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));
        }
        if (this.policyURI !== null) {
            arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI)));
        }
        if (this.keyFlags !== null) {
            bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));
            arr.push(writeSubPacket(sub.keyFlags, true, bytes));
        }
        if (this.signersUserID !== null) {
            arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID)));
        }
        if (this.reasonForRevocationFlag !== null) {
            bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);
            arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes));
        }
        if (this.features !== null) {
            bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));
            arr.push(writeSubPacket(sub.features, false, bytes));
        }
        if (this.signatureTargetPublicKeyAlgorithm !== null) {
            bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];
            bytes.push(util.stringToUint8Array(this.signatureTargetHash));
            bytes = util.concat(bytes);
            arr.push(writeSubPacket(sub.signatureTarget, true, bytes));
        }
        if (this.embeddedSignature !== null) {
            arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write()));
        }
        if (this.issuerFingerprint !== null) {
            bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];
            bytes = util.concat(bytes);
            arr.push(writeSubPacket(sub.issuerFingerprint, this.version >= 5, bytes));
        }
        if (this.preferredAEADAlgorithms !== null) {
            bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));
            arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes));
        }
        if (this.preferredCipherSuites !== null) {
            bytes = new Uint8Array([].concat(...this.preferredCipherSuites));
            arr.push(writeSubPacket(sub.preferredCipherSuites, false, bytes));
        }
        const result = util.concat(arr);
        const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2);
        return util.concat([length, result]);
    }
    /**
     * Creates an Uint8Array containing the unhashed subpackets
     * @returns {Uint8Array} Subpacket data.
     */
    writeUnhashedSubPackets() {
        const arr = this.unhashedSubpackets.map(({ type, critical, body }) => {
            return writeSubPacket(type, critical, body);
        });
        const result = util.concat(arr);
        const length = util.writeNumber(result.length, this.version === 6 ? 4 : 2);
        return util.concat([length, result]);
    }
    // Signature subpackets
    readSubPacket(bytes, hashed = true) {
        let mypos = 0;
        // The leftmost bit denotes a "critical" packet
        const critical = !!(bytes[mypos] & 0x80);
        const type = bytes[mypos] & 0x7F;
        mypos++;
        if (!hashed) {
            this.unhashedSubpackets.push({
                type,
                critical,
                body: bytes.subarray(mypos, bytes.length)
            });
            if (!allowedUnhashedSubpackets.has(type)) {
                return;
            }
        }
        // subpacket type
        switch (type) {
            case enums.signatureSubpacket.signatureCreationTime:
                // Signature Creation Time
                this.created = util.readDate(bytes.subarray(mypos, bytes.length));
                break;
            case enums.signatureSubpacket.signatureExpirationTime: {
                // Signature Expiration Time in seconds
                const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));
                this.signatureNeverExpires = seconds === 0;
                this.signatureExpirationTime = seconds;
                break;
            }
            case enums.signatureSubpacket.exportableCertification:
                // Exportable Certification
                this.exportable = bytes[mypos++] === 1;
                break;
            case enums.signatureSubpacket.trustSignature:
                // Trust Signature
                this.trustLevel = bytes[mypos++];
                this.trustAmount = bytes[mypos++];
                break;
            case enums.signatureSubpacket.regularExpression:
                // Regular Expression
                this.regularExpression = bytes[mypos];
                break;
            case enums.signatureSubpacket.revocable:
                // Revocable
                this.revocable = bytes[mypos++] === 1;
                break;
            case enums.signatureSubpacket.keyExpirationTime: {
                // Key Expiration Time in seconds
                const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));
                this.keyExpirationTime = seconds;
                this.keyNeverExpires = seconds === 0;
                break;
            }
            case enums.signatureSubpacket.preferredSymmetricAlgorithms:
                // Preferred Symmetric Algorithms
                this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];
                break;
            case enums.signatureSubpacket.revocationKey:
                // Revocation Key
                // (1 octet of class, 1 octet of public-key algorithm ID, 20
                // octets of
                // fingerprint)
                this.revocationKeyClass = bytes[mypos++];
                this.revocationKeyAlgorithm = bytes[mypos++];
                this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);
                break;
            case enums.signatureSubpacket.issuerKeyID:
                // Issuer
                if (this.version === 4) {
                    this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));
                }
                else if (hashed) {
                    // If the version of the key is greater than 4, this subpacket MUST NOT be included in the signature,
                    // since the Issuer Fingerprint subpacket is to be used instead.
                    // The `issuerKeyID` value will be set when reading the issuerFingerprint packet.
                    // For this reason, if the issuer Key ID packet is present but unhashed, we simply ignore it,
                    // to avoid situations where `.getSigningKeyIDs()` returns a keyID potentially different from the (signed)
                    // issuerFingerprint.
                    // If the packet is hashed, then we reject the signature, to avoid verifying data different from
                    // what was parsed.
                    throw new Error('Unexpected Issuer Key ID subpacket');
                }
                break;
            case enums.signatureSubpacket.notationData: {
                // Notation Data
                const humanReadable = !!(bytes[mypos] & 0x80);
                // We extract key/value tuple from the byte stream.
                mypos += 4;
                const m = util.readNumber(bytes.subarray(mypos, mypos + 2));
                mypos += 2;
                const n = util.readNumber(bytes.subarray(mypos, mypos + 2));
                mypos += 2;
                const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m));
                const value = bytes.subarray(mypos + m, mypos + m + n);
                this.rawNotations.push({ name, humanReadable, value, critical });
                if (humanReadable) {
                    this.notations[name] = util.decodeUTF8(value);
                }
                break;
            }
            case enums.signatureSubpacket.preferredHashAlgorithms:
                // Preferred Hash Algorithms
                this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];
                break;
            case enums.signatureSubpacket.preferredCompressionAlgorithms:
                // Preferred Compression Algorithms
                this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];
                break;
            case enums.signatureSubpacket.keyServerPreferences:
                // Key Server Preferences
                this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];
                break;
            case enums.signatureSubpacket.preferredKeyServer:
                // Preferred Key Server
                this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length));
                break;
            case enums.signatureSubpacket.primaryUserID:
                // Primary User ID
                this.isPrimaryUserID = bytes[mypos++] !== 0;
                break;
            case enums.signatureSubpacket.policyURI:
                // Policy URI
                this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length));
                break;
            case enums.signatureSubpacket.keyFlags:
                // Key Flags
                this.keyFlags = [...bytes.subarray(mypos, bytes.length)];
                break;
            case enums.signatureSubpacket.signersUserID:
                // Signer's User ID
                this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length));
                break;
            case enums.signatureSubpacket.reasonForRevocation:
                // Reason for Revocation
                this.reasonForRevocationFlag = bytes[mypos++];
                this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length));
                break;
            case enums.signatureSubpacket.features:
                // Features
                this.features = [...bytes.subarray(mypos, bytes.length)];
                break;
            case enums.signatureSubpacket.signatureTarget: {
                // Signature Target
                // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)
                this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];
                this.signatureTargetHashAlgorithm = bytes[mypos++];
                const len = getHashByteLength(this.signatureTargetHashAlgorithm);
                this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));
                break;
            }
            case enums.signatureSubpacket.embeddedSignature:
                // Embedded Signature
                this.embeddedSignature = new SignaturePacket();
                this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));
                break;
            case enums.signatureSubpacket.issuerFingerprint:
                // Issuer Fingerprint
                this.issuerKeyVersion = bytes[mypos++];
                this.issuerFingerprint = bytes.subarray(mypos, bytes.length);
                if (this.issuerKeyVersion >= 5) {
                    this.issuerKeyID.read(this.issuerFingerprint);
                }
                else {
                    this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));
                }
                break;
            case enums.signatureSubpacket.preferredAEADAlgorithms:
                // Preferred AEAD Algorithms
                this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];
                break;
            case enums.signatureSubpacket.preferredCipherSuites:
                // Preferred AEAD Cipher Suites
                this.preferredCipherSuites = [];
                for (let i = mypos; i < bytes.length; i += 2) {
                    this.preferredCipherSuites.push([bytes[i], bytes[i + 1]]);
                }
                break;
            default:
                this.unknownSubpackets.push({
                    type,
                    critical,
                    body: bytes.subarray(mypos, bytes.length)
                });
                break;
        }
    }
    readSubPackets(bytes, trusted = true, config) {
        const subpacketLengthBytes = this.version === 6 ? 4 : 2;
        // Two-octet scalar octet count for following subpacket data.
        const subpacketLength = util.readNumber(bytes.subarray(0, subpacketLengthBytes));
        let i = subpacketLengthBytes;
        // subpacket data set (zero or more subpackets)
        while (i < subpacketLengthBytes + subpacketLength) {
            const len = readSimpleLength(bytes.subarray(i, bytes.length));
            i += len.offset;
            this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);
            i += len.len;
        }
        return i;
    }
    // Produces data to produce signature on
    toSign(type, data) {
        const t = enums.signature;
        switch (type) {
            case t.binary:
                if (data.text !== null) {
                    return util.encodeUTF8(data.getText(true));
                }
                return data.getBytes(true);
            case t.text: {
                const bytes = data.getBytes(true);
                // normalize EOL to \r\n
                return util.canonicalizeEOL(bytes);
            }
            case t.standalone:
                return new Uint8Array(0);
            case t.certGeneric:
            case t.certPersona:
            case t.certCasual:
            case t.certPositive:
            case t.certRevocation: {
                let packet;
                let tag;
                if (data.userID) {
                    tag = 0xB4;
                    packet = data.userID;
                }
                else if (data.userAttribute) {
                    tag = 0xD1;
                    packet = data.userAttribute;
                }
                else {
                    throw new Error('Either a userID or userAttribute packet needs to be ' +
                        'supplied for certification.');
                }
                const bytes = packet.write();
                return util.concat([this.toSign(t.key, data),
                    new Uint8Array([tag]),
                    util.writeNumber(bytes.length, 4),
                    bytes]);
            }
            case t.subkeyBinding:
            case t.subkeyRevocation:
            case t.keyBinding:
                return util.concat([this.toSign(t.key, data), this.toSign(t.key, {
                        key: data.bind
                    })]);
            case t.key:
                if (data.key === undefined) {
                    throw new Error('Key packet is required for this signature.');
                }
                return data.key.writeForHash(this.version);
            case t.keyRevocation:
                return this.toSign(t.key, data);
            case t.timestamp:
                return new Uint8Array(0);
            case t.thirdParty:
                throw new Error('Not implemented');
            default:
                throw new Error('Unknown signature type.');
        }
    }
    calculateTrailer(data, detached) {
        let length = 0;
        return transform(clone(this.signatureData), value => {
            length += value.length;
        }, () => {
            const arr = [];
            if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {
                if (detached) {
                    arr.push(new Uint8Array(6));
                }
                else {
                    arr.push(data.writeHeader());
                }
            }
            arr.push(new Uint8Array([this.version, 0xFF]));
            if (this.version === 5) {
                arr.push(new Uint8Array(4));
            }
            arr.push(util.writeNumber(length, 4));
            // For v5, this should really be writeNumber(length, 8) rather than the
            // hardcoded 4 zero bytes above
            return util.concat(arr);
        });
    }
    toHash(signatureType, data, detached = false) {
        const bytes = this.toSign(signatureType, data);
        return util.concat([this.salt || new Uint8Array(), bytes, this.signatureData, this.calculateTrailer(data, detached)]);
    }
    async hash(signatureType, data, toHash, detached = false) {
        if (this.version === 6 && this.salt.length !== saltLengthForHash(this.hashAlgorithm)) {
            // avoid hashing unexpected salt size
            throw new Error('Signature salt does not have the expected length');
        }
        if (!toHash)
            toHash = this.toHash(signatureType, data, detached);
        return computeDigest(this.hashAlgorithm, toHash);
    }
    /**
     * verifies the signature packet. Note: not all signature types are implemented
     * @param {PublicSubkeyPacket|PublicKeyPacket|
     *         SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature
     * @param {module:enums.signature} signatureType - Expected signature type
     * @param {Uint8Array|Object} data - Data which on the signature applies
     * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration
     * @param {Boolean} [detached] - Whether to verify a detached signature
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @throws {Error} if signature validation failed
     * @async
     */
    async verify(key, signatureType, data, date = new Date(), detached = false, config$1 = config) {
        if (!this.issuerKeyID.equals(key.getKeyID())) {
            throw new Error('Signature was not issued by the given public key');
        }
        if (this.publicKeyAlgorithm !== key.algorithm) {
            throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');
        }
        const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;
        // Cryptographic validity is cached after one successful verification.
        // However, for message signatures, we always re-verify, since the passed `data` can change
        const skipVerify = this[verified] && !isMessageSignature;
        if (!skipVerify) {
            let toHash;
            let hash;
            if (this.hashed) {
                hash = await this.hashed;
            }
            else {
                toHash = this.toHash(signatureType, data, detached);
                hash = await this.hash(signatureType, data, toHash);
            }
            hash = await readToEnd(hash);
            if (this.signedHashValue[0] !== hash[0] ||
                this.signedHashValue[1] !== hash[1]) {
                throw new Error('Signed digest did not match');
            }
            this.params = await this.params;
            this[verified] = await verify$1(this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams, toHash, hash);
            if (!this[verified]) {
                throw new Error('Signature verification failed');
            }
        }
        const normDate = util.normalizeDate(date);
        if (normDate && this.created > normDate) {
            throw new Error('Signature creation time is in the future');
        }
        if (normDate && normDate >= this.getExpirationTime()) {
            throw new Error('Signature is expired');
        }
        if (config$1.rejectHashAlgorithms.has(this.hashAlgorithm)) {
            throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());
        }
        if (config$1.rejectMessageHashAlgorithms.has(this.hashAlgorithm) &&
            [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {
            throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());
        }
        this.unknownSubpackets.forEach(({ type, critical }) => {
            if (critical) {
                throw new Error(`Unknown critical signature subpacket type ${type}`);
            }
        });
        this.rawNotations.forEach(({ name, critical }) => {
            if (critical && (config$1.knownNotations.indexOf(name) < 0)) {
                throw new Error(`Unknown critical notation: ${name}`);
            }
        });
        if (this.revocationKeyClass !== null) {
            throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');
        }
    }
    /**
     * Verifies signature expiration date
     * @param {Date} [date] - Use the given date for verification instead of the current time
     * @returns {Boolean} True if expired.
     */
    isExpired(date = new Date()) {
        const normDate = util.normalizeDate(date);
        if (normDate !== null) {
            return !(this.created <= normDate && normDate < this.getExpirationTime());
        }
        return false;
    }
    /**
     * Returns the expiration time of the signature or Infinity if signature does not expire
     * @returns {Date | Infinity} Expiration time.
     */
    getExpirationTime() {
        return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);
    }
}
/**
 * Creates a Uint8Array representation of a sub signature packet
 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}
 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}
 * @param {Integer} type - Subpacket signature type.
 * @param {Boolean} critical - Whether the subpacket should be critical.
 * @param {String} data - Data to be included
 * @returns {Uint8Array} The signature subpacket.
 * @private
 */
function writeSubPacket(type, critical, data) {
    const arr = [];
    arr.push(writeSimpleLength(data.length + 1));
    arr.push(new Uint8Array([(critical ? 0x80 : 0) | type]));
    arr.push(data);
    return util.concat(arr);
}
/**
 * Select the required salt length for the given hash algorithm, as per Table 23 (Hash algorithm registry) of the crypto refresh.
 * @see {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#section-9.5|Crypto Refresh Section 9.5}
 * @param {enums.hash} hashAlgorithm - Hash algorithm.
 * @returns {Integer} Salt length.
 * @private
 */
function saltLengthForHash(hashAlgorithm) {
    switch (hashAlgorithm) {
        case enums.hash.sha256: return 16;
        case enums.hash.sha384: return 24;
        case enums.hash.sha512: return 32;
        case enums.hash.sha224: return 16;
        case enums.hash.sha3_256: return 16;
        case enums.hash.sha3_512: return 32;
        default: throw new Error('Unsupported hash function');
    }
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Implementation of the One-Pass Signature Packets (Tag 4)
 *
 * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:
 * The One-Pass Signature packet precedes the signed data and contains
 * enough information to allow the receiver to begin calculating any
 * hashes needed to verify the signature.  It allows the Signature
 * packet to be placed at the end of the message, so that the signer
 * can compute the entire signed message in one pass.
 */
class OnePassSignaturePacket {
    static get tag() {
        return enums.packet.onePassSignature;
    }
    static fromSignaturePacket(signaturePacket, isLast) {
        const onePassSig = new OnePassSignaturePacket();
        onePassSig.version = signaturePacket.version === 6 ? 6 : 3;
        onePassSig.signatureType = signaturePacket.signatureType;
        onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;
        onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;
        onePassSig.issuerKeyID = signaturePacket.issuerKeyID;
        onePassSig.salt = signaturePacket.salt; // v6 only
        onePassSig.issuerFingerprint = signaturePacket.issuerFingerprint; // v6 only
        onePassSig.flags = isLast ? 1 : 0;
        return onePassSig;
    }
    constructor() {
        /** A one-octet version number.  The current versions are 3 and 6. */
        this.version = null;
        /**
         * A one-octet signature type.
         * Signature types are described in
         * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.
         * @type {enums.signature}
    
         */
        this.signatureType = null;
        /**
         * A one-octet number describing the hash algorithm used.
         * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}
         * @type {enums.hash}
         */
        this.hashAlgorithm = null;
        /**
         * A one-octet number describing the public-key algorithm used.
         * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}
         * @type {enums.publicKey}
         */
        this.publicKeyAlgorithm = null;
        /** Only for v6, a variable-length field containing the salt. */
        this.salt = null;
        /** Only for v3 packets, an eight-octet number holding the Key ID of the signing key. */
        this.issuerKeyID = null;
        /** Only for v6 packets, 32 octets of the fingerprint of the signing key. */
        this.issuerFingerprint = null;
        /**
         * A one-octet number holding a flag showing whether the signature is nested.
         * A zero value indicates that the next packet is another One-Pass Signature packet
         * that describes another signature to be applied to the same message data.
         */
        this.flags = null;
    }
    /**
     * parsing function for a one-pass signature packet (tag 4).
     * @param {Uint8Array} bytes - Payload of a tag 4 packet
     * @returns {OnePassSignaturePacket} Object representation.
     */
    read(bytes) {
        let mypos = 0;
        // A one-octet version number.  The current versions are 3 or 6.
        this.version = bytes[mypos++];
        if (this.version !== 3 && this.version !== 6) {
            throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);
        }
        // A one-octet signature type.  Signature types are described in
        //   Section 5.2.1.
        this.signatureType = bytes[mypos++];
        // A one-octet number describing the hash algorithm used.
        this.hashAlgorithm = bytes[mypos++];
        // A one-octet number describing the public-key algorithm used.
        this.publicKeyAlgorithm = bytes[mypos++];
        if (this.version === 6) {
            // Only for v6 signatures, a variable-length field containing:
            // A one-octet salt size. The value MUST match the value defined
            // for the hash algorithm as specified in Table 23 (Hash algorithm registry).
            // To allow parsing unknown hash algos, we only check the expected salt length when verifying.
            const saltLength = bytes[mypos++];
            // The salt; a random value value of the specified size.
            this.salt = bytes.subarray(mypos, mypos + saltLength);
            mypos += saltLength;
            // Only for v6 packets, 32 octets of the fingerprint of the signing key.
            this.issuerFingerprint = bytes.subarray(mypos, mypos + 32);
            mypos += 32;
            this.issuerKeyID = new KeyID();
            // For v6 the Key ID is the high-order 64 bits of the fingerprint.
            this.issuerKeyID.read(this.issuerFingerprint);
        }
        else {
            // Only for v3 packets, an eight-octet number holding the Key ID of the signing key.
            this.issuerKeyID = new KeyID();
            this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));
            mypos += 8;
        }
        // A one-octet number holding a flag showing whether the signature
        //   is nested.  A zero value indicates that the next packet is
        //   another One-Pass Signature packet that describes another
        //   signature to be applied to the same message data.
        this.flags = bytes[mypos++];
        return this;
    }
    /**
     * creates a string representation of a one-pass signature packet
     * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.
     */
    write() {
        const arr = [new Uint8Array([
                this.version,
                this.signatureType,
                this.hashAlgorithm,
                this.publicKeyAlgorithm
            ])];
        if (this.version === 6) {
            arr.push(new Uint8Array([this.salt.length]), this.salt, this.issuerFingerprint);
        }
        else {
            arr.push(this.issuerKeyID.write());
        }
        arr.push(new Uint8Array([this.flags]));
        return util.concatUint8Array(arr);
    }
    calculateTrailer(...args) {
        return fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));
    }
    async verify() {
        const correspondingSig = await this.correspondingSig;
        if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {
            throw new Error('Corresponding signature packet missing');
        }
        if (correspondingSig.signatureType !== this.signatureType ||
            correspondingSig.hashAlgorithm !== this.hashAlgorithm ||
            correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||
            !correspondingSig.issuerKeyID.equals(this.issuerKeyID) ||
            (this.version === 3 && correspondingSig.version === 6) ||
            (this.version === 6 && correspondingSig.version !== 6) ||
            (this.version === 6 && !util.equalsUint8Array(correspondingSig.issuerFingerprint, this.issuerFingerprint)) ||
            (this.version === 6 && !util.equalsUint8Array(correspondingSig.salt, this.salt))) {
            throw new Error('Corresponding signature packet does not match one-pass signature packet');
        }
        correspondingSig.hashed = this.hashed;
        return correspondingSig.verify.apply(correspondingSig, arguments);
    }
}
// eslint-disable-next-line @typescript-eslint/unbound-method
OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;
// eslint-disable-next-line @typescript-eslint/unbound-method
OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;
// eslint-disable-next-line @typescript-eslint/unbound-method
OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;

/** @access private */
/**
 * Instantiate a new packet given its tag
 * @function newPacketFromTag
 * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}
 * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
 * @returns {Object} New packet object with type based on tag
 * @throws {Error|UnsupportedError} for disallowed or unknown packets
 * @access private
 */
function newPacketFromTag(tag, allowedPackets) {
    if (!allowedPackets[tag]) {
        // distinguish between disallowed packets and unknown ones
        let packetType;
        try {
            packetType = enums.read(enums.packet, tag);
        }
        catch {
            throw new UnknownPacketError(`Unknown packet type with tag: ${tag}`);
        }
        throw new Error(`Packet not allowed in this context: ${packetType}`);
    }
    return new allowedPackets[tag]();
}
/**
 * This class represents a list of openpgp packets.
 * Take care when iterating over it - the packets themselves
 * are stored as numerical indices.
 * @extends Array
 * @access public
 */
class PacketList extends Array {
    /**
     * Parses the given binary data and returns a list of packets.
     * Equivalent to calling `read` on an empty PacketList instance.
     * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - binary data to parse
     * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
     * @param {Object} [config] - full configuration, defaults to openpgp.config
     * @param {function(enums.packet[], boolean, Object): void} [grammarValidator]
     * @param {Boolean} [delayErrors] - delay errors until the input stream has been read completely
     * @returns {Promise<PacketList>} parsed list of packets
     * @throws on parsing errors
     * @async
     */
    static async fromBinary(bytes, allowedPackets, config$1 = config, grammarValidator = null, delayErrors = false) {
        const packets = new PacketList();
        await packets.read(bytes, allowedPackets, config$1, grammarValidator, delayErrors);
        return packets;
    }
    /**
     * Reads a stream of binary data and interprets it as a list of packets.
     * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - binary data to parse
     * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
     * @param {Object} [config] - full configuration, defaults to openpgp.config
     * @param {function(enums.packet[], boolean, Object): void} [grammarValidator]
     * @param {Boolean} [delayErrors] - delay errors until the input stream has been read completely
     * @throws on parsing errors
     * @async
     */
    async read(bytes, allowedPackets, config$1 = config, grammarValidator = null, delayErrors = false) {
        let additionalAllowedPackets;
        if (config$1.additionalAllowedPackets.length) {
            additionalAllowedPackets = util.constructAllowedPackets(config$1.additionalAllowedPackets);
            allowedPackets = { ...allowedPackets, ...additionalAllowedPackets };
        }
        this.stream = transformPair(bytes, async (readable, writable) => {
            const reader = getReader(readable);
            const writer = getWriter(writable);
            try {
                let useStreamType = util.isStream(readable);
                while (true) {
                    await writer.ready;
                    let unauthenticatedError;
                    let wasStream;
                    await readPacket(reader, useStreamType, async (parsed) => {
                        try {
                            if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust || parsed.tag === enums.packet.padding) {
                                // According to the spec, these packet types should be ignored and not cause parsing errors, even if not explicitly allowed:
                                // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145
                                // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10
                                // - [Padding Packets] MUST be ignored when received: https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21
                                return;
                            }
                            const packet = newPacketFromTag(parsed.tag, allowedPackets);
                            // Unknown packets throw in the call above, we ignore them
                            // in the grammar checker.
                            try {
                                grammarValidator?.recordPacket(parsed.tag, additionalAllowedPackets);
                            }
                            catch (e) {
                                if (config$1.enforceGrammar) {
                                    throw e;
                                }
                                else {
                                    util.printDebugError(e);
                                }
                            }
                            packet.packets = new PacketList();
                            packet.fromStream = util.isStream(parsed.packet);
                            wasStream = packet.fromStream;
                            try {
                                await packet.read(parsed.packet, config$1);
                            }
                            catch (e) {
                                if (!(e instanceof UnsupportedError)) {
                                    throw util.wrapError(new MalformedPacketError(`Parsing ${packet.constructor.name} failed`), e);
                                }
                                throw e;
                            }
                            await writer.write(packet);
                        }
                        catch (e) {
                            // If an implementation encounters a critical packet where the packet type is unknown in a packet sequence,
                            // it MUST reject the whole packet sequence. On the other hand, an unknown non-critical packet MUST be ignored.
                            // Packet Tags from 0 to 39 are critical. Packet Tags from 40 to 63 are non-critical.
                            const throwUnknownPacketError = e instanceof UnknownPacketError &&
                                parsed.tag <= 39;
                            // In case of unsupported packet versions/algorithms/etc, we ignore the error by default
                            // (unless the packet is a data packet, see below).
                            const throwUnsupportedError = e instanceof UnsupportedError &&
                                !(e instanceof UnknownPacketError) &&
                                !config$1.ignoreUnsupportedPackets;
                            // In case of packet parsing errors, e.name was set to 'MalformedPacketError' above.
                            // By default, we throw for these errors.
                            const throwMalformedPacketError = e instanceof MalformedPacketError &&
                                !config$1.ignoreMalformedPackets;
                            // The packets that support streaming are the ones that contain message data.
                            // Those are also the ones we want to be more strict about and throw on all errors
                            // (since we likely cannot process the message without these packets anyway).
                            const throwDataPacketError = supportsStreaming(parsed.tag);
                            // Throw all other errors, including `GrammarError`s, disallowed packet errors, and unexpected errors.
                            const throwOtherError = !(e instanceof UnknownPacketError ||
                                e instanceof UnsupportedError ||
                                e instanceof MalformedPacketError);
                            if (throwUnknownPacketError ||
                                throwUnsupportedError ||
                                throwMalformedPacketError ||
                                throwDataPacketError ||
                                throwOtherError) {
                                if (delayErrors) {
                                    unauthenticatedError = e;
                                }
                                else {
                                    await writer.abort(e);
                                }
                            }
                            else {
                                const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet);
                                await writer.write(unparsedPacket);
                            }
                            util.printDebugError(e);
                        }
                    });
                    if (wasStream) {
                        // Don't allow more than one streaming packet, as read errors
                        // may get lost in the second packet's data stream.
                        useStreamType = null;
                    }
                    // If there was a parse error, read the entire input first
                    // in case there's an MDC error, which should take precedence.
                    if (unauthenticatedError) {
                        await reader.readToEnd();
                        // eslint-disable-next-line @typescript-eslint/only-throw-error
                        throw unauthenticatedError;
                    }
                    // We peek to check whether this was the last packet.
                    // We peek 2 bytes instead of 1 because `readPacket` also
                    // peeks 2 bytes, and we want to cut a `subarray` of the
                    // correct length into `web-stream-tools`' `externalBuffer`
                    // as a tiny optimization here.
                    const nextPacket = await reader.peekBytes(2);
                    const done = !nextPacket || !nextPacket.length;
                    if (done) {
                        // Here we are past the MDC check for SEIPDv1 data, hence
                        // the data is always authenticated at this point.
                        try {
                            grammarValidator?.recordEnd();
                        }
                        catch (e) {
                            if (config$1.enforceGrammar) {
                                throw e;
                            }
                            else {
                                util.printDebugError(e);
                            }
                        }
                        await writer.ready;
                        await writer.close();
                        return;
                    }
                }
            }
            catch (e) {
                await writer.abort(e);
            }
        });
        // Wait until first few packets have been read
        const reader = getReader(this.stream);
        while (true) {
            const { done, value } = await reader.read();
            if (!done) {
                this.push(value);
            }
            else {
                this.stream = null;
            }
            if (done || supportsStreaming(value.constructor.tag)) {
                break;
            }
        }
        reader.releaseLock();
    }
    /**
     * Creates a binary representation of openpgp objects contained within the
     * class instance.
     * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.
     */
    write() {
        const arr = [];
        for (let i = 0; i < this.length; i++) {
            const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag;
            const packetbytes = this[i].write();
            if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {
                let buffer = [];
                let bufferLength = 0;
                const minLength = 512;
                arr.push(writeTag(tag));
                arr.push(transform(packetbytes, value => {
                    buffer.push(value);
                    bufferLength += value.length;
                    if (bufferLength >= minLength) {
                        const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);
                        const chunkSize = 2 ** powerOf2;
                        const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));
                        buffer = [bufferConcat.subarray(1 + chunkSize)];
                        bufferLength = buffer[0].length;
                        return bufferConcat.subarray(0, 1 + chunkSize);
                    }
                }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));
            }
            else {
                if (util.isStream(packetbytes)) {
                    let length = 0;
                    arr.push(transform(clone(packetbytes), value => {
                        length += value.length;
                    }, () => writeHeader(tag, length)));
                }
                else {
                    arr.push(writeHeader(tag, packetbytes.length));
                }
                arr.push(packetbytes);
            }
        }
        return util.concat(arr);
    }
    /**
     * Creates a new PacketList with all packets matching the given tag(s)
     * @param {...module:enums.packet} tags - packet tags to look for
     * @returns {PacketList}
     */
    filterByTag(...tags) {
        const filtered = new PacketList();
        const handle = tag => packetType => tag === packetType;
        for (let i = 0; i < this.length; i++) {
            if (tags.some(handle(this[i].constructor.tag))) {
                filtered.push(this[i]);
            }
        }
        return filtered;
    }
    /**
     * Traverses packet list and returns first packet with matching tag
     * @param {module:enums.packet} tag - The packet tag
     * @returns {Packet|undefined}
     */
    findPacket(tag) {
        return this.find(packet => packet.constructor.tag === tag);
    }
    /**
     * Find indices of packets with the given tag(s)
     * @param {...module:enums.packet} tags - packet tags to look for
     * @returns {Integer[]} packet indices
     */
    indexOfTag(...tags) {
        const tagIndex = [];
        const that = this;
        const handle = tag => packetType => tag === packetType;
        for (let i = 0; i < this.length; i++) {
            if (tags.some(handle(that[i].constructor.tag))) {
                tagIndex.push(i);
            }
        }
        return tagIndex;
    }
}

/** @access private */
class GrammarError extends Error {
    constructor(...params) {
        super(...params);
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, GrammarError);
        }
        this.name = 'GrammarError';
    }
}
var MessageType;
(function (MessageType) {
    MessageType[MessageType["EmptyMessage"] = 0] = "EmptyMessage";
    MessageType[MessageType["PlaintextOrEncryptedData"] = 1] = "PlaintextOrEncryptedData";
    MessageType[MessageType["EncryptedSessionKeys"] = 2] = "EncryptedSessionKeys";
    MessageType[MessageType["StandaloneAdditionalAllowedData"] = 3] = "StandaloneAdditionalAllowedData";
})(MessageType || (MessageType = {}));
/**
 * Implement OpenPGP message grammar based on: https://www.rfc-editor.org/rfc/rfc9580.html#section-10.3 .
 * It is slightly more lenient as it also allows standalone ESK sequences, as well as empty (signed) messages.
 * This latter case is needed to allow unknown packets.
 * A new `MessageGrammarValidator` instance must be created for each packet sequence, as the instance is stateful:
 * - `recordPacket` must be called for each packet in the sequence; the function will throw as soon as
 *  an invalid packet is detected.
 * - `recordEnd` must be called at the end of the packet sequence to confirm its validity.
 * @access private
 */
class MessageGrammarValidator {
    constructor() {
        // PDA validator inspired by https://blog.jabberhead.tk/2022/10/26/implementing-packet-sequence-validation-using-pushdown-automata/ .
        this.state = MessageType.EmptyMessage;
        this.leadingOnePassSignatureCounter = 0;
    }
    /**
     * Determine validity of the next packet in the sequence.
     * NB: padding, marker and unknown packets are expected to already be filtered out on parsing,
     * and are not accepted by `recordPacket`.
     * @param packet - packet to validate
     * @param additionalAllowedPackets - object containing packets which are allowed anywhere in the sequence, except they cannot precede a OPS packet
     * @throws {GrammarError} on invalid `packet` input
     */
    recordPacket(packet, additionalAllowedPackets) {
        switch (this.state) {
            case MessageType.EmptyMessage:
            case MessageType.StandaloneAdditionalAllowedData:
                switch (packet) {
                    case enums.packet.literalData:
                    case enums.packet.compressedData:
                    case enums.packet.aeadEncryptedData:
                    case enums.packet.symEncryptedIntegrityProtectedData:
                    case enums.packet.symmetricallyEncryptedData:
                        this.state = MessageType.PlaintextOrEncryptedData;
                        return;
                    case enums.packet.signature:
                        // Signature | <AdditionalAllowedPacketsOnly> and
                        // OPS | Signature | <AdditionalAllowedPacketsOnly> | Signature and
                        // OPS | <AdditionalAllowedPacketsOnly> | Signature are allowed
                        if (this.state === MessageType.StandaloneAdditionalAllowedData) {
                            if (--this.leadingOnePassSignatureCounter < 0) {
                                throw new GrammarError('Trailing signature packet without OPS');
                            }
                        }
                        // this.state remains EmptyMessage or StandaloneAdditionalAllowedData
                        return;
                    case enums.packet.onePassSignature:
                        if (this.state === MessageType.StandaloneAdditionalAllowedData) {
                            // we do not allow this case, for simplicity
                            throw new GrammarError('OPS following StandaloneAdditionalAllowedData');
                        }
                        this.leadingOnePassSignatureCounter++;
                        // this.state remains EmptyMessage
                        return;
                    case enums.packet.publicKeyEncryptedSessionKey:
                    case enums.packet.symEncryptedSessionKey:
                        this.state = MessageType.EncryptedSessionKeys;
                        return;
                    default:
                        if (!additionalAllowedPackets?.[packet]) {
                            throw new GrammarError(`Unexpected packet ${packet} in state ${this.state}`);
                        }
                        this.state = MessageType.StandaloneAdditionalAllowedData;
                        return;
                }
            case MessageType.PlaintextOrEncryptedData:
                switch (packet) {
                    case enums.packet.signature:
                        if (--this.leadingOnePassSignatureCounter < 0) {
                            throw new GrammarError('Trailing signature packet without OPS');
                        }
                        this.state = MessageType.PlaintextOrEncryptedData;
                        return;
                    default:
                        if (!additionalAllowedPackets?.[packet]) {
                            throw new GrammarError(`Unexpected packet ${packet} in state ${this.state}`);
                        }
                        this.state = MessageType.PlaintextOrEncryptedData;
                        return;
                }
            case MessageType.EncryptedSessionKeys:
                switch (packet) {
                    case enums.packet.publicKeyEncryptedSessionKey:
                    case enums.packet.symEncryptedSessionKey:
                        this.state = MessageType.EncryptedSessionKeys;
                        return;
                    case enums.packet.symEncryptedIntegrityProtectedData:
                    case enums.packet.aeadEncryptedData:
                    case enums.packet.symmetricallyEncryptedData:
                        this.state = MessageType.PlaintextOrEncryptedData;
                        return;
                    case enums.packet.signature:
                        if (--this.leadingOnePassSignatureCounter < 0) {
                            throw new GrammarError('Trailing signature packet without OPS');
                        }
                        this.state = MessageType.PlaintextOrEncryptedData;
                        return;
                    default:
                        if (!additionalAllowedPackets?.[packet]) {
                            throw new GrammarError(`Unexpected packet ${packet} in state ${this.state}`);
                        }
                        this.state = MessageType.EncryptedSessionKeys;
                }
        }
    }
    /**
     * Signal end of the packet sequence for final validity check
     * @throws {GrammarError} on invalid sequence
     */
    recordEnd() {
        switch (this.state) {
            case MessageType.EmptyMessage: // needs to be allowed for PacketLists that only include unknown packets
            case MessageType.PlaintextOrEncryptedData:
            case MessageType.EncryptedSessionKeys:
            case MessageType.StandaloneAdditionalAllowedData:
                if (this.leadingOnePassSignatureCounter > 0) {
                    throw new GrammarError('Missing trailing signature packets');
                }
        }
    }
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// A Compressed Data packet can contain the following packet types
const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([
    LiteralDataPacket,
    OnePassSignaturePacket,
    SignaturePacket
]);
/**
 * Implementation of the Compressed Data Packet (Tag 8)
 *
 * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:
 * The Compressed Data packet contains compressed data.  Typically,
 * this packet is found as the contents of an encrypted packet, or following
 * a Signature or One-Pass Signature packet, and contains a literal data packet.
 */
class CompressedDataPacket {
    static get tag() {
        return enums.packet.compressedData;
    }
    /**
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     */
    constructor(config$1 = config) {
        /**
         * List of packets
         * @type {PacketList}
         */
        this.packets = null;
        /**
         * Compression algorithm
         * @type {enums.compression}
         */
        this.algorithm = config$1.preferredCompressionAlgorithm;
        /**
         * Compressed packet data
         * @type {Uint8Array | ReadableStream<Uint8Array>}
         */
        this.compressed = null;
    }
    /**
     * Parsing function for the packet.
     * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - Payload of a tag 8 packet
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     */
    async read(bytes, config$1 = config) {
        await parse(bytes, async (reader) => {
            // One octet that gives the algorithm used to compress the packet.
            this.algorithm = await reader.readByte();
            // Compressed data, which makes up the remainder of the packet.
            this.compressed = reader.remainder();
            await this.decompress(config$1);
        });
    }
    /**
     * Return the compressed packet.
     * @returns {Uint8Array | ReadableStream<Uint8Array>} Binary compressed packet.
     */
    write() {
        if (this.compressed === null) {
            this.compress();
        }
        return util.concat([new Uint8Array([this.algorithm]), this.compressed]);
    }
    /**
     * Decompression method for decompressing the compressed data
     * read by read_packet
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     */
    async decompress(config$1 = config) {
        const compressionName = enums.read(enums.compression, this.algorithm);
        const decompressionFn = decompress_fns[compressionName]; // bzip decompression is async
        if (!decompressionFn) {
            throw new Error(`${compressionName} decompression not supported`);
        }
        let decompressed = await decompressionFn(this.compressed, config$1);
        if (config$1.maxDecompressedMessageSize !== Infinity) {
            let decompressedSize = 0;
            decompressed = transform(decompressed, chunk => {
                decompressedSize += chunk.length;
                if (decompressedSize > config$1.maxDecompressedMessageSize) {
                    throw new Error('Maximum decompressed message size exceeded');
                }
                return chunk;
            });
        }
        if (!isStream(this.compressed) || isArrayStream(this.compressed)) {
            decompressed = await readToEnd(decompressed);
        }
        // Decompressing a Compressed Data packet MUST also yield a valid OpenPGP Message
        this.packets = await PacketList.fromBinary(decompressed, allowedPackets$5, config$1, new MessageGrammarValidator());
    }
    /**
     * Compress the packet data (member decompressedData)
     */
    compress() {
        const compressionName = enums.read(enums.compression, this.algorithm);
        const compressionFn = compress_fns[compressionName];
        if (!compressionFn) {
            throw new Error(`${compressionName} compression not supported`);
        }
        const data = this.packets.write();
        let compressed = compressionFn(data);
        if (!isStream(data) || isArrayStream(data)) {
            // Convert back to an ArrayStream when we weren't streaming before,
            // even if web streams were used internally while compressing,
            // so that we don't return a stream from the high-level function.
            compressed = fromAsync(() => readToEnd(compressed));
        }
        this.compressed = compressed;
    }
}
//////////////////////////
//                      //
//   Helper functions   //
//                      //
//////////////////////////
function splitStream(data) {
    const chunkSize = 65536;
    const reader = getReader(data);
    return new ReadableStream({
        async pull(controller) {
            try {
                const { value, done } = await reader.read();
                if (done) {
                    controller.close();
                    return;
                }
                for (let i = 0; i <= value.length; i += chunkSize) {
                    if (!i || i < value.length) {
                        controller.enqueue(value.subarray(i, i + chunkSize));
                    }
                }
            }
            catch (e) {
                controller.error(e);
            }
        }
    }, { highWaterMark: 0 });
}
/**
 * Zlib processor relying on Compression Stream API if available, or falling back to fflate otherwise.
 * @param {function(): CompressionStream|function(): DecompressionStream} compressionStreamInstantiator
 * @param {FunctionConstructor} ZlibStreamedConstructor - fflate constructor
 * @returns {ReadableStream<Uint8Array>} compressed or decompressed data
 * @private
 */
function zlib(compressionStreamInstantiator, ZlibStreamedConstructor) {
    return (data, _config) => {
        let stream;
        if (isArrayStream(data)) {
            stream = new ReadableStream({
                async start(controller) {
                    try {
                        controller.enqueue(await readToEnd(data));
                        controller.close();
                    }
                    catch (e) {
                        controller.error(e);
                    }
                }
            });
        }
        else if (isStream(data)) {
            stream = data;
        }
        else {
            stream = toStream(data);
        }
        // Split the input stream into chunks of 64KiB.
        // This is only necessary for the fflate fallback decompressor, and
        // the native Compression API in WebKit, as they decompress the
        // entire input chunk and emit one output chunk, rather than
        // outputting chunks incrementally as it decompresses the input.
        // Therefore, for backpressure to work properly, we need to split
        // the input chunks.
        // We do it unconditionally here (regardless of the platform and
        // API used) for simplicity and because it doesn't hurt much.
        // (This only does anything if the input chunks aren't already 64KiB
        // or smaller, e.g. when a large message is passed all at once.)
        stream = splitStream(stream);
        // Use Compression Streams API if available (see https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API)
        if (compressionStreamInstantiator) {
            try {
                const compressorOrDecompressor = compressionStreamInstantiator();
                return stream.pipeThrough(compressorOrDecompressor);
            }
            catch (err) {
                // If format is unsupported in Compression/DecompressionStream, then a TypeError is thrown, and we fallback to fflate.
                if (err.name !== 'TypeError') {
                    throw err;
                }
            }
        }
        // JS fallback
        const inputReader = getReader(stream);
        const zlibStream = new ZlibStreamedConstructor();
        let providedData = false;
        let allDone = false;
        return new ReadableStream({
            start(controller) {
                zlibStream.ondata = (value, isLast) => {
                    controller.enqueue(value);
                    providedData = true;
                    if (isLast) {
                        controller.close();
                        allDone = true;
                    }
                };
            },
            async pull() {
                providedData = false;
                while (!providedData && !allDone) {
                    const { done, value } = await inputReader.read();
                    if (done) {
                        zlibStream.push(new Uint8Array(), true);
                        return;
                    }
                    else if (value.length) {
                        zlibStream.push(value);
                    }
                }
            }
        }, { highWaterMark: 0 });
    };
}
function bzip2Decompress() {
    return async function (data, config) {
        const { default: unbzip2Stream } = await Promise.resolve().then(function () { return index$1; });
        return unbzip2Stream(toStream(data), config.maxDecompressedMessageSize);
    };
}
/**
 * Get Compression Stream API instantiators if the constructors are implemented.
 * NB: the return instantiator functions will throw when called if the provided `compressionFormat` is not supported
 * (supported formats cannot be determined in advance).
 * @param {'deflate-raw'|'deflate'|'gzip'|string} compressionFormat
 * @returns {{ compressor: function(): CompressionStream | false, decompressor: function(): DecompressionStream | false }}
 * @private
 */
const getCompressionStreamInstantiators = compressionFormat => ({
    compressor: typeof CompressionStream !== 'undefined' && (() => new CompressionStream(compressionFormat)),
    decompressor: typeof DecompressionStream !== 'undefined' && (() => new DecompressionStream(compressionFormat))
});
const compress_fns = {
    zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').compressor, Deflate),
    zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').compressor, Zlib)
};
const decompress_fns = {
    uncompressed: (data, _config) => data,
    zip: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate-raw').decompressor, Inflate),
    zlib: /*#__PURE__*/ zlib(getCompressionStreamInstantiators('deflate').decompressor, Unzlib),
    bzip2: /*#__PURE__*/ bzip2Decompress() // NB: async due to dynamic lib import
};

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Store `value` in the 64-bit big-endian field at `byteOffset` of `view`.
 * @param {DataView} dataView
 * @param {Number} byteOffset - Offset of the 64-bit field
 * @param {Number} value - Value to store (a safe integer)
 */
function setUint64(dataView, byteOffset, value) {
    if (typeof dataView.setBigUint64 === 'function') {
        return dataView.setBigUint64(byteOffset, BigInt(value));
    }
    // Fallback for Safari 14, which lacks `DataView.prototype.setBigUint64`.
    if (value <= 0xFFFFFFFF) {
        dataView.setUint32(byteOffset, 0);
        dataView.setUint32(byteOffset + 4, value);
    }
    else {
        const bigValue = BigInt(value);
        dataView.setUint32(byteOffset, Number(bigValue >> BigInt(32)));
        dataView.setUint32(byteOffset + 4, Number(bigValue & BigInt(0xFFFFFFFF)));
    }
}
// A SEIP packet can contain the following packet types
const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([
    LiteralDataPacket,
    CompressedDataPacket,
    OnePassSignaturePacket,
    SignaturePacket
]);
/**
 * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)
 *
 * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:
 * The Symmetrically Encrypted Integrity Protected Data packet is
 * a variant of the Symmetrically Encrypted Data packet. It is a new feature
 * created for OpenPGP that addresses the problem of detecting a modification to
 * encrypted data. It is used in combination with a Modification Detection Code
 * packet.
 */
class SymEncryptedIntegrityProtectedDataPacket {
    static get tag() {
        return enums.packet.symEncryptedIntegrityProtectedData;
    }
    static fromObject({ version, aeadAlgorithm }) {
        if (version !== 1 && version !== 2) {
            throw new Error('Unsupported SEIPD version');
        }
        const seip = new SymEncryptedIntegrityProtectedDataPacket();
        seip.version = version;
        if (version === 2) {
            seip.aeadAlgorithm = aeadAlgorithm;
        }
        return seip;
    }
    constructor() {
        this.version = null;
        // The following 4 fields are for V2 only.
        /** @type {enums.symmetric} */
        this.cipherAlgorithm = null;
        /** @type {enums.aead} */
        this.aeadAlgorithm = null;
        this.chunkSizeByte = null;
        this.salt = null;
        this.encrypted = null;
        this.packets = null;
    }
    async read(bytes) {
        await parse(bytes, async (reader) => {
            this.version = await reader.readByte();
            // - A one-octet version number with value 1 or 2.
            if (this.version !== 1 && this.version !== 2) {
                throw new UnsupportedError(`Version ${this.version} of the SEIP packet is unsupported.`);
            }
            if (this.version === 2) {
                // - A one-octet cipher algorithm.
                this.cipherAlgorithm = await reader.readByte();
                // - A one-octet AEAD algorithm.
                this.aeadAlgorithm = await reader.readByte();
                // - A one-octet chunk size.
                this.chunkSizeByte = await reader.readByte();
                // - Thirty-two octets of salt. The salt is used to derive the message key and must be unique.
                this.salt = await reader.readBytes(32);
            }
            // For V1:
            // - Encrypted data, the output of the selected symmetric-key cipher
            //   operating in Cipher Feedback mode with shift amount equal to the
            //   block size of the cipher (CFB-n where n is the block size).
            // For V2:
            // - Encrypted data, the output of the selected symmetric-key cipher operating in the given AEAD mode.
            // - A final, summary authentication tag for the AEAD mode.
            this.encrypted = reader.remainder();
        });
    }
    write() {
        if (this.version === 2) {
            return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.salt, this.encrypted]);
        }
        return util.concat([new Uint8Array([this.version]), this.encrypted]);
    }
    /**
     * Encrypt the payload in the packet.
     * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use
     * @param {Uint8Array} key - The key of cipher blocksize length to be used
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Boolean>}
     * @throws {Error} on encryption failure
     * @async
     */
    async encrypt(sessionKeyAlgorithm, key, config$1 = config) {
        // We check that the session key size matches the one expected by the symmetric algorithm.
        // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size,
        // but we want to ensure that the input key isn't e.g. too short.
        // The check is done here, instead of on encrypted session key (ESK) encryption, because v6 ESK packets do not store the session key algorithm,
        // which is instead included in the SEIPDv2 data.
        const { blockSize, keySize } = getCipherParams(sessionKeyAlgorithm);
        if (key.length !== keySize) {
            throw new Error('Unexpected session key size');
        }
        let bytes = this.packets.write();
        if (isArrayStream(bytes))
            bytes = await readToEnd(bytes);
        if (this.version === 2) {
            this.cipherAlgorithm = sessionKeyAlgorithm;
            this.salt = getRandomBytes(32);
            this.chunkSizeByte = config$1.aeadChunkSizeByte;
            this.encrypted = await runAEAD(this, 'encrypt', key, bytes);
        }
        else {
            const prefix = await getPrefixRandom(sessionKeyAlgorithm);
            const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet
            const tohash = util.concat([prefix, bytes, mdc]);
            const hash = await computeDigest(enums.hash.sha1, passiveClone(tohash));
            const plaintext = util.concat([tohash, hash]);
            this.encrypted = await encrypt$1(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize));
        }
        return true;
    }
    /**
     * Decrypts the encrypted data contained in the packet.
     * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used
     * @param {Uint8Array} key - The key of cipher blocksize length to be used
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Boolean>}
     * @throws {Error} on decryption failure
     * @async
     */
    async decrypt(sessionKeyAlgorithm, key, config$1 = config) {
        // We check that the session key size matches the one expected by the symmetric algorithm.
        // This is especially important for SEIPDv2 session keys, as a key derivation step is run where the resulting key will always match the expected cipher size,
        // but we want to ensure that the input key isn't e.g. too short.
        // The check is done here, instead of on encrypted session key (ESK) decryption, because v6 ESK packets do not store the session key algorithm,
        // which is instead included in the SEIPDv2 data.
        if (key.length !== getCipherParams(sessionKeyAlgorithm).keySize) {
            throw new Error('Unexpected session key size');
        }
        let encrypted = clone(this.encrypted);
        if (isArrayStream(encrypted))
            encrypted = await readToEnd(encrypted);
        let packetbytes;
        let delayErrors = false;
        if (this.version === 2) {
            if (this.cipherAlgorithm !== sessionKeyAlgorithm) {
                // sanity check
                throw new Error('Unexpected session key algorithm');
            }
            packetbytes = await runAEAD(this, 'decrypt', key, encrypted);
        }
        else {
            const { blockSize } = getCipherParams(sessionKeyAlgorithm);
            const decrypted = await decrypt$1(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize));
            // there must be a modification detection code packet as the
            // last packet and everything gets hashed except the hash itself
            const realHash = slice(passiveClone(decrypted), -20);
            const tohash = slice(decrypted, 0, -20);
            const verifyHash = Promise.all([
                readToEnd(await computeDigest(enums.hash.sha1, passiveClone(tohash))),
                readToEnd(realHash)
            ]).then(([hash, mdc]) => {
                if (!util.equalsUint8Array(hash, mdc)) {
                    throw new Error('Modification detected.');
                }
                // this last chunk comes at the end of the stream passed to Packetlist.read's streamTransformPair,
                // which can thus be 'done' only after the MDC has been checked.
                return new Uint8Array();
            });
            const bytes = slice(tohash, blockSize + 2); // Remove random prefix
            packetbytes = slice(bytes, 0, -2); // Remove MDC packet
            packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]);
            if (util.isStream(encrypted) && config$1.allowUnauthenticatedStream) {
                delayErrors = true;
            }
            else {
                packetbytes = await readToEnd(packetbytes);
            }
        }
        // - Decrypting a version 1 Symmetrically Encrypted and Integrity Protected Data packet
        // MUST yield a valid OpenPGP Message.
        // - Decrypting a version 2 Symmetrically Encrypted and Integrity Protected Data packet
        // MUST yield a valid Optionally Padded Message.
        this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$4, config$1, new MessageGrammarValidator(), delayErrors);
        return true;
    }
}
/**
 * En/decrypt the payload.
 * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt
 * @param {Uint8Array} key - The session key used to en/decrypt the payload
 * @param {Uint8Array | ReadableStream<Uint8Array>} data - The data to en/decrypt
 * @returns {Promise<Uint8Array | ReadableStream<Uint8Array>>}
 * @async
 * @access private
 */
async function runAEAD(packet, fn, key, data) {
    const isSEIPDv2 = packet instanceof SymEncryptedIntegrityProtectedDataPacket && packet.version === 2;
    const isAEADP = !isSEIPDv2 && packet.constructor.tag === enums.packet.aeadEncryptedData; // no `instanceof` to avoid importing the corresponding class (circular import)
    if (!isSEIPDv2 && !isAEADP)
        throw new Error('Unexpected packet type');
    // we allow `experimentalGCM` for AEADP for backwards compatibility, since v5 keys from OpenPGP.js v5 might be declaring
    // that preference, as the `gcm` ID had not been standardized at the time.
    // NB: AEADP are never automatically generate as part of message encryption by OpenPGP.js, the packet must be manually created.
    const mode = getAEADMode(packet.aeadAlgorithm, isAEADP);
    const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;
    const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;
    const chunkSize = 2 ** (packet.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))
    const chunkIndexSizeIfAEADEP = isAEADP ? 8 : 0;
    const adataBuffer = new ArrayBuffer(13 + chunkIndexSizeIfAEADEP);
    const adataArray = new Uint8Array(adataBuffer, 0, 5 + chunkIndexSizeIfAEADEP);
    const adataTagArray = new Uint8Array(adataBuffer);
    const adataView = new DataView(adataBuffer);
    const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);
    adataArray.set([0xC0 | packet.constructor.tag, packet.version, packet.cipherAlgorithm, packet.aeadAlgorithm, packet.chunkSizeByte], 0);
    let chunkIndex = 0;
    let latestPromise = Promise.resolve();
    let cryptedBytes = 0;
    let queuedBytes = 0;
    let iv;
    let ivView;
    if (isSEIPDv2) {
        const { keySize } = getCipherParams(packet.cipherAlgorithm);
        const { ivLength } = mode;
        const info = new Uint8Array(adataBuffer, 0, 5);
        const derived = await computeHKDF(enums.hash.sha256, key, packet.salt, info, keySize + ivLength);
        key = derived.subarray(0, keySize);
        iv = derived.subarray(keySize); // The last 8 bytes of HKDF output are unneeded, but this avoids one copy.
        iv.fill(0, iv.length - 8);
        ivView = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);
    }
    else { // AEADEncryptedDataPacket
        iv = packet.iv;
        // ivView is unused in this case
    }
    const modeInstance = await mode(packet.cipherAlgorithm, key);
    return transformPair(data, async (readable, writable) => {
        if (util.isStream(readable) !== 'array') {
            const buffer = new TransformStream({}, {
                highWaterMark: util.getHardwareConcurrency() * 2 ** (packet.chunkSizeByte + 6),
                size: array => array.length
            });
            pipe(buffer.readable, writable);
            writable = buffer.writable;
        }
        const reader = getReader(readable);
        const writer = getWriter(writable);
        try {
            while (true) {
                let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();
                const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);
                chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);
                let cryptedPromise;
                let done;
                let nonce;
                if (isSEIPDv2) { // SEIPD V2
                    nonce = iv;
                }
                else { // AEADEncryptedDataPacket
                    nonce = iv.slice();
                    for (let i = 0; i < 8; i++) {
                        nonce[iv.length - 8 + i] ^= chunkIndexArray[i];
                    }
                }
                if (!chunkIndex || chunk.length) {
                    reader.unshift(finalChunk);
                    cryptedPromise = modeInstance[fn](chunk, nonce, adataArray);
                    cryptedPromise.catch(() => { });
                    queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;
                }
                else {
                    // After the last chunk, we either encrypt a final, empty
                    // data chunk to get the final authentication tag or
                    // validate that final authentication tag.
                    setUint64(adataView, 5 + chunkIndexSizeIfAEADEP, cryptedBytes);
                    cryptedPromise = modeInstance[fn](finalChunk, nonce, adataTagArray);
                    cryptedPromise.catch(() => { });
                    queuedBytes += tagLengthIfEncrypting;
                    done = true;
                }
                cryptedBytes += chunk.length - tagLengthIfDecrypting;
                latestPromise = latestPromise.then(() => cryptedPromise).then(async (crypted) => {
                    await writer.ready;
                    await writer.write(crypted);
                    queuedBytes -= crypted.length;
                }).catch(err => writer.abort(err));
                if (done || queuedBytes > writer.desiredSize) {
                    await latestPromise; // Respect backpressure
                }
                if (!done) {
                    // The chunk index is written as a full 64-bit value, so the derived nonces are always unique
                    // and never wrap. This also keeps AES-GCM within its security bounds without an explicit chunk limit:
                    // the NIST SP 800-38D 2^32-invocation limit guards against random-nonce collisions, which do not
                    // apply to the OpenPGP counter-based nonces.
                    if (isSEIPDv2) { // SEIPD V2
                        setUint64(ivView, iv.length - 8, ++chunkIndex);
                    }
                    else { // AEADEncryptedDataPacket
                        setUint64(adataView, 5, ++chunkIndex);
                    }
                }
                else {
                    await writer.close();
                    break;
                }
            }
        }
        catch (e) {
            await writer.ready.catch(() => { });
            await writer.abort(e);
        }
    });
}

/** @access public */
// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2016 Tankred Hase
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// An AEAD-encrypted Data packet can contain the following packet types
const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([
    LiteralDataPacket,
    CompressedDataPacket,
    OnePassSignaturePacket,
    SignaturePacket
]);
const VERSION$1 = 1; // A one-octet version number of the data packet.
/**
 * Implementation of the Symmetrically Encrypted Authenticated Encryption with
 * Additional Data (AEAD) Protected Data Packet
 *
 * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:
 * AEAD Protected Data Packet
 */
class AEADEncryptedDataPacket {
    static get tag() {
        return enums.packet.aeadEncryptedData;
    }
    constructor() {
        this.version = VERSION$1;
        /** @type {enums.symmetric} */
        this.cipherAlgorithm = null;
        /** @type {enums.aead} */
        this.aeadAlgorithm = enums.aead.eax;
        this.chunkSizeByte = null;
        this.iv = null;
        this.encrypted = null;
        this.packets = null;
    }
    /**
     * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
     * @param {Uint8Array | ReadableStream<Uint8Array>} bytes
     * @throws {Error} on parsing failure
     */
    async read(bytes) {
        await parse(bytes, async (reader) => {
            const version = await reader.readByte();
            if (version !== VERSION$1) { // The only currently defined value is 1.
                throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);
            }
            this.cipherAlgorithm = await reader.readByte();
            this.aeadAlgorithm = await reader.readByte();
            this.chunkSizeByte = await reader.readByte();
            const mode = getAEADMode(this.aeadAlgorithm, true);
            this.iv = await reader.readBytes(mode.ivLength);
            this.encrypted = reader.remainder();
        });
    }
    /**
     * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
     * @returns {Uint8Array | ReadableStream<Uint8Array>} The encrypted payload.
     */
    write() {
        return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]);
    }
    /**
     * Decrypt the encrypted payload.
     * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm
     * @param {Uint8Array} key - The session key used to encrypt the payload
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @throws {Error} if decryption was not successful
     * @async
     */
    async decrypt(sessionKeyAlgorithm, key, config$1 = config) {
        this.packets = await PacketList.fromBinary(await runAEAD(this, 'decrypt', key, clone(this.encrypted)), allowedPackets$3, config$1, new MessageGrammarValidator());
    }
    /**
     * Encrypt the packet payload.
     * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm
     * @param {Uint8Array} key - The session key used to encrypt the payload
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @throws {Error} if encryption was not successful
     * @async
     */
    async encrypt(sessionKeyAlgorithm, key, config$1 = config) {
        this.cipherAlgorithm = sessionKeyAlgorithm;
        const { ivLength } = getAEADMode(this.aeadAlgorithm, true);
        this.iv = getRandomBytes(ivLength); // generate new random IV
        this.chunkSizeByte = config$1.aeadChunkSizeByte;
        const data = this.packets.write();
        this.encrypted = await runAEAD(this, 'encrypt', key, data);
    }
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Public-Key Encrypted Session Key Packets (Tag 1)
 *
 * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:
 * A Public-Key Encrypted Session Key packet holds the session key
 * used to encrypt a message. Zero or more Public-Key Encrypted Session Key
 * packets and/or Symmetric-Key Encrypted Session Key packets may precede a
 * Symmetrically Encrypted Data Packet, which holds an encrypted message. The
 * message is encrypted with the session key, and the session key is itself
 * encrypted and stored in the Encrypted Session Key packet(s). The
 * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted
 * Session Key packet for each OpenPGP key to which the message is encrypted.
 * The recipient of the message finds a session key that is encrypted to their
 * public key, decrypts the session key, and then uses the session key to
 * decrypt the message.
 */
class PublicKeyEncryptedSessionKeyPacket {
    static get tag() {
        return enums.packet.publicKeyEncryptedSessionKey;
    }
    constructor() {
        this.version = null;
        // For version 3, but also used internally by v6 in e.g. `getEncryptionKeyIDs()`
        this.publicKeyID = new KeyID();
        // For version 6:
        this.publicKeyVersion = null;
        this.publicKeyFingerprint = null;
        // For all versions:
        /** @type {enums.publicKey | null} */
        this.publicKeyAlgorithm = null;
        this.sessionKey = null;
        /**
         * Algorithm to encrypt the message with
         * @type {enums.symmetric}
         */
        this.sessionKeyAlgorithm = null;
        /** @type {Object} */
        this.encrypted = {};
    }
    static fromObject({ version, encryptionKeyPacket, anonymousRecipient, sessionKey, sessionKeyAlgorithm }) {
        const pkesk = new PublicKeyEncryptedSessionKeyPacket();
        if (version !== 3 && version !== 6) {
            throw new Error('Unsupported PKESK version');
        }
        pkesk.version = version;
        if (version === 6) {
            pkesk.publicKeyVersion = anonymousRecipient ? null : encryptionKeyPacket.version;
            pkesk.publicKeyFingerprint = anonymousRecipient ? null : encryptionKeyPacket.getFingerprintBytes();
        }
        pkesk.publicKeyID = anonymousRecipient ? KeyID.wildcard() : encryptionKeyPacket.getKeyID();
        pkesk.publicKeyAlgorithm = encryptionKeyPacket.algorithm;
        pkesk.sessionKey = sessionKey;
        pkesk.sessionKeyAlgorithm = sessionKeyAlgorithm;
        return pkesk;
    }
    /**
     * Parsing function for a publickey encrypted session key packet (tag 1).
     *
     * @param {Uint8Array} bytes - Payload of a tag 1 packet
     */
    read(bytes) {
        let offset = 0;
        this.version = bytes[offset++];
        if (this.version !== 3 && this.version !== 6) {
            throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);
        }
        if (this.version === 6) {
            // A one-octet size of the following two fields:
            // - A one octet key version number.
            // - The fingerprint of the public key or subkey to which the session key is encrypted.
            // The size may also be zero.
            const versionAndFingerprintLength = bytes[offset++];
            if (versionAndFingerprintLength) {
                this.publicKeyVersion = bytes[offset++];
                const fingerprintLength = versionAndFingerprintLength - 1;
                this.publicKeyFingerprint = bytes.subarray(offset, offset + fingerprintLength);
                offset += fingerprintLength;
                if (this.publicKeyVersion >= 5) {
                    // For v5/6 the Key ID is the high-order 64 bits of the fingerprint.
                    this.publicKeyID.read(this.publicKeyFingerprint);
                }
                else {
                    // For v4 The Key ID is the low-order 64 bits of the fingerprint.
                    this.publicKeyID.read(this.publicKeyFingerprint.subarray(-8));
                }
            }
            else {
                // The size may also be zero, and the key version and
                // fingerprint omitted for an "anonymous recipient"
                this.publicKeyID = KeyID.wildcard();
            }
        }
        else {
            offset += this.publicKeyID.read(bytes.subarray(offset, offset + 8));
        }
        this.publicKeyAlgorithm = bytes[offset++];
        this.encrypted = parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(offset));
        if (this.publicKeyAlgorithm === enums.publicKey.x25519 || this.publicKeyAlgorithm === enums.publicKey.x448) {
            if (this.version === 3) {
                this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm);
            }
            else if (this.encrypted.C.algorithm !== null) {
                throw new Error('Unexpected cleartext symmetric algorithm');
            }
        }
    }
    /**
     * Create a binary representation of a tag 1 packet
     *
     * @returns {Uint8Array} The Uint8Array representation.
     */
    write() {
        const arr = [
            new Uint8Array([this.version])
        ];
        if (this.version === 6) {
            if (this.publicKeyFingerprint !== null) {
                arr.push(new Uint8Array([
                    this.publicKeyFingerprint.length + 1,
                    this.publicKeyVersion
                ]));
                arr.push(this.publicKeyFingerprint);
            }
            else {
                arr.push(new Uint8Array([0]));
            }
        }
        else {
            arr.push(this.publicKeyID.write());
        }
        arr.push(new Uint8Array([this.publicKeyAlgorithm]), serializeParams(this.publicKeyAlgorithm, this.encrypted));
        return util.concatUint8Array(arr);
    }
    /**
     * Encrypt session key packet
     * @param {PublicKeyPacket} key - Public key
     * @throws {Error} if encryption failed
     * @async
     */
    async encrypt(key) {
        const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);
        // No symmetric encryption algorithm identifier is passed to the public-key algorithm for a
        // v6 PKESK packet, as it is included in the v2 SEIPD packet.
        const sessionKeyAlgorithm = this.version === 3 ? this.sessionKeyAlgorithm : null;
        const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes();
        const encoded = encodeSessionKey(this.version, algo, sessionKeyAlgorithm, this.sessionKey);
        this.encrypted = await publicKeyEncrypt(algo, sessionKeyAlgorithm, key.publicParams, encoded, fingerprint);
    }
    /**
     * Decrypts the session key (only for public key encrypted session key packets (tag 1)
     * @param {SecretKeyPacket} key - decrypted private key
     * @param {Object} [randomSessionKey] - Bogus session key to use in case of sensitive decryption error, or if the decrypted session key is of a different type/size.
     *                                      This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric }
     * @throws {Error} if decryption failed, unless `randomSessionKey` is given
     * @async
     */
    async decrypt(key, randomSessionKey) {
        // check that session key algo matches the secret key algo
        if (this.publicKeyAlgorithm !== key.algorithm) {
            throw new Error('Decryption error');
        }
        const randomPayload = randomSessionKey ?
            encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) :
            null;
        const fingerprint = key.version === 5 ? key.getFingerprintBytes().subarray(0, 20) : key.getFingerprintBytes();
        const decryptedData = await publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, fingerprint, randomPayload);
        const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey);
        if (this.version === 3) {
            // v3 Montgomery curves have cleartext cipher algo
            const hasEncryptedAlgo = this.publicKeyAlgorithm !== enums.publicKey.x25519 && this.publicKeyAlgorithm !== enums.publicKey.x448;
            this.sessionKeyAlgorithm = hasEncryptedAlgo ? sessionKeyAlgorithm : this.sessionKeyAlgorithm;
            if (sessionKey.length !== getCipherParams(this.sessionKeyAlgorithm).keySize) {
                throw new Error('Unexpected session key size');
            }
        }
        this.sessionKey = sessionKey;
    }
}
function encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) {
    switch (keyAlgo) {
        case enums.publicKey.rsaEncrypt:
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.elgamal:
        case enums.publicKey.ecdh:
            // add checksum
            return util.concatUint8Array([
                new Uint8Array(version === 6 ? [] : [cipherAlgo]),
                sessionKeyData,
                util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8))
            ]);
        case enums.publicKey.x25519:
        case enums.publicKey.x448:
            return sessionKeyData;
        default:
            throw new Error('Unsupported public key algorithm');
    }
}
function decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) {
    switch (keyAlgo) {
        case enums.publicKey.rsaEncrypt:
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.elgamal:
        case enums.publicKey.ecdh: {
            // verify checksum in constant time
            const result = decryptedData.subarray(0, decryptedData.length - 2);
            const checksum = decryptedData.subarray(decryptedData.length - 2);
            const computedChecksum = util.writeChecksum(result.subarray(result.length % 8));
            const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1];
            const decryptedSessionKey = version === 6 ?
                { sessionKeyAlgorithm: null, sessionKey: result } :
                { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) };
            if (randomSessionKey) {
                // We must not leak info about the validity of the decrypted checksum or cipher algo.
                // The decrypted session key must be of the same algo and size as the random session key, otherwise we discard it and use the random data.
                const isValidPayload = isValidChecksum &
                    decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm &
                    decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length;
                return {
                    sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey),
                    sessionKeyAlgorithm: version === 6 ? null : util.selectUint8(isValidPayload, decryptedSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm)
                };
            }
            else {
                const isValidPayload = isValidChecksum && (version === 6 || enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm));
                if (isValidPayload) {
                    return decryptedSessionKey;
                }
                else {
                    throw new Error('Decryption error');
                }
            }
        }
        case enums.publicKey.x25519:
        case enums.publicKey.x448:
            return {
                sessionKeyAlgorithm: null,
                sessionKey: decryptedData
            };
        default:
            throw new Error('Unsupported public key algorithm');
    }
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Symmetric-Key Encrypted Session Key Packets (Tag 3)
 *
 * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:
 * The Symmetric-Key Encrypted Session Key packet holds the
 * symmetric-key encryption of a session key used to encrypt a message.
 * Zero or more Public-Key Encrypted Session Key packets and/or
 * Symmetric-Key Encrypted Session Key packets may precede a
 * Symmetrically Encrypted Data packet that holds an encrypted message.
 * The message is encrypted with a session key, and the session key is
 * itself encrypted and stored in the Encrypted Session Key packet or
 * the Symmetric-Key Encrypted Session Key packet.
 */
class SymEncryptedSessionKeyPacket {
    static get tag() {
        return enums.packet.symEncryptedSessionKey;
    }
    /**
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     */
    constructor(config$1 = config) {
        this.version = config$1.aeadProtect ? 6 : 4;
        this.sessionKey = null;
        /**
         * Algorithm to encrypt the session key with
         * @type {enums.symmetric}
         */
        this.sessionKeyEncryptionAlgorithm = null;
        /**
         * Algorithm to encrypt the message with
         * @type {enums.symmetric}
         */
        this.sessionKeyAlgorithm = null;
        /**
         * AEAD mode to encrypt the session key with (if AEAD protection is enabled)
         * @type {enums.aead}
         */
        this.aeadAlgorithm = enums.write(enums.aead, config$1.preferredAEADAlgorithm);
        this.encrypted = null;
        this.s2k = null;
        this.iv = null;
    }
    /**
     * Parsing function for a symmetric encrypted session key packet (tag 3).
     *
     * @param {Uint8Array} bytes - Payload of a tag 3 packet
     */
    read(bytes) {
        let offset = 0;
        // A one-octet version number with value 4, 5 or 6.
        this.version = bytes[offset++];
        if (this.version !== 4 && this.version !== 5 && this.version !== 6) {
            throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);
        }
        if (this.version === 6) {
            // A one-octet scalar octet count of the following 5 fields.
            offset++;
        }
        // A one-octet number describing the symmetric algorithm used.
        const algo = bytes[offset++];
        if (this.version >= 5) {
            // A one-octet AEAD algorithm.
            this.aeadAlgorithm = bytes[offset++];
            if (this.version === 6) {
                // A one-octet scalar octet count of the following field.
                offset++;
            }
        }
        // A string-to-key (S2K) specifier, length as defined above.
        const s2kType = bytes[offset++];
        this.s2k = newS2KFromType(s2kType);
        offset += this.s2k.read(bytes.subarray(offset, bytes.length));
        if (this.version >= 5) {
            const mode = getAEADMode(this.aeadAlgorithm, true);
            // A starting initialization vector of size specified by the AEAD
            // algorithm.
            this.iv = bytes.subarray(offset, offset += mode.ivLength);
        }
        // The encrypted session key itself, which is decrypted with the
        // string-to-key object. This is optional in version 4.
        if (this.version >= 5 || offset < bytes.length) {
            this.encrypted = bytes.subarray(offset, bytes.length);
            this.sessionKeyEncryptionAlgorithm = algo;
        }
        else {
            this.sessionKeyAlgorithm = algo;
        }
    }
    /**
     * Create a binary representation of a tag 3 packet
     *
     * @returns {Uint8Array} The Uint8Array representation.
    */
    write() {
        const algo = this.encrypted === null ?
            this.sessionKeyAlgorithm :
            this.sessionKeyEncryptionAlgorithm;
        let bytes;
        const s2k = this.s2k.write();
        if (this.version === 6) {
            const s2kLen = s2k.length;
            const fieldsLen = 3 + s2kLen + this.iv.length;
            bytes = util.concatUint8Array([new Uint8Array([this.version, fieldsLen, algo, this.aeadAlgorithm, s2kLen]), s2k, this.iv, this.encrypted]);
        }
        else if (this.version === 5) {
            bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), s2k, this.iv, this.encrypted]);
        }
        else {
            bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), s2k]);
            if (this.encrypted !== null) {
                bytes = util.concatUint8Array([bytes, this.encrypted]);
            }
        }
        return bytes;
    }
    /**
     * Decrypts the session key with the given passphrase
     * @param {String} passphrase - The passphrase in string form
     * @param {Object} config
     * @throws {Error} if decryption was not successful
     * @async
     */
    async decrypt(passphrase, config$1 = config) {
        const algo = this.sessionKeyEncryptionAlgorithm !== null ?
            this.sessionKeyEncryptionAlgorithm :
            this.sessionKeyAlgorithm;
        const { blockSize, keySize } = getCipherParams(algo);
        const key = await this.s2k.produceKey(passphrase, keySize, config$1);
        if (this.version >= 5) {
            const mode = getAEADMode(this.aeadAlgorithm, true);
            const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);
            const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key;
            const modeInstance = await mode(algo, encryptionKey);
            this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);
        }
        else if (this.encrypted !== null) {
            const decrypted = await decrypt$1(algo, key, this.encrypted, new Uint8Array(blockSize));
            this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]);
            this.sessionKey = decrypted.subarray(1, decrypted.length);
            if (this.sessionKey.length !== getCipherParams(this.sessionKeyAlgorithm).keySize) {
                throw new Error('Unexpected session key size');
            }
        }
        else {
            // session key size is checked as part of SEIPDv2 decryption, where we know the expected symmetric algo
            this.sessionKey = key;
        }
    }
    /**
     * Encrypts the session key with the given passphrase
     * @param {String} passphrase - The passphrase in string form
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @throws {Error} if encryption was not successful
     * @async
     */
    async encrypt(passphrase, config$1 = config) {
        const algo = this.sessionKeyEncryptionAlgorithm !== null ?
            this.sessionKeyEncryptionAlgorithm :
            this.sessionKeyAlgorithm;
        this.sessionKeyEncryptionAlgorithm = algo;
        this.s2k = newS2KFromConfig(config$1);
        this.s2k.generateSalt();
        const { blockSize, keySize } = getCipherParams(algo);
        const key = await this.s2k.produceKey(passphrase, keySize, config$1);
        if (this.sessionKey === null) {
            this.sessionKey = generateSessionKey$1(this.sessionKeyAlgorithm);
        }
        if (this.version >= 5) {
            const mode = getAEADMode(this.aeadAlgorithm);
            this.iv = getRandomBytes(mode.ivLength); // generate new random IV
            const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);
            const encryptionKey = this.version === 6 ? await computeHKDF(enums.hash.sha256, key, new Uint8Array(), adata, keySize) : key;
            const modeInstance = await mode(algo, encryptionKey);
            this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata);
        }
        else {
            const toEncrypt = util.concatUint8Array([
                new Uint8Array([this.sessionKeyAlgorithm]),
                this.sessionKey
            ]);
            this.encrypted = await encrypt$1(algo, key, toEncrypt, new Uint8Array(blockSize));
        }
    }
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Implementation of the Key Material Packet (Tag 5,6,7,14)
 *
 * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:
 * A key material packet contains all the information about a public or
 * private key.  There are four variants of this packet type, and two
 * major versions.
 *
 * A Public-Key packet starts a series of packets that forms an OpenPGP
 * key (sometimes called an OpenPGP certificate).
 */
class PublicKeyPacket {
    static get tag() {
        return enums.packet.publicKey;
    }
    /**
     * @param {Date} [date] - Creation date
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     */
    constructor(date = new Date(), config$1 = config) {
        /**
         * Packet version
         * @type {Integer}
         */
        this.version = config$1.v6Keys ? 6 : 4;
        /**
         * Key creation date.
         * @type {Date}
         */
        this.created = util.normalizeDate(date);
        /**
         * Public key algorithm.
         * @type {enums.publicKey}
         */
        this.algorithm = null;
        /**
         * Algorithm specific public params
         * @type {Object}
         */
        this.publicParams = null;
        /**
         * Time until expiration in days (V3 only)
         * @type {Integer}
         */
        this.expirationTimeV3 = 0;
        /**
         * Fingerprint bytes
         * @type {Uint8Array}
         */
        this.fingerprint = null;
        /**
         * KeyID
         * @type {module:type/keyid~KeyID}
         */
        this.keyID = null;
    }
    /**
     * Create a PublicKeyPacket from a SecretKeyPacket
     * @param {SecretKeyPacket} secretKeyPacket - key packet to convert
     * @returns {PublicKeyPacket} public key packet
     * @static
     */
    static fromSecretKeyPacket(secretKeyPacket) {
        const keyPacket = new PublicKeyPacket();
        const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;
        keyPacket.version = version;
        keyPacket.created = created;
        keyPacket.algorithm = algorithm;
        keyPacket.publicParams = publicParams;
        keyPacket.keyID = keyID;
        keyPacket.fingerprint = fingerprint;
        return keyPacket;
    }
    /**
     * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats}
     * @param {Uint8Array} bytes - Input array to read the packet from
     * @returns {Promise<number>} The number of bytes read from `bytes`
     * @async
     */
    async read(bytes, config$1 = config) {
        let pos = 0;
        // A one-octet version number (4, 5 or 6).
        this.version = bytes[pos++];
        if (this.version === 5 && !config$1.enableParsingV5Entities) {
            throw new UnsupportedError('Support for parsing v5 entities is disabled; turn on `config.enableParsingV5Entities` if needed');
        }
        if (this.version === 4 || this.version === 5 || this.version === 6) {
            // - A four-octet number denoting the time that the key was created.
            this.created = util.readDate(bytes.subarray(pos, pos + 4));
            pos += 4;
            // - A one-octet number denoting the public-key algorithm of this key.
            this.algorithm = bytes[pos++];
            if (this.version >= 5) {
                // - A four-octet scalar octet count for the following key material.
                pos += 4;
            }
            // - A series of values comprising the key material.
            const { read, publicParams } = parsePublicKeyParams(this.algorithm, bytes.subarray(pos));
            // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures.
            // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs.
            if (this.version === 6 &&
                publicParams.oid && (publicParams.oid.getName() === enums.curve.curve25519Legacy ||
                publicParams.oid.getName() === enums.curve.ed25519Legacy)) {
                throw new Error('Legacy curve25519 cannot be used with v6 keys');
            }
            this.publicParams = publicParams;
            pos += read;
            // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor
            await this.computeFingerprintAndKeyID();
            return pos;
        }
        throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);
    }
    /**
     * Creates an OpenPGP public key packet for the given key.
     * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.
     */
    write() {
        const arr = [];
        // Version
        arr.push(new Uint8Array([this.version]));
        arr.push(util.writeDate(this.created));
        // A one-octet number denoting the public-key algorithm of this key
        arr.push(new Uint8Array([this.algorithm]));
        const params = serializeParams(this.algorithm, this.publicParams);
        if (this.version >= 5) {
            // A four-octet scalar octet count for the following key material
            arr.push(util.writeNumber(params.length, 4));
        }
        // Algorithm-specific params
        arr.push(params);
        return util.concatUint8Array(arr);
    }
    /**
     * Write packet in order to be hashed; either for a signature or a fingerprint
     * @param {Integer} version - target version of signature or key
     */
    writeForHash(version) {
        const bytes = this.writePublicKey();
        const versionOctet = 0x95 + version;
        const lengthOctets = version >= 5 ? 4 : 2;
        return util.concatUint8Array([new Uint8Array([versionOctet]), util.writeNumber(bytes.length, lengthOctets), bytes]);
    }
    /**
     * Check whether secret-key data is available in decrypted form. Returns null for public keys.
     * @returns {Boolean|null}
     */
    isDecrypted() {
        return null;
    }
    /**
     * Returns the creation time of the key
     * @returns {Date}
     */
    getCreationTime() {
        return this.created;
    }
    /**
     * Return the key ID of the key
     * @returns {module:type/keyid~KeyID} The 8-byte key ID
     */
    getKeyID() {
        return this.keyID;
    }
    /**
     * Computes and set the key ID and fingerprint of the key
     * @async
     */
    async computeFingerprintAndKeyID() {
        await this.computeFingerprint();
        this.keyID = new KeyID();
        if (this.version >= 5) {
            this.keyID.read(this.fingerprint.subarray(0, 8));
        }
        else if (this.version === 4) {
            this.keyID.read(this.fingerprint.subarray(12, 20));
        }
        else {
            throw new Error('Unsupported key version');
        }
    }
    /**
     * Computes and set the fingerprint of the key
     */
    async computeFingerprint() {
        const toHash = this.writeForHash(this.version);
        if (this.version >= 5) {
            this.fingerprint = await computeDigest(enums.hash.sha256, toHash);
        }
        else if (this.version === 4) {
            this.fingerprint = await computeDigest(enums.hash.sha1, toHash);
        }
        else {
            throw new Error('Unsupported key version');
        }
    }
    /**
     * Returns the fingerprint of the key, as an array of bytes
     * @returns {Uint8Array} A Uint8Array containing the fingerprint
     */
    getFingerprintBytes() {
        return this.fingerprint;
    }
    /**
     * Calculates and returns the fingerprint of the key, as a string
     * @returns {String} A string containing the fingerprint in lowercase hex
     */
    getFingerprint() {
        return util.uint8ArrayToHex(this.getFingerprintBytes());
    }
    /**
     * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint
     * @returns {Boolean} Whether the two keys have the same version and public key data.
     */
    hasSameFingerprintAs(other) {
        return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());
    }
    /**
     * Returns algorithm information
     * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.
     */
    getAlgorithmInfo() {
        const result = {};
        result.algorithm = enums.read(enums.publicKey, this.algorithm);
        // RSA, DSA or ElGamal public modulo
        const modulo = this.publicParams.n || this.publicParams.p;
        if (modulo) {
            result.bits = util.uint8ArrayBitLength(modulo);
        }
        else if (this.publicParams.oid) {
            result.curve = this.publicParams.oid.getName();
        }
        return result;
    }
}
/**
 * Alias of read()
 * @see PublicKeyPacket#read
 */
// eslint-disable-next-line @typescript-eslint/unbound-method
PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;
/**
 * Alias of write()
 * @see PublicKeyPacket#write
 */
// eslint-disable-next-line @typescript-eslint/unbound-method
PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// A SE packet can contain the following packet types
const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([
    LiteralDataPacket,
    CompressedDataPacket,
    OnePassSignaturePacket,
    SignaturePacket
]);
/**
 * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)
 *
 * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:
 * The Symmetrically Encrypted Data packet contains data encrypted with a
 * symmetric-key algorithm. When it has been decrypted, it contains other
 * packets (usually a literal data packet or compressed data packet, but in
 * theory other Symmetrically Encrypted Data packets or sequences of packets
 * that form whole OpenPGP messages).
 */
class SymmetricallyEncryptedDataPacket {
    static get tag() {
        return enums.packet.symmetricallyEncryptedData;
    }
    constructor() {
        /**
         * Encrypted secret-key data
         */
        this.encrypted = null;
        /**
         * Decrypted packets contained within.
         * @type {PacketList}
         */
        this.packets = null;
    }
    read(bytes) {
        this.encrypted = bytes;
    }
    write() {
        return this.encrypted;
    }
    /**
     * Decrypt the symmetrically-encrypted packet data
     * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
     * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use
     * @param {Uint8Array} key - The key of cipher blocksize length to be used
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
  
     * @throws {Error} if decryption was not successful
     * @async
     */
    async decrypt(sessionKeyAlgorithm, key, config$1 = config) {
        // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error
        if (!config$1.allowUnauthenticatedMessages) {
            throw new Error('Message is not authenticated.');
        }
        const { blockSize } = getCipherParams(sessionKeyAlgorithm);
        const encrypted = await readToEnd(clone(this.encrypted));
        const decrypted = await decrypt$1(sessionKeyAlgorithm, key, encrypted.subarray(blockSize + 2), encrypted.subarray(2, blockSize + 2));
        // Decrypting a Symmetrically Encrypted Data packet MUST yield a valid OpenPGP Message.
        // But due to the lack of authentication over the decrypted data,
        // we do not run any grammarValidator, to avoid enabling a decryption oracle
        // (plus, there is probably a higher chance that these messages have an expected structure).
        this.packets = await PacketList.fromBinary(decrypted, allowedPackets$2, config$1);
    }
    /**
     * Encrypt the symmetrically-encrypted packet data
     * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
     * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use
     * @param {Uint8Array} key - The key of cipher blocksize length to be used
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @throws {Error} if encryption was not successful
     * @async
     */
    async encrypt(sessionKeyAlgorithm, key, config$1 = config) {
        const data = this.packets.write();
        const { blockSize } = getCipherParams(sessionKeyAlgorithm);
        const prefix = await getPrefixRandom(sessionKeyAlgorithm);
        const FRE = await encrypt$1(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize));
        const ciphertext = await encrypt$1(sessionKeyAlgorithm, key, data, FRE.subarray(2));
        this.encrypted = util.concat([FRE, ciphertext]);
    }
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Implementation of the strange "Marker packet" (Tag 10)
 *
 * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:
 * An experimental version of PGP used this packet as the Literal
 * packet, but no released version of PGP generated Literal packets with this
 * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as
 * the Marker packet.
 *
 * The body of this packet consists of:
 *   The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8).
 *
 * Such a packet MUST be ignored when received. It may be placed at the
 * beginning of a message that uses features not available in PGP
 * version 2.6 in order to cause that version to report that newer
 * software is necessary to process the message.
 */
class MarkerPacket {
    static get tag() {
        return enums.packet.marker;
    }
    /**
     * Parsing function for a marker data packet (tag 10).
     * @param {Uint8Array} bytes - Payload of a tag 10 packet
     * @returns {Boolean} whether the packet payload contains "PGP"
     */
    read(bytes) {
        if (bytes[0] === 0x50 && // P
            bytes[1] === 0x47 && // G
            bytes[2] === 0x50) { // P
            return true;
        }
        return false;
    }
    write() {
        return new Uint8Array([0x50, 0x47, 0x50]);
    }
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * A Public-Subkey packet (tag 14) has exactly the same format as a
 * Public-Key packet, but denotes a subkey.  One or more subkeys may be
 * associated with a top-level key.  By convention, the top-level key
 * provides signature services, and the subkeys provide encryption
 * services.
 * @extends PublicKeyPacket
 */
class PublicSubkeyPacket extends PublicKeyPacket {
    static get tag() {
        return enums.packet.publicSubkey;
    }
    /**
     * @param {Date} [date] - Creation date
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     */
    constructor(date, config) {
        super(date, config);
    }
    /**
     * Create a PublicSubkeyPacket from a SecretSubkeyPacket
     * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert
     * @returns {SecretSubkeyPacket} public key packet
     * @static
     */
    static fromSecretSubkeyPacket(secretSubkeyPacket) {
        const keyPacket = new PublicSubkeyPacket();
        const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;
        keyPacket.version = version;
        keyPacket.created = created;
        keyPacket.algorithm = algorithm;
        keyPacket.publicParams = publicParams;
        keyPacket.keyID = keyID;
        keyPacket.fingerprint = fingerprint;
        return keyPacket;
    }
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Implementation of the User Attribute Packet (Tag 17)
 *
 * The User Attribute packet is a variation of the User ID packet.  It
 * is capable of storing more types of data than the User ID packet,
 * which is limited to text.  Like the User ID packet, a User Attribute
 * packet may be certified by the key owner ("self-signed") or any other
 * key owner who cares to certify it.  Except as noted, a User Attribute
 * packet may be used anywhere that a User ID packet may be used.
 *
 * While User Attribute packets are not a required part of the OpenPGP
 * standard, implementations SHOULD provide at least enough
 * compatibility to properly handle a certification signature on the
 * User Attribute packet.  A simple way to do this is by treating the
 * User Attribute packet as a User ID packet with opaque contents, but
 * an implementation may use any method desired.
 */
class UserAttributePacket {
    static get tag() {
        return enums.packet.userAttribute;
    }
    constructor() {
        this.attributes = [];
    }
    /**
     * parsing function for a user attribute packet (tag 17).
     * @param {Uint8Array} input - Payload of a tag 17 packet
     */
    read(bytes) {
        let i = 0;
        while (i < bytes.length) {
            const len = readSimpleLength(bytes.subarray(i, bytes.length));
            i += len.offset;
            this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));
            i += len.len;
        }
    }
    /**
     * Creates a binary representation of the user attribute packet
     * @returns {Uint8Array} String representation.
     */
    write() {
        const arr = [];
        for (let i = 0; i < this.attributes.length; i++) {
            arr.push(writeSimpleLength(this.attributes[i].length));
            arr.push(util.stringToUint8Array(this.attributes[i]));
        }
        return util.concatUint8Array(arr);
    }
    /**
     * Compare for equality
     * @param {UserAttributePacket} usrAttr
     * @returns {Boolean} True if equal.
     */
    equals(usrAttr) {
        if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {
            return false;
        }
        return this.attributes.every(function (attr, index) {
            return attr === usrAttr.attributes[index];
        });
    }
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * A Secret-Key packet contains all the information that is found in a
 * Public-Key packet, including the public-key material, but also
 * includes the secret-key material after all the public-key fields.
 * @extends PublicKeyPacket
 */
class SecretKeyPacket extends PublicKeyPacket {
    static get tag() {
        return enums.packet.secretKey;
    }
    /**
     * @param {Date} [date] - Creation date
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     */
    constructor(date = new Date(), config$1 = config) {
        super(date, config$1);
        /**
         * Secret-key data
         */
        this.keyMaterial = null;
        /**
         * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.
         */
        this.isEncrypted = null;
        /**
         * S2K usage
         * @type {number}
         */
        this.s2kUsage = 0;
        /**
         * S2K object
         * @type {type/s2k}
         */
        this.s2k = null;
        /**
         * Symmetric algorithm to encrypt the key with
         * @type {enums.symmetric}
         */
        this.symmetric = null;
        /**
         * AEAD algorithm to encrypt the key with (if AEAD protection is enabled)
         * @type {enums.aead}
         */
        this.aead = null;
        /**
         * Whether the key is encrypted using the legacy AEAD format proposal from RFC4880bis
         * (i.e. it was encrypted with the flag `config.aeadProtect` in OpenPGP.js v5 or older).
         * This value is only relevant to know how to decrypt the key:
         * if AEAD is enabled, a v4 key is always re-encrypted using the standard AEAD mechanism.
         * @type {Boolean}
         * @private
         */
        this.isLegacyAEAD = null;
        /**
         * Decrypted private parameters, referenced by name
         * @type {Object}
         */
        this.privateParams = null;
        /**
         * `true` for keys whose integrity is already confirmed, based on
         * the AEAD encryption mechanism
         * @type {Boolean}
         * @private
         */
        this.usedModernAEAD = null;
    }
    // 5.5.3.  Secret-Key Packet Formats
    /**
     * Internal parser for private keys as specified in
     * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}
     * @param {Uint8Array} bytes - Input string to read the packet from
     * @async
     */
    async read(bytes, config$1 = config) {
        // - A Public-Key or Public-Subkey packet, as described above.
        let i = await this.readPublicKey(bytes, config$1);
        const startOfSecretKeyData = i;
        // - One octet indicating string-to-key usage conventions.  Zero
        //   indicates that the secret-key data is not encrypted.  255 or 254
        //   indicates that a string-to-key specifier is being given.  Any
        //   other value is a symmetric-key encryption algorithm identifier.
        this.s2kUsage = bytes[i++];
        // - Only for a version 5 packet, a one-octet scalar octet count of
        //   the next 4 optional fields.
        if (this.version === 5) {
            i++;
        }
        // - Only for a version 6 packet where the secret key material is
        //   encrypted (that is, where the previous octet is not zero), a one-
        //   octet scalar octet count of the cumulative length of all the
        //   following optional string-to-key parameter fields.
        if (this.version === 6 && this.s2kUsage) {
            i++;
        }
        try {
            // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
            //   one-octet symmetric encryption algorithm.
            if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {
                this.symmetric = bytes[i++];
                // - [Optional] If string-to-key usage octet was 253, a one-octet
                //   AEAD algorithm.
                if (this.s2kUsage === 253) {
                    this.aead = bytes[i++];
                }
                // - [Optional] Only for a version 6 packet, and if string-to-key usage
                //   octet was 255, 254, or 253, an one-octet count of the following field.
                if (this.version === 6) {
                    i++;
                }
                // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
                //   string-to-key specifier.  The length of the string-to-key
                //   specifier is implied by its type, as described above.
                const s2kType = bytes[i++];
                this.s2k = newS2KFromType(s2kType);
                i += this.s2k.read(bytes.subarray(i, bytes.length));
                if (this.s2k.type === 'gnu-dummy') {
                    return;
                }
            }
            else if (this.s2kUsage) {
                this.symmetric = this.s2kUsage;
            }
            if (this.s2kUsage) {
                // OpenPGP.js up to v5 used to support encrypting v4 keys using AEAD as specified by draft RFC4880bis (https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-5.5.3-3.5).
                // This legacy format is incompatible, but fundamentally indistinguishable, from that of the crypto-refresh for v4 keys (v5 keys are always in legacy format).
                // While parsing the key may succeed (if IV and AES block sizes match), key decryption will always
                // fail if the key was parsed according to the wrong format, since the keys are processed differently.
                // Thus, for v4 keys, we rely on the caller to instruct us to process the key as legacy, via config flag.
                this.isLegacyAEAD = this.s2kUsage === 253 && (this.version === 5 || (this.version === 4 && config$1.parseAEADEncryptedV4KeysAsLegacy));
                // - crypto-refresh: If string-to-key usage octet was 255, 254 [..], an initialization vector (IV)
                // of the same length as the cipher's block size.
                // - RFC4880bis (v5 keys, regardless of AEAD): an Initial Vector (IV) of the same length as the
                //   cipher's block size. If string-to-key usage octet was 253 the IV is used as the nonce for the AEAD algorithm.
                // If the AEAD algorithm requires a shorter nonce, the high-order bits of the IV are used and the remaining bits MUST be zero
                if (this.s2kUsage !== 253 || this.isLegacyAEAD) {
                    this.iv = bytes.subarray(i, i + getCipherParams(this.symmetric).blockSize);
                    this.usedModernAEAD = false;
                }
                else {
                    // crypto-refresh: If string-to-key usage octet was 253 (that is, the secret data is AEAD-encrypted),
                    // an initialization vector (IV) of size specified by the AEAD algorithm (see Section 5.13.2), which
                    // is used as the nonce for the AEAD algorithm.
                    this.iv = bytes.subarray(i, i + getAEADMode(this.aead).ivLength);
                    // the non-legacy AEAD encryption mechanism also authenticates public key params; no need for manual validation.
                    this.usedModernAEAD = true;
                }
                i += this.iv.length;
            }
        }
        catch (e) {
            // if the s2k is unsupported, we still want to support encrypting and verifying with the given key
            if (!this.s2kUsage)
                throw e; // always throw for decrypted keys
            this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData);
            this.isEncrypted = true;
        }
        // - Only for a version 5 packet, a four-octet scalar octet count for
        //   the following key material.
        if (this.version === 5) {
            i += 4;
        }
        // - Plain or encrypted multiprecision integers comprising the secret
        //   key data.  These algorithm-specific fields are as described
        //   below.
        this.keyMaterial = bytes.subarray(i);
        this.isEncrypted = !!this.s2kUsage;
        if (!this.isEncrypted) {
            let cleartext;
            if (this.version === 6) {
                cleartext = this.keyMaterial;
            }
            else {
                cleartext = this.keyMaterial.subarray(0, -2);
                if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {
                    throw new Error('Key checksum mismatch');
                }
            }
            try {
                const { read, privateParams } = parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);
                if (read < cleartext.length) {
                    throw new Error('Error reading MPIs');
                }
                this.privateParams = privateParams;
            }
            catch (err) {
                if (err instanceof UnsupportedError)
                    throw err;
                // avoid throwing potentially sensitive errors
                throw new Error('Error reading MPIs');
            }
        }
    }
    /**
     * Creates an OpenPGP key packet for the given key.
     * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.
     */
    write() {
        const serializedPublicKey = this.writePublicKey();
        if (this.unparseableKeyMaterial) {
            return util.concatUint8Array([
                serializedPublicKey,
                this.unparseableKeyMaterial
            ]);
        }
        const arr = [serializedPublicKey];
        arr.push(new Uint8Array([this.s2kUsage]));
        const optionalFieldsArr = [];
        // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
        //   one- octet symmetric encryption algorithm.
        if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {
            optionalFieldsArr.push(this.symmetric);
            // - [Optional] If string-to-key usage octet was 253, a one-octet
            //   AEAD algorithm.
            if (this.s2kUsage === 253) {
                optionalFieldsArr.push(this.aead);
            }
            const s2k = this.s2k.write();
            // - [Optional] Only for a version 6 packet, and if string-to-key usage
            //   octet was 255, 254, or 253, an one-octet count of the following field.
            if (this.version === 6) {
                optionalFieldsArr.push(s2k.length);
            }
            // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
            //   string-to-key specifier.  The length of the string-to-key
            //   specifier is implied by its type, as described above.
            optionalFieldsArr.push(...s2k);
        }
        // - [Optional] If secret data is encrypted (string-to-key usage octet
        //   not zero), an Initial Vector (IV) of the same length as the
        //   cipher's block size.
        if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {
            optionalFieldsArr.push(...this.iv);
        }
        if (this.version === 5 || (this.version === 6 && this.s2kUsage)) {
            arr.push(new Uint8Array([optionalFieldsArr.length]));
        }
        arr.push(new Uint8Array(optionalFieldsArr));
        if (!this.isDummy()) {
            if (!this.s2kUsage) {
                this.keyMaterial = serializeParams(this.algorithm, this.privateParams);
            }
            if (this.version === 5) {
                arr.push(util.writeNumber(this.keyMaterial.length, 4));
            }
            arr.push(this.keyMaterial);
            if (!this.s2kUsage && this.version !== 6) {
                arr.push(util.writeChecksum(this.keyMaterial));
            }
        }
        return util.concatUint8Array(arr);
    }
    /**
     * Check whether secret-key data is available in decrypted form.
     * Returns false for gnu-dummy keys and null for public keys.
     * @returns {Boolean|null}
     */
    isDecrypted() {
        return this.isEncrypted === false;
    }
    /**
     * Check whether the key includes secret key material.
     * Some secret keys do not include it, and can thus only be used
     * for public-key operations (encryption and verification).
     * Such keys are:
     * - GNU-dummy keys, where the secret material has been stripped away
     * - encrypted keys with unsupported S2K or cipher
     */
    isMissingSecretKeyMaterial() {
        return this.unparseableKeyMaterial !== undefined || this.isDummy();
    }
    /**
     * Check whether this is a gnu-dummy key
     * @returns {Boolean}
     */
    isDummy() {
        return !!(this.s2k && this.s2k.type === 'gnu-dummy');
    }
    /**
     * Remove private key material, converting the key to a dummy one.
     * The resulting key cannot be used for signing/decrypting but can still verify signatures.
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     */
    makeDummy(config$1 = config) {
        if (this.isDummy()) {
            return;
        }
        if (this.isDecrypted()) {
            this.clearPrivateParams();
        }
        delete this.unparseableKeyMaterial;
        this.isEncrypted = null;
        this.keyMaterial = null;
        this.s2k = newS2KFromType(enums.s2k.gnu, config$1);
        this.s2k.algorithm = 0;
        this.s2k.c = 0;
        this.s2k.type = 'gnu-dummy';
        this.s2kUsage = 254;
        this.symmetric = enums.symmetric.aes256;
        this.isLegacyAEAD = null;
        this.usedModernAEAD = null;
    }
    /**
     * Encrypt the payload. By default, we use aes256 and iterated, salted string
     * to key specifier. If the key is in a decrypted state (isEncrypted === false)
     * and the passphrase is empty or undefined, the key will be set as not encrypted.
     * This can be used to remove passphrase protection after calling decrypt().
     * @param {String} passphrase
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @throws {Error} if encryption was not successful
     * @async
     */
    async encrypt(passphrase, config$1 = config) {
        if (this.isDummy()) {
            return;
        }
        if (!this.isDecrypted()) {
            throw new Error('Key packet is already encrypted');
        }
        if (!passphrase) {
            throw new Error('A non-empty passphrase is required for key encryption.');
        }
        this.s2k = newS2KFromConfig(config$1);
        this.s2k.generateSalt();
        const cleartext = serializeParams(this.algorithm, this.privateParams);
        this.symmetric = enums.symmetric.aes256;
        const { blockSize } = getCipherParams(this.symmetric);
        if (config$1.aeadProtect) {
            this.s2kUsage = 253;
            this.aead = config$1.preferredAEADAlgorithm;
            const mode = getAEADMode(this.aead);
            this.isLegacyAEAD = this.version === 5; // v4 is always re-encrypted with standard format instead.
            this.usedModernAEAD = !this.isLegacyAEAD; // legacy AEAD does not guarantee integrity of public key material
            const serializedPacketTag = writeTag(this.constructor.tag);
            const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD, config$1);
            const modeInstance = await mode(this.symmetric, key);
            this.iv = this.isLegacyAEAD ? getRandomBytes(blockSize) : getRandomBytes(mode.ivLength);
            const associateData = this.isLegacyAEAD ?
                new Uint8Array() :
                util.concatUint8Array([serializedPacketTag, this.writePublicKey()]);
            this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), associateData);
        }
        else {
            this.s2kUsage = 254;
            this.usedModernAEAD = false;
            const key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric, undefined, undefined, undefined, config$1);
            this.iv = getRandomBytes(blockSize);
            this.keyMaterial = await encrypt$1(this.symmetric, key, util.concatUint8Array([
                cleartext,
                await computeDigest(enums.hash.sha1, cleartext)
            ]), this.iv);
        }
    }
    /**
     * Decrypts the private key params which are needed to use the key.
     * Successful decryption does not imply key integrity, call validate() to confirm that.
     * {@link SecretKeyPacket.isDecrypted} should be false, as
     * otherwise calls to this function will throw an error.
     * @param {String} passphrase - The passphrase for this private key as string
     * @param {Object} config
     * @throws {Error} if the key is already decrypted, or if decryption was not successful
     * @async
     */
    async decrypt(passphrase, config$1 = config) {
        if (this.isDummy()) {
            return false;
        }
        if (this.unparseableKeyMaterial) {
            throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo');
        }
        if (this.isDecrypted()) {
            throw new Error('Key packet is already decrypted.');
        }
        let key;
        const serializedPacketTag = writeTag(this.constructor.tag); // relevant for AEAD only
        if (this.s2kUsage === 254 || this.s2kUsage === 253) {
            key = await produceEncryptionKey(this.version, this.s2k, passphrase, this.symmetric, this.aead, serializedPacketTag, this.isLegacyAEAD, config$1);
        }
        else if (this.s2kUsage === 255) {
            throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');
        }
        else {
            throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');
        }
        let cleartext;
        if (this.s2kUsage === 253) {
            const mode = getAEADMode(this.aead, true);
            const modeInstance = await mode(this.symmetric, key);
            try {
                const associateData = this.isLegacyAEAD ?
                    new Uint8Array() :
                    util.concatUint8Array([serializedPacketTag, this.writePublicKey()]);
                cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), associateData);
            }
            catch (err) {
                if (err.message === 'Authentication tag mismatch') {
                    throw new Error('Incorrect key passphrase: ' + err.message);
                }
                throw err;
            }
        }
        else {
            const cleartextWithHash = await decrypt$1(this.symmetric, key, this.keyMaterial, this.iv);
            cleartext = cleartextWithHash.subarray(0, -20);
            const hash = await computeDigest(enums.hash.sha1, cleartext);
            if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {
                throw new Error('Incorrect key passphrase');
            }
        }
        try {
            const { privateParams } = parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);
            this.privateParams = privateParams;
        }
        catch {
            throw new Error('Error reading MPIs');
        }
        this.isEncrypted = false;
        this.keyMaterial = null;
        this.s2kUsage = 0;
        this.aead = null;
        this.symmetric = null;
        this.isLegacyAEAD = null;
    }
    /**
     * Checks that the key parameters are consistent
     * @throws {Error} if validation was not successful
     * @async
     */
    async validate() {
        if (this.isDummy()) {
            return;
        }
        if (!this.isDecrypted()) {
            throw new Error('Key is not decrypted');
        }
        if (this.usedModernAEAD) {
            // key integrity confirmed by successful AEAD decryption
            return;
        }
        let validParams;
        try {
            // this can throw if some parameters are undefined
            validParams = await validateParams$1(this.algorithm, this.publicParams, this.privateParams);
        }
        catch {
            validParams = false;
        }
        if (!validParams) {
            throw new Error('Key is invalid');
        }
    }
    async generate(bits, curve) {
        // The deprecated OIDs for Ed25519Legacy and Curve25519Legacy are used in legacy version 4 keys and signatures.
        // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs.
        if (this.version === 6 && ((this.algorithm === enums.publicKey.ecdh && curve === enums.curve.curve25519Legacy) ||
            this.algorithm === enums.publicKey.eddsaLegacy)) {
            throw new Error(`Cannot generate v6 keys of type 'ecc' with curve ${curve}. Generate a key of type 'curve25519' instead`);
        }
        const { privateParams, publicParams } = await generateParams(this.algorithm, bits, curve);
        this.privateParams = privateParams;
        this.publicParams = publicParams;
        this.isEncrypted = false;
    }
    /**
     * Clear private key parameters
     */
    clearPrivateParams() {
        if (this.isMissingSecretKeyMaterial()) {
            return;
        }
        Object.keys(this.privateParams).forEach(name => {
            const param = this.privateParams[name];
            param.fill(0);
            delete this.privateParams[name];
        });
        this.privateParams = null;
        this.isEncrypted = true;
    }
}
/**
 * Derive encryption key
 * @param {Number} keyVersion - key derivation differs for v5 keys
 * @param {module:type/s2k} s2k
 * @param {String} passphrase
 * @param {module:enums.symmetric} cipherAlgo
 * @param {module:enums.aead} [aeadMode] - for AEAD-encrypted keys only (excluding v5)
 * @param {Uint8Array} [serializedPacketTag] - for AEAD-encrypted keys only (excluding v5)
 * @param {Boolean} [isLegacyAEAD] - for AEAD-encrypted keys from RFC4880bis (v4 and v5 only)
 * @param {Object} config
 * @returns encryption key
 * @access private
 */
async function produceEncryptionKey(keyVersion, s2k, passphrase, cipherAlgo, aeadMode, serializedPacketTag, isLegacyAEAD, config) {
    if (s2k.type === 'argon2' && !aeadMode) {
        throw new Error('Using Argon2 S2K without AEAD is not allowed');
    }
    if (s2k.type === 'simple' && keyVersion === 6) {
        throw new Error('Using Simple S2K with version 6 keys is not allowed');
    }
    const { keySize } = getCipherParams(cipherAlgo);
    const derivedKey = await s2k.produceKey(passphrase, keySize, config);
    if (!aeadMode || keyVersion === 5 || isLegacyAEAD) {
        return derivedKey;
    }
    const info = util.concatUint8Array([
        serializedPacketTag,
        new Uint8Array([keyVersion, cipherAlgo, aeadMode])
    ]);
    return computeHKDF(enums.hash.sha256, derivedKey, new Uint8Array(), info, keySize);
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Implementation of the User ID Packet (Tag 13)
 *
 * A User ID packet consists of UTF-8 text that is intended to represent
 * the name and email address of the key holder.  By convention, it
 * includes an RFC 2822 [RFC2822] mail name-addr, but there are no
 * restrictions on its content.  The packet length in the header
 * specifies the length of the User ID.
 */
class UserIDPacket {
    static get tag() {
        return enums.packet.userID;
    }
    constructor() {
        /** A string containing the user id. Usually in the form
         * John Doe <john@example.com>
         * @type {String}
         */
        this.userID = '';
        this.name = '';
        this.email = '';
        this.comment = '';
    }
    /**
     * Create UserIDPacket instance from object
     * @param {Object} userID - Object specifying userID name, email and comment
     * @returns {UserIDPacket}
     * @static
     */
    static fromObject(userID) {
        if (util.isString(userID) ||
            (userID.name && !util.isString(userID.name)) ||
            (userID.email && !util.isEmailAddress(userID.email)) ||
            (userID.comment && !util.isString(userID.comment))) {
            throw new Error('Invalid user ID format');
        }
        const packet = new UserIDPacket();
        Object.assign(packet, userID);
        const components = [];
        if (packet.name)
            components.push(packet.name);
        if (packet.comment)
            components.push(`(${packet.comment})`);
        if (packet.email)
            components.push(`<${packet.email}>`);
        packet.userID = components.join(' ');
        return packet;
    }
    /**
     * Parsing function for a user id packet (tag 13).
     * @param {Uint8Array} input - Payload of a tag 13 packet
     */
    read(bytes, config$1 = config) {
        const userID = util.decodeUTF8(bytes);
        if (userID.length > config$1.maxUserIDLength) {
            throw new Error('User ID string is too long');
        }
        /**
         * We support the conventional cases described in https://www.ietf.org/id/draft-dkg-openpgp-userid-conventions-00.html#section-4.1,
         * as well comments placed between the name (if present) and the bracketed email address:
         * - name (comment) <email>
         * - email
         * In the first case, the `email` is the only required part, and it must contain the `@` symbol.
         * The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`,
         * since they interfere with `comment` parsing.
         */
        const isValidEmail = str => /^[^\s@]+@[^\s@]+$/.test(str); // enforce single @ and no whitespace
        const firstBracket = userID.indexOf('<');
        const lastBracket = userID.lastIndexOf('>');
        if (firstBracket !== -1 &&
            lastBracket !== -1 &&
            lastBracket > firstBracket) {
            const potentialEmail = userID.substring(firstBracket + 1, lastBracket);
            if (isValidEmail(potentialEmail)) {
                this.email = potentialEmail;
                const beforeEmail = userID.substring(0, firstBracket).trim();
                const firstParen = beforeEmail.indexOf('(');
                const lastParen = beforeEmail.lastIndexOf(')');
                if (firstParen !== -1 && lastParen !== -1 && lastParen > firstParen) {
                    this.comment = beforeEmail
                        .substring(firstParen + 1, lastParen)
                        .trim();
                    this.name = beforeEmail.substring(0, firstParen).trim();
                }
                else {
                    this.name = beforeEmail;
                    this.comment = '';
                }
            }
        }
        else if (isValidEmail(userID.trim())) {
            // unbracketed email case
            this.email = userID.trim();
            this.name = '';
            this.comment = '';
        }
        this.userID = userID;
    }
    /**
     * Creates a binary representation of the user id packet
     * @returns {Uint8Array} Binary representation.
     */
    write() {
        return util.encodeUTF8(this.userID);
    }
    equals(otherUserID) {
        return otherUserID && otherUserID.userID === this.userID;
    }
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret
 * Key packet and has exactly the same format.
 * @extends SecretKeyPacket
 */
class SecretSubkeyPacket extends SecretKeyPacket {
    static get tag() {
        return enums.packet.secretSubkey;
    }
    /**
     * @param {Date} [date] - Creation date
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     */
    constructor(date = new Date(), config$1 = config) {
        super(date, config$1);
    }
}

/** @access public */
/**
 * Implementation of the Trust Packet (Tag 12)
 *
 * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:
 * The Trust packet is used only within keyrings and is not normally
 * exported.  Trust packets contain data that record the user's
 * specifications of which key holders are trustworthy introducers,
 * along with other information that implementing software uses for
 * trust information.  The format of Trust packets is defined by a given
 * implementation.
 *
 * Trust packets SHOULD NOT be emitted to output streams that are
 * transferred to other users, and they SHOULD be ignored on any input
 * other than local keyring files.
 */
class TrustPacket {
    static get tag() {
        return enums.packet.trust;
    }
    /**
     * Parsing function for a trust packet (tag 12).
     * Currently not implemented as we ignore trust packets
     */
    read() {
        throw new UnsupportedError('Trust packets are not supported');
    }
    write() {
        throw new UnsupportedError('Trust packets are not supported');
    }
}

/** @access public */
// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2022 Proton AG
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Implementation of the Padding Packet
 *
 * {@link https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#name-padding-packet-tag-21}:
 * Padding Packet
 */
class PaddingPacket {
    static get tag() {
        return enums.packet.padding;
    }
    constructor() {
        this.padding = null;
    }
    /**
     * Read a padding packet
     * @param {Uint8Array | ReadableStream<Uint8Array>} bytes
     */
    read(bytes) {
        // Padding packets are ignored, so this function is never called.
    }
    /**
     * Write the padding packet
     * @returns {Uint8Array} The padding packet.
     */
    write() {
        return this.padding;
    }
    /**
     * Create random padding.
     * @param {Number} length - The length of padding to be generated.
     * @throws {Error} if padding generation was not successful
     * @async needed to avoid breaking change until next major release
     */
    // eslint-disable-next-line @typescript-eslint/require-await
    async createPadding(length) {
        this.padding = getRandomBytes(length);
    }
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// A Signature can contain the following packets
const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
/**
 * Class that represents an OpenPGP signature.
 */
class Signature {
    /**
     * @param {PacketList} packetlist - The signature packets
     */
    constructor(packetlist) {
        this.packets = packetlist || new PacketList();
    }
    /**
     * Returns binary encoded signature
     * @returns {ReadableStream<Uint8Array>} Binary signature.
     */
    write() {
        return this.packets.write();
    }
    /**
     * Returns ASCII armored text of signature
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {ReadableStream<String>} ASCII armor.
     */
    armor(config$1 = config) {
        // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.
        const emitChecksum = this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6);
        return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, emitChecksum, config$1);
    }
    /**
     * Returns an array of KeyIDs of all of the issuers who created this signature
     * @returns {Array<KeyID>} The Key IDs of the signing keys
     */
    getSigningKeyIDs() {
        return this.packets.map(packet => packet.issuerKeyID);
    }
}
/**
 * reads an (optionally armored) OpenPGP signature and returns a signature object
 * @param {Object} options
 * @param {String} [options.armoredSignature] - Armored signature to be parsed
 * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<Signature>} New signature object.
 * @async
 * @static
 */
async function readSignature({ armoredSignature, binarySignature, config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    let input = armoredSignature || binarySignature;
    if (!input) {
        throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');
    }
    if (armoredSignature && !util.isString(armoredSignature)) {
        throw new Error('readSignature: options.armoredSignature must be a string');
    }
    if (binarySignature && !util.isUint8Array(binarySignature)) {
        throw new Error('readSignature: options.binarySignature must be a Uint8Array');
    }
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    if (armoredSignature) {
        const { type, data } = await unarmor(input);
        if (type !== enums.armor.signature) {
            throw new Error('Armored text not of type signature');
        }
        input = data;
    }
    const packetlist = await PacketList.fromBinary(input, allowedPackets$1, config$1);
    return new Signature(packetlist);
}

/**
 * @fileoverview Provides helpers methods for key module
 * @module key/helper
 * @access private
 */
async function generateSecretSubkey(options, config) {
    const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);
    secretSubkeyPacket.packets = null;
    secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);
    await secretSubkeyPacket.generate(options.rsaBits, options.curve);
    await secretSubkeyPacket.computeFingerprintAndKeyID();
    return secretSubkeyPacket;
}
async function generateSecretKey(options, config) {
    const secretKeyPacket = new SecretKeyPacket(options.date, config);
    secretKeyPacket.packets = null;
    secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);
    await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);
    await secretKeyPacket.computeFingerprintAndKeyID();
    return secretKeyPacket;
}
/**
 * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.
 * @param {Array<SignaturePacket>} signatures - List of signatures
 * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature
 * @param {module:enums.signature} signatureType - Signature type to determine how to hash the data (NB: for userID signatures,
 *                          `enums.signatures.certGeneric` should be given regardless of the actual trust level)
 * @param {Date} date - Use the given date instead of the current time
 * @param {Object} config - full configuration
 * @returns {Promise<SignaturePacket>} The latest valid signature.
 * @async
 */
async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {
    let latestValid;
    let exception;
    for (let i = signatures.length - 1; i >= 0; i--) {
        try {
            if ((!latestValid || signatures[i].created >= latestValid.created)) {
                await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);
                latestValid = signatures[i];
            }
        }
        catch (e) {
            exception = e;
        }
    }
    if (!latestValid) {
        throw util.wrapError(`Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`
            .replace('certGeneric ', 'self-')
            .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()), exception);
    }
    return latestValid;
}
function isDataExpired(keyPacket, signature, date = new Date()) {
    const normDate = util.normalizeDate(date);
    if (normDate !== null) {
        const expirationTime = getKeyExpirationTime(keyPacket, signature);
        return !(keyPacket.created <= normDate && normDate < expirationTime);
    }
    return false;
}
/**
 * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}
 * @param {SecretSubkeyPacket} subkey - Subkey key packet
 * @param {SecretKeyPacket} primaryKey - Primary key packet
 * @param {Object} options
 * @param {Object} config - Full configuration
 */
async function createBindingSignature(subkey, primaryKey, options, config) {
    const dataToSign = {};
    dataToSign.key = primaryKey;
    dataToSign.bind = subkey;
    const signatureProperties = { signatureType: enums.signature.subkeyBinding };
    if (options.sign) {
        signatureProperties.keyFlags = [enums.keyFlags.signData];
        signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, [], subkey, {
            signatureType: enums.signature.keyBinding
        }, options.date, undefined, undefined, undefined, config);
    }
    else {
        signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];
    }
    if (options.keyExpirationTime > 0) {
        signatureProperties.keyExpirationTime = options.keyExpirationTime;
        signatureProperties.keyNeverExpires = false;
    }
    const subkeySignaturePacket = await createSignaturePacket(dataToSign, [], primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config);
    return subkeySignaturePacket;
}
/**
 * Returns the preferred signature hash algorithm for a set of keys.
 * @param {Array<Key>} [targetKeys] - The keys to get preferences from
 * @param {SecretKeyPacket|SecretSubkeyPacket} signingKeyPacket - key packet used for signing
 * @param {Date} [date] - Use the given date for verification instead of the current time
 * @param {Object} [targetUserID] - User IDs corresponding to `targetKeys` to get preferences from
 * @param {Object} config - full configuration
 * @returns {Promise<enums.hash>}
 * @async
 */
async function getPreferredHashAlgo(targetKeys, signingKeyPacket, date = new Date(), targetUserIDs = [], config) {
    /**
     * If `preferredSenderAlgo` appears in the prefs of all recipients, we pick it; otherwise, we use the
     * strongest supported algo (`defaultAlgo` is always implicitly supported by all keys).
     * if no keys are available, `preferredSenderAlgo` is returned.
     * For ECC signing key, the curve preferred hash is taken into account as well (see logic below).
     */
    const defaultAlgo = enums.hash.sha256; // MUST implement
    const preferredSenderAlgo = config.preferredHashAlgorithm;
    const supportedAlgosPerTarget = await Promise.all(targetKeys.map(async (key, i) => {
        const selfCertification = await key.getPrimarySelfSignature(date, targetUserIDs[i], config);
        const targetPrefs = selfCertification.preferredHashAlgorithms;
        return targetPrefs || [];
    }));
    const supportedAlgosMap = new Map(); // use Map over object to preserve numeric keys
    for (const supportedAlgos of supportedAlgosPerTarget) {
        for (const hashAlgo of supportedAlgos) {
            try {
                // ensure that `hashAlgo` is recognized/implemented by us, otherwise e.g. `getHashByteLength` will throw later on
                const supportedAlgo = enums.write(enums.hash, hashAlgo);
                supportedAlgosMap.set(supportedAlgo, supportedAlgosMap.has(supportedAlgo) ? supportedAlgosMap.get(supportedAlgo) + 1 : 1);
            }
            catch { }
        }
    }
    const isSupportedHashAlgo = hashAlgo => targetKeys.length === 0 || supportedAlgosMap.get(hashAlgo) === targetKeys.length || hashAlgo === defaultAlgo;
    const getStrongestSupportedHashAlgo = () => {
        if (supportedAlgosMap.size === 0) {
            return defaultAlgo;
        }
        const sortedHashAlgos = Array.from(supportedAlgosMap.keys())
            .filter(hashAlgo => isSupportedHashAlgo(hashAlgo))
            .sort((algoA, algoB) => getHashByteLength(algoA) - getHashByteLength(algoB));
        const strongestHashAlgo = sortedHashAlgos[0];
        // defaultAlgo is always implicitly supported, and might be stronger than the rest
        return getHashByteLength(strongestHashAlgo) >= getHashByteLength(defaultAlgo) ? strongestHashAlgo : defaultAlgo;
    };
    const eccAlgos = new Set([
        enums.publicKey.ecdsa,
        enums.publicKey.eddsaLegacy,
        enums.publicKey.ed25519,
        enums.publicKey.ed448
    ]);
    if (eccAlgos.has(signingKeyPacket.algorithm)) {
        // For ECC, the returned hash algo MUST be at least as strong as `preferredCurveHashAlgo`, see:
        // - ECDSA: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.2-5
        // - EdDSALegacy: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.3-3
        // - Ed25519: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.4-4
        // - Ed448: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3.5-4
        // Hence, we return the `preferredHashAlgo` as long as it's supported and strong enough;
        // Otherwise, we look at the strongest supported algo, and ultimately fallback to the curve
        // preferred algo, even if not supported by all targets.
        const preferredCurveAlgo = getPreferredCurveHashAlgo(signingKeyPacket.algorithm, signingKeyPacket.publicParams.oid);
        const preferredSenderAlgoIsSupported = isSupportedHashAlgo(preferredSenderAlgo);
        const preferredSenderAlgoStrongerThanCurveAlgo = getHashByteLength(preferredSenderAlgo) >= getHashByteLength(preferredCurveAlgo);
        if (preferredSenderAlgoIsSupported && preferredSenderAlgoStrongerThanCurveAlgo) {
            return preferredSenderAlgo;
        }
        else {
            const strongestSupportedAlgo = getStrongestSupportedHashAlgo();
            return getHashByteLength(strongestSupportedAlgo) >= getHashByteLength(preferredCurveAlgo) ?
                strongestSupportedAlgo :
                preferredCurveAlgo;
        }
    }
    // `preferredSenderAlgo` may be weaker than the default, but we do not guard against this,
    // since it was manually set by the sender.
    return isSupportedHashAlgo(preferredSenderAlgo) ? preferredSenderAlgo : getStrongestSupportedHashAlgo();
}
/**
 * Returns the preferred compression algorithm for a set of keys
 * @param {Array<Key>} [keys] - Set of keys
 * @param {Date} [date] - Use the given date for verification instead of the current time
 * @param {Array} [userIDs] - User IDs
 * @param {Object} [config] - Full configuration, defaults to openpgp.config
 * @returns {Promise<module:enums.compression>} Preferred compression algorithm
 * @async
 */
async function getPreferredCompressionAlgo(keys = [], date = new Date(), userIDs = [], config$1 = config) {
    const defaultAlgo = enums.compression.uncompressed;
    const preferredSenderAlgo = config$1.preferredCompressionAlgorithm;
    // if preferredSenderAlgo appears in the prefs of all recipients, we pick it
    // otherwise we use the default algo
    // if no keys are available, preferredSenderAlgo is returned
    const senderAlgoSupport = await Promise.all(keys.map(async function (key, i) {
        const selfCertification = await key.getPrimarySelfSignature(date, userIDs[i], config$1);
        const recipientPrefs = selfCertification.preferredCompressionAlgorithms;
        return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;
    }));
    return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;
}
/**
 * Returns the preferred symmetric and AEAD algorithm (if any) for a set of keys
 * @param {Array<Key>} [keys] - Set of keys
 * @param {Date} [date] - Use the given date for verification instead of the current time
 * @param {Array} [userIDs] - User IDs
 * @param {Object} [config] - Full configuration, defaults to openpgp.config
 * @returns {Promise<{ symmetricAlgo: module:enums.symmetric, aeadAlgo: module:enums.aead | undefined }>} Object containing the preferred symmetric algorithm, and the preferred AEAD algorithm, or undefined if CFB is preferred
 * @async
 */
async function getPreferredCipherSuite(keys = [], date = new Date(), userIDs = [], config$1 = config) {
    const selfSigs = await Promise.all(keys.map((key, i) => key.getPrimarySelfSignature(date, userIDs[i], config$1)));
    const withAEAD = keys.length ?
        selfSigs.every(selfSig => selfSig.features && (selfSig.features[0] & enums.features.seipdv2)) :
        config$1.aeadProtect;
    if (withAEAD) {
        const defaultCipherSuite = { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: enums.aead.ocb };
        const desiredCipherSuites = [
            { symmetricAlgo: config$1.preferredSymmetricAlgorithm, aeadAlgo: config$1.preferredAEADAlgorithm },
            { symmetricAlgo: config$1.preferredSymmetricAlgorithm, aeadAlgo: enums.aead.ocb },
            { symmetricAlgo: enums.symmetric.aes128, aeadAlgo: config$1.preferredAEADAlgorithm }
        ];
        for (const desiredCipherSuite of desiredCipherSuites) {
            if (selfSigs.every(selfSig => selfSig.preferredCipherSuites && selfSig.preferredCipherSuites.some(cipherSuite => cipherSuite[0] === desiredCipherSuite.symmetricAlgo && cipherSuite[1] === desiredCipherSuite.aeadAlgo))) {
                return desiredCipherSuite;
            }
        }
        return defaultCipherSuite;
    }
    const defaultSymAlgo = enums.symmetric.aes128;
    const desiredSymAlgo = config$1.preferredSymmetricAlgorithm;
    return {
        symmetricAlgo: selfSigs.every(selfSig => selfSig.preferredSymmetricAlgorithms && selfSig.preferredSymmetricAlgorithms.includes(desiredSymAlgo)) ?
            desiredSymAlgo :
            defaultSymAlgo,
        aeadAlgo: undefined
    };
}
/**
 * Create signature packet
 * @param {Object} dataToSign - Contains packets to be signed
 * @param {Array<Key>} recipientKeys - keys to get preferences from
 * @param  {SecretKeyPacket|
 *          SecretSubkeyPacket}              signingKeyPacket secret key packet for signing
 * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing
 * @param {Date} [date] - Override the creationtime of the signature
 * @param {Object} [userID] - User ID
 * @param {Array} [notations] - Notation Data to add to the signature, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]
 * @param {Object} [detached] - Whether to create a detached signature packet
 * @param {Object} config - full configuration
 * @returns {Promise<SignaturePacket>} Signature packet.
 */
async function createSignaturePacket(dataToSign, recipientKeys, signingKeyPacket, signatureProperties, date, recipientUserIDs, notations = [], detached = false, config) {
    if (signingKeyPacket.isDummy()) {
        throw new Error('Cannot sign with a gnu-dummy key.');
    }
    if (!signingKeyPacket.isDecrypted()) {
        throw new Error('Signing key is not decrypted.');
    }
    const signaturePacket = new SignaturePacket();
    Object.assign(signaturePacket, signatureProperties);
    signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;
    signaturePacket.hashAlgorithm = await getPreferredHashAlgo(recipientKeys, signingKeyPacket, date, recipientUserIDs, config);
    signaturePacket.rawNotations = [...notations];
    await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached, config);
    return signaturePacket;
}
/**
 * Merges signatures from source[attr] to dest[attr]
 * @param {Object} source
 * @param {Object} dest
 * @param {String} attr
 * @param {Date} [date] - date to use for signature expiration check, instead of the current time
 * @param {Function} [checkFn] - signature only merged if true
 */
async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {
    source = source[attr];
    if (source) {
        if (!dest[attr].length) {
            dest[attr] = source;
        }
        else {
            await Promise.all(source.map(async function (sourceSig) {
                if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&
                    !dest[attr].some(function (destSig) {
                        return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());
                    })) {
                    dest[attr].push(sourceSig);
                }
            }));
        }
    }
}
/**
 * Checks if a given certificate or binding signature is revoked
 * @param  {SecretKeyPacket|
 *          PublicKeyPacket}        primaryKey   The primary key packet
 * @param {Object} dataToVerify - The data to check
 * @param {Array<SignaturePacket>} revocations - The revocation signatures to check
 * @param {SignaturePacket} signature - The certificate or signature to check
 * @param  {PublicSubkeyPacket|
 *          SecretSubkeyPacket|
 *          PublicKeyPacket|
 *          SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key
 * @param {Date} date - Use the given date instead of the current time
 * @param {Object} config - Full configuration
 * @returns {Promise<Boolean>} True if the signature revokes the data.
 * @async
 */
async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {
    key = key || primaryKey;
    const revocationKeyIDs = [];
    await Promise.all(revocations.map(async function (revocationSignature) {
        try {
            if (
            // Note: a third-party revocation signature could legitimately revoke a
            // self-signature if the signature has an authorized revocation key.
            // However, we don't support passing authorized revocation keys, nor
            // verifying such revocation signatures. Instead, we indicate an error
            // when parsing a key with an authorized revocation key, and ignore
            // third-party revocation signatures here. (It could also be revoking a
            // third-party key certification, which should only affect
            // `verifyAllCertifications`.)
            !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)) {
                const isHardRevocation = ![
                    enums.reasonForRevocation.keyRetired,
                    enums.reasonForRevocation.keySuperseded,
                    enums.reasonForRevocation.userIDInvalid
                ].includes(revocationSignature.reasonForRevocationFlag);
                await revocationSignature.verify(key, signatureType, dataToVerify, isHardRevocation ? null : date, false, config);
                // TODO get an identifier of the revoked object instead
                revocationKeyIDs.push(revocationSignature.issuerKeyID);
            }
        }
        catch { }
    }));
    // TODO further verify that this is the signature that should be revoked
    if (signature) {
        signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :
            signature.revoked || false;
        return signature.revoked;
    }
    return revocationKeyIDs.length > 0;
}
/**
 * Returns key expiration time based on the given certification signature.
 * The expiration time of the signature is ignored.
 * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check
 * @param {SignaturePacket} signature - signature to process
 * @returns {Date|Infinity} expiration time or infinity if the key does not expire
 */
function getKeyExpirationTime(keyPacket, signature) {
    let expirationTime;
    // check V4 expiration time
    if (signature.keyNeverExpires === false) {
        expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;
    }
    return expirationTime ? new Date(expirationTime) : Infinity;
}
function sanitizeKeyOptions(options, subkeyDefaults = {}) {
    options.type = options.type || subkeyDefaults.type;
    options.curve = options.curve || subkeyDefaults.curve;
    options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;
    options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;
    options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
    options.date = options.date || subkeyDefaults.date;
    options.sign = options.sign || false;
    switch (options.type) {
        case 'ecc': // NB: this case also handles legacy eddsa and x25519 keys, based on `options.curve`
            try {
                options.curve = enums.write(enums.curve, options.curve);
            }
            catch {
                throw new Error('Unknown curve');
            }
            if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy ||
                options.curve === 'ed25519' || options.curve === 'curve25519') { // keep support for curve names without 'Legacy' addition, for now
                options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy;
            }
            if (options.sign) {
                options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa;
            }
            else {
                options.algorithm = enums.publicKey.ecdh;
            }
            break;
        case 'curve25519':
            options.algorithm = options.sign ? enums.publicKey.ed25519 : enums.publicKey.x25519;
            break;
        case 'curve448':
            options.algorithm = options.sign ? enums.publicKey.ed448 : enums.publicKey.x448;
            break;
        case 'rsa':
            options.algorithm = enums.publicKey.rsaEncryptSign;
            break;
        default:
            throw new Error(`Unsupported key type ${options.type}`);
    }
    return options;
}
function validateSigningKeyPacket(keyPacket, signature, config) {
    switch (keyPacket.algorithm) {
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.rsaSign:
        case enums.publicKey.dsa:
        case enums.publicKey.ecdsa:
        case enums.publicKey.eddsaLegacy:
        case enums.publicKey.ed25519:
        case enums.publicKey.ed448:
            if (!signature.keyFlags && !config.allowMissingKeyFlags) {
                throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');
            }
            return !signature.keyFlags ||
                (signature.keyFlags[0] & enums.keyFlags.signData) !== 0;
        default:
            return false;
    }
}
function validateEncryptionKeyPacket(keyPacket, signature, config) {
    switch (keyPacket.algorithm) {
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.rsaEncrypt:
        case enums.publicKey.elgamal:
        case enums.publicKey.ecdh:
        case enums.publicKey.x25519:
        case enums.publicKey.x448:
            if (!signature.keyFlags && !config.allowMissingKeyFlags) {
                throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');
            }
            return !signature.keyFlags ||
                (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||
                (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;
        default:
            return false;
    }
}
function validateDecryptionKeyPacket(keyPacket, signature, config) {
    if (!signature.keyFlags && !config.allowMissingKeyFlags) {
        throw new Error('None of the key flags is set: consider passing `config.allowMissingKeyFlags`');
    }
    switch (keyPacket.algorithm) {
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.rsaEncrypt:
        case enums.publicKey.elgamal:
        case enums.publicKey.ecdh:
        case enums.publicKey.x25519:
        case enums.publicKey.x448: {
            const isValidSigningKeyPacket = !signature.keyFlags || (signature.keyFlags[0] & enums.keyFlags.signData) !== 0;
            if (isValidSigningKeyPacket && config.allowInsecureDecryptionWithSigningKeys) {
                // This is only relevant for RSA keys, all other signing algorithms cannot decrypt
                return true;
            }
            return !signature.keyFlags ||
                (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||
                (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;
        }
        default:
            return false;
    }
}
/**
 * Check key against blacklisted algorithms and minimum strength requirements.
 * @param {SecretKeyPacket|PublicKeyPacket|
 *        SecretSubkeyPacket|PublicSubkeyPacket} keyPacket
 * @param {Config} config
 * @throws {Error} if the key packet does not meet the requirements
 */
function checkKeyRequirements(keyPacket, config) {
    const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);
    const algoInfo = keyPacket.getAlgorithmInfo();
    if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {
        throw new Error(`${algoInfo.algorithm} keys are considered too weak.`);
    }
    switch (keyAlgo) {
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.rsaSign:
        case enums.publicKey.rsaEncrypt:
            if (algoInfo.bits < config.minRSABits) {
                throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);
            }
            break;
        case enums.publicKey.ecdsa:
        case enums.publicKey.eddsaLegacy:
        case enums.publicKey.ecdh:
            if (config.rejectCurves.has(algoInfo.curve)) {
                throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`);
            }
            break;
    }
}

/**
 * @module key/User
 * @access private
 */
/**
 * Class that represents an user ID or attribute packet and the relevant signatures.
  * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info
  * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with
 */
class User {
    constructor(userPacket, mainKey) {
        this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;
        this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;
        this.selfCertifications = [];
        this.otherCertifications = [];
        this.revocationSignatures = [];
        this.mainKey = mainKey;
    }
    /**
     * Transforms structured user data to packetlist
     * @returns {PacketList}
     */
    toPacketList() {
        const packetlist = new PacketList();
        packetlist.push(this.userID || this.userAttribute);
        packetlist.push(...this.revocationSignatures);
        packetlist.push(...this.selfCertifications);
        packetlist.push(...this.otherCertifications);
        return packetlist;
    }
    /**
     * Shallow clone
     * @returns {User}
     */
    clone() {
        const user = new User(this.userID || this.userAttribute, this.mainKey);
        user.selfCertifications = [...this.selfCertifications];
        user.otherCertifications = [...this.otherCertifications];
        user.revocationSignatures = [...this.revocationSignatures];
        return user;
    }
    /**
     * Generate third-party certifications over this user and its primary key
     * @param {Array<PrivateKey>} signingKeys - Decrypted private keys for signing
     * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time
     * @param {Object} config - Full configuration
     * @returns {Promise<User>} New user with new certifications.
     * @async
     */
    async certify(signingKeys, date, config) {
        const primaryKey = this.mainKey.keyPacket;
        const dataToSign = {
            userID: this.userID,
            userAttribute: this.userAttribute,
            key: primaryKey
        };
        const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);
        user.otherCertifications = await Promise.all(signingKeys.map(async function (privateKey) {
            if (!privateKey.isPrivate()) {
                throw new Error('Need private key for signing');
            }
            if (privateKey.hasSameFingerprintAs(primaryKey)) {
                throw new Error("The user's own key can only be used for self-certifications");
            }
            const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);
            return createSignaturePacket(dataToSign, [privateKey], signingKey.keyPacket, {
                // Most OpenPGP implementations use generic certification (0x10)
                signatureType: enums.signature.certGeneric,
                keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]
            }, date, undefined, undefined, undefined, config);
        }));
        await user.update(this, date, config);
        return user;
    }
    /**
     * Checks if a given certificate of the user is revoked
     * @param {SignaturePacket} certificate - The certificate to verify
     * @param  {PublicSubkeyPacket|
     *          SecretSubkeyPacket|
     *          PublicKeyPacket|
     *          SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key
     * @param {Date} [date] - Use the given date for verification instead of the current time
     * @param {Object} config - Full configuration
     * @returns {Promise<Boolean>} True if the certificate is revoked.
     * @async
     */
    async isRevoked(certificate, keyPacket, date = new Date(), config$1 = config) {
        const primaryKey = this.mainKey.keyPacket;
        return isDataRevoked(primaryKey, enums.signature.certRevocation, {
            key: primaryKey,
            userID: this.userID,
            userAttribute: this.userAttribute
        }, this.revocationSignatures, certificate, keyPacket, date, config$1);
    }
    /**
     * Verifies the user certificate.
     * @param {SignaturePacket} certificate - A certificate of this user
     * @param {Array<PublicKey>} verificationKeys - Array of keys to verify certificate signatures
     * @param {Date} [date] - Use the given date instead of the current time
     * @param {Object} config - Full configuration
     * @returns {Promise<true|null>} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate
     * @throws if the user certificate is invalid.
     * @async
     */
    async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {
        const that = this;
        const primaryKey = this.mainKey.keyPacket;
        const dataToVerify = {
            userID: this.userID,
            userAttribute: this.userAttribute,
            key: primaryKey
        };
        const { issuerKeyID } = certificate;
        const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);
        if (issuerKeys.length === 0) {
            return null;
        }
        await Promise.all(issuerKeys.map(async (key) => {
            const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);
            if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {
                throw new Error('User certificate is revoked');
            }
            try {
                await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);
            }
            catch (e) {
                throw util.wrapError('User certificate is invalid', e);
            }
        }));
        return true;
    }
    /**
     * Verifies all user certificates
     * @param {Array<PublicKey>} verificationKeys - Array of keys to verify certificate signatures
     * @param {Date} [date] - Use the given date instead of the current time
     * @param {Object} config - Full configuration
     * @returns {Promise<Array<{
     *   keyID: module:type/keyid~KeyID,
     *   valid: Boolean | null
     * }>>} List of signer's keyID and validity of signature.
     *      Signature validity is null if the verification keys do not correspond to the certificate.
     * @async
     */
    async verifyAllCertifications(verificationKeys, date = new Date(), config) {
        const that = this;
        const certifications = this.selfCertifications.concat(this.otherCertifications);
        return Promise.all(certifications.map(async (certification) => ({
            keyID: certification.issuerKeyID,
            valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)
        })));
    }
    /**
     * Verify User. Checks for existence of self signatures, revocation signatures
     * and validity of self signature.
     * @param {Date} date - Use the given date instead of the current time
     * @param {Object} config - Full configuration
     * @returns {Promise<true>} Status of user.
     * @throws {Error} if there are no valid self signatures.
     * @async
     */
    async verify(date = new Date(), config) {
        if (!this.selfCertifications.length) {
            throw new Error('No self-certifications found');
        }
        const that = this;
        const primaryKey = this.mainKey.keyPacket;
        const dataToVerify = {
            userID: this.userID,
            userAttribute: this.userAttribute,
            key: primaryKey
        };
        // TODO replace when Promise.some or Promise.any are implemented
        let exception;
        for (let i = this.selfCertifications.length - 1; i >= 0; i--) {
            try {
                const selfCertification = this.selfCertifications[i];
                if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {
                    throw new Error('Self-certification is revoked');
                }
                try {
                    await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);
                }
                catch (e) {
                    throw util.wrapError('Self-certification is invalid', e);
                }
                return true;
            }
            catch (e) {
                exception = e;
            }
        }
        throw exception;
    }
    /**
     * Update user with new components from specified user
     * @param {User} sourceUser - Source user to merge
     * @param {Date} date - Date to verify the validity of signatures
     * @param {Object} config - Full configuration
     * @returns {Promise<undefined>}
     * @async
     */
    async update(sourceUser, date, config) {
        const primaryKey = this.mainKey.keyPacket;
        const dataToVerify = {
            userID: this.userID,
            userAttribute: this.userAttribute,
            key: primaryKey
        };
        // self signatures
        await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function (srcSelfSig) {
            try {
                await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);
                return true;
            }
            catch {
                return false;
            }
        });
        // other signatures
        await mergeSignatures(sourceUser, this, 'otherCertifications', date);
        // revocation signatures
        await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function (srcRevSig) {
            return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);
        });
    }
    /**
     * Revokes the user
     * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation
     * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation
     * @param  {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
     * @param  {String} reasonForRevocation.string optional, string explaining the reason for revocation
     * @param {Date} date - optional, override the creationtime of the revocation signature
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<User>} New user with revocation signature.
     * @async
     */
    async revoke(primaryKey, { flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, string: reasonForRevocationString = '' } = {}, date = new Date(), config$1 = config) {
        const dataToSign = {
            userID: this.userID,
            userAttribute: this.userAttribute,
            key: primaryKey
        };
        const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);
        user.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, {
            signatureType: enums.signature.certRevocation,
            reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),
            reasonForRevocationString
        }, date, undefined, undefined, false, config$1));
        await user.update(this);
        return user;
    }
}

/**
 * @module key/Subkey
 * @access private
 */
/**
 * Class that represents a subkey packet and the relevant signatures.
 * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID
 * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint
 * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs
 * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo
 * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime
 * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted
 */
class Subkey {
    /**
     * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey
     * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey
     */
    constructor(subkeyPacket, mainKey) {
        this.keyPacket = subkeyPacket;
        this.bindingSignatures = [];
        this.revocationSignatures = [];
        this.mainKey = mainKey;
    }
    /**
     * Transforms structured subkey data to packetlist
     * @returns {PacketList}
     */
    toPacketList() {
        const packetlist = new PacketList();
        packetlist.push(this.keyPacket);
        packetlist.push(...this.revocationSignatures);
        packetlist.push(...this.bindingSignatures);
        return packetlist;
    }
    /**
     * Shallow clone
     * @return {Subkey}
     */
    clone() {
        const subkey = new Subkey(this.keyPacket, this.mainKey);
        subkey.bindingSignatures = [...this.bindingSignatures];
        subkey.revocationSignatures = [...this.revocationSignatures];
        return subkey;
    }
    /**
     * Checks if a binding signature of a subkey is revoked
     * @param {SignaturePacket} signature - The binding signature to verify
     * @param  {PublicSubkeyPacket|
     *          SecretSubkeyPacket|
     *          PublicKeyPacket|
     *          SecretKeyPacket} key, optional The key to verify the signature
     * @param {Date} [date] - Use the given date for verification instead of the current time
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Boolean>} True if the binding signature is revoked.
     * @async
     */
    async isRevoked(signature, key, date = new Date(), config$1 = config) {
        const primaryKey = this.mainKey.keyPacket;
        return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, {
            key: primaryKey,
            bind: this.keyPacket
        }, this.revocationSignatures, signature, key, date, config$1);
    }
    /**
     * Verify subkey. Checks for revocation signatures, expiration time
     * and valid binding signature.
     * @param {Date} date - Use the given date instead of the current time
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<SignaturePacket>}
     * @throws {Error}           if the subkey is invalid.
     * @async
     */
    async verify(date = new Date(), config$1 = config) {
        const primaryKey = this.mainKey.keyPacket;
        const dataToVerify = { key: primaryKey, bind: this.keyPacket };
        // check subkey binding signatures
        const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1);
        // check binding signature is not revoked
        if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config$1)) {
            throw new Error('Subkey is revoked');
        }
        // check for expiration time
        if (isDataExpired(this.keyPacket, bindingSignature, date)) {
            throw new Error('Subkey is expired');
        }
        return bindingSignature;
    }
    /**
     * Returns the expiration time of the subkey or Infinity if key does not expire.
     * Returns null if the subkey is invalid.
     * @param {Date} date - Use the given date instead of the current time
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Date | Infinity | null>}
     * @async
     */
    async getExpirationTime(date = new Date(), config$1 = config) {
        const primaryKey = this.mainKey.keyPacket;
        const dataToVerify = { key: primaryKey, bind: this.keyPacket };
        let bindingSignature;
        try {
            bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1);
        }
        catch {
            return null;
        }
        const keyExpiry = getKeyExpirationTime(this.keyPacket, bindingSignature);
        const sigExpiry = bindingSignature.getExpirationTime();
        return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;
    }
    /**
     * Update subkey with new components from specified subkey
     * @param {Subkey} subkey - Source subkey to merge
     * @param {Date} [date] - Date to verify validity of signatures
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @throws {Error} if update failed
     * @async
     */
    async update(subkey, date = new Date(), config$1 = config) {
        const primaryKey = this.mainKey.keyPacket;
        if (!this.hasSameFingerprintAs(subkey)) {
            throw new Error('Subkey update method: fingerprints of subkeys not equal');
        }
        // key packet
        if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&
            subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {
            this.keyPacket = subkey.keyPacket;
        }
        // update missing binding signatures
        const that = this;
        const dataToVerify = { key: primaryKey, bind: that.keyPacket };
        await mergeSignatures(subkey, this, 'bindingSignatures', date, async function (srcBindSig) {
            for (let i = 0; i < that.bindingSignatures.length; i++) {
                if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {
                    if (srcBindSig.created > that.bindingSignatures[i].created) {
                        that.bindingSignatures[i] = srcBindSig;
                    }
                    return false;
                }
            }
            try {
                await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config$1);
                return true;
            }
            catch {
                return false;
            }
        });
        // revocation signatures
        await mergeSignatures(subkey, this, 'revocationSignatures', date, function (srcRevSig) {
            return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config$1);
        });
    }
    /**
     * Revokes the subkey
     * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation
     * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation
     * @param  {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
     * @param  {String} reasonForRevocation.string optional, string explaining the reason for revocation
     * @param {Date} date - optional, override the creationtime of the revocation signature
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Subkey>} New subkey with revocation signature.
     * @async
     */
    async revoke(primaryKey, { flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, string: reasonForRevocationString = '' } = {}, date = new Date(), config$1 = config) {
        const dataToSign = { key: primaryKey, bind: this.keyPacket };
        const subkey = new Subkey(this.keyPacket, this.mainKey);
        subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, [], primaryKey, {
            signatureType: enums.signature.subkeyRevocation,
            reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),
            reasonForRevocationString
        }, date, undefined, undefined, false, config$1));
        await subkey.update(this);
        return subkey;
    }
    hasSameFingerprintAs(other) {
        return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);
    }
}
['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {
    Subkey.prototype[name] =
        function () {
            return this.keyPacket[name]();
        };
});

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// A key revocation certificate can contain the following packets
const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
const mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.secretKey]);
const keyPacketTags = new Set([
    enums.packet.publicKey, enums.packet.secretKey,
    enums.packet.publicSubkey, enums.packet.secretSubkey
]);
/**
 * Abstract class that represents an OpenPGP key. Must contain a primary key.
 * Can contain additional subkeys, signatures, user ids, user attributes.
 * @borrows PublicKeyPacket#getKeyID as Key#getKeyID
 * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint
 * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs
 * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo
 * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime
 */
class Key {
    /**
     * Transforms packetlist to structured key data
     * @param {PacketList} packetlist - The packets that form a key
     * @param {Set<enums.packet>} disallowedPackets - disallowed packet tags
     */
    packetListToStructure(packetlist, disallowedPackets = new Set()) {
        let user;
        let primaryKeyID;
        let subkey;
        let ignoreUntil;
        for (const packet of packetlist) {
            if (packet instanceof UnparseablePacket) {
                const isUnparseableKeyPacket = keyPacketTags.has(packet.tag);
                if (isUnparseableKeyPacket && !ignoreUntil) {
                    // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must
                    // discard all non-key packets that follow, until another (sub)key packet is found.
                    if (mainKeyPacketTags.has(packet.tag)) {
                        ignoreUntil = mainKeyPacketTags;
                    }
                    else {
                        ignoreUntil = keyPacketTags;
                    }
                }
                continue;
            }
            const tag = packet.constructor.tag;
            if (ignoreUntil) {
                if (!ignoreUntil.has(tag))
                    continue;
                ignoreUntil = null;
            }
            if (disallowedPackets.has(tag)) {
                throw new Error(`Unexpected packet type: ${tag}`);
            }
            switch (tag) {
                case enums.packet.publicKey:
                case enums.packet.secretKey:
                    if (this.keyPacket) {
                        throw new Error('Key block contains multiple keys');
                    }
                    this.keyPacket = packet;
                    primaryKeyID = this.getKeyID();
                    if (!primaryKeyID) {
                        throw new Error('Missing Key ID');
                    }
                    break;
                case enums.packet.userID:
                case enums.packet.userAttribute:
                    user = new User(packet, this);
                    this.users.push(user);
                    break;
                case enums.packet.publicSubkey:
                case enums.packet.secretSubkey:
                    user = null;
                    subkey = new Subkey(packet, this);
                    this.subkeys.push(subkey);
                    break;
                case enums.packet.signature:
                    switch (packet.signatureType) {
                        case enums.signature.certGeneric:
                        case enums.signature.certPersona:
                        case enums.signature.certCasual:
                        case enums.signature.certPositive:
                            if (!user) {
                                util.printDebug('Dropping certification signatures without preceding user packet');
                                continue;
                            }
                            if (packet.issuerKeyID.equals(primaryKeyID)) {
                                user.selfCertifications.push(packet);
                            }
                            else {
                                user.otherCertifications.push(packet);
                            }
                            break;
                        case enums.signature.certRevocation:
                            if (user) {
                                user.revocationSignatures.push(packet);
                            }
                            else {
                                this.directSignatures.push(packet);
                            }
                            break;
                        case enums.signature.key:
                            this.directSignatures.push(packet);
                            break;
                        case enums.signature.subkeyBinding:
                            if (!subkey) {
                                util.printDebug('Dropping subkey binding signature without preceding subkey packet');
                                continue;
                            }
                            subkey.bindingSignatures.push(packet);
                            break;
                        case enums.signature.keyRevocation:
                            this.revocationSignatures.push(packet);
                            break;
                        case enums.signature.subkeyRevocation:
                            if (!subkey) {
                                util.printDebug('Dropping subkey revocation signature without preceding subkey packet');
                                continue;
                            }
                            subkey.revocationSignatures.push(packet);
                            break;
                    }
                    break;
            }
        }
    }
    /**
     * Transforms structured key data to packetlist
     * @returns {PacketList} The packets that form a key.
     */
    toPacketList() {
        const packetlist = new PacketList();
        packetlist.push(this.keyPacket);
        packetlist.push(...this.revocationSignatures);
        packetlist.push(...this.directSignatures);
        this.users.map(user => packetlist.push(...user.toPacketList()));
        this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));
        return packetlist;
    }
    /**
     * Clones the key object. The copy is shallow, as it references the same packet objects as the original. However, if the top-level API is used, the two key instances are effectively independent.
     * @param {Boolean} [clonePrivateParams=false] Only relevant for private keys: whether the secret key paramenters should be deeply copied. This is needed if e.g. `encrypt()` is to be called either on the clone or the original key.
     * @returns {Promise<Key>} Clone of the key.
     */
    clone(clonePrivateParams = false) {
        const key = new this.constructor(this.toPacketList());
        if (clonePrivateParams) {
            key.getKeys().forEach(k => {
                // shallow clone the key packets
                k.keyPacket = Object.create(Object.getPrototypeOf(k.keyPacket), Object.getOwnPropertyDescriptors(k.keyPacket));
                if (!k.keyPacket.isDecrypted())
                    return;
                // deep clone the private params, which are cleared during encryption
                const privateParams = {};
                Object.keys(k.keyPacket.privateParams).forEach(name => {
                    privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);
                });
                k.keyPacket.privateParams = privateParams;
            });
        }
        return key;
    }
    /**
     * Returns an array containing all public or private subkeys matching keyID;
     * If no keyID is given, returns all subkeys.
     * @param {type/keyID} [keyID] - key ID to look for
     * @returns {Array<Subkey>} array of subkeys
     */
    getSubkeys(keyID = null) {
        const subkeys = this.subkeys.filter(subkey => (!keyID || subkey.getKeyID().equals(keyID, true)));
        return subkeys;
    }
    /**
     * Returns an array containing all public or private keys matching keyID.
     * If no keyID is given, returns all keys, starting with the primary key.
     * @param {type/keyid~KeyID} [keyID] - key ID to look for
     * @returns {Array<Key|Subkey>} array of keys
     */
    getKeys(keyID = null) {
        const keys = [];
        if (!keyID || this.getKeyID().equals(keyID, true)) {
            keys.push(this);
        }
        return keys.concat(this.getSubkeys(keyID));
    }
    /**
     * Returns key IDs of all keys
     * @returns {Array<module:type/keyid~KeyID>}
     */
    getKeyIDs() {
        return this.getKeys().map(key => key.getKeyID());
    }
    /**
     * Returns userIDs
     * @returns {Array<string>} Array of userIDs.
     */
    getUserIDs() {
        return this.users.map(user => {
            return user.userID ? user.userID.userID : null;
        }).filter(userID => userID !== null);
    }
    /**
     * Returns binary encoded key
     * @returns {Uint8Array} Binary key.
     */
    write() {
        return this.toPacketList().write();
    }
    /**
     * Returns last created key or key by given keyID that is available for signing and verification
     * @param  {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve
     * @param  {Date} [date] - use the fiven date date to  to check key validity instead of the current date
     * @param  {Object} [userID] - filter keys for the given user ID
     * @param  {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Key|Subkey>} signing key
     * @throws if no valid signing key was found
     * @async
     */
    async getSigningKey(keyID = null, date = new Date(), userID = {}, config$1 = config) {
        await this.verifyPrimaryKey(date, userID, config$1);
        const primaryKey = this.keyPacket;
        try {
            checkKeyRequirements(primaryKey, config$1);
        }
        catch (err) {
            throw util.wrapError('Could not verify primary key', err);
        }
        // Prefer the most recently created valid subkey, or the subkey with
        // the highest algorithm ID in case of equal creation timestamps.
        const subkeys = this.subkeys.slice().sort((a, b) => (b.keyPacket.created - a.keyPacket.created ||
            b.keyPacket.algorithm - a.keyPacket.algorithm));
        let exception;
        for (const subkey of subkeys) {
            if (!keyID || subkey.getKeyID().equals(keyID)) {
                try {
                    await subkey.verify(date, config$1);
                    const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };
                    const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1);
                    if (!validateSigningKeyPacket(subkey.keyPacket, bindingSignature, config$1)) {
                        continue;
                    }
                    if (!bindingSignature.embeddedSignature) {
                        throw new Error('Missing embedded signature');
                    }
                    // verify embedded signature
                    await getLatestValidSignature([bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config$1);
                    checkKeyRequirements(subkey.keyPacket, config$1);
                    return subkey;
                }
                catch (e) {
                    exception = e;
                }
            }
        }
        try {
            const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1);
            if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&
                validateSigningKeyPacket(primaryKey, selfCertification, config$1)) {
                checkKeyRequirements(primaryKey, config$1);
                return this;
            }
        }
        catch (e) {
            exception = e;
        }
        throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);
    }
    /**
     * Returns last created key or key by given keyID that is available for encryption or decryption
     * @param  {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve
     * @param  {Date}   [date] - use the fiven date date to  to check key validity instead of the current date
     * @param  {Object} [userID] - filter keys for the given user ID
     * @param  {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Key|Subkey>} encryption key
     * @throws if no valid encryption key was found
     * @async
     */
    async getEncryptionKey(keyID, date = new Date(), userID = {}, config$1 = config) {
        await this.verifyPrimaryKey(date, userID, config$1);
        const primaryKey = this.keyPacket;
        try {
            checkKeyRequirements(primaryKey, config$1);
        }
        catch (err) {
            throw util.wrapError('Could not verify primary key', err);
        }
        // Prefer the most recently created valid subkey, or the subkey with
        // the highest algorithm ID in case of equal creation timestamps.
        const subkeys = this.subkeys.slice().sort((a, b) => (b.keyPacket.created - a.keyPacket.created ||
            b.keyPacket.algorithm - a.keyPacket.algorithm));
        let exception;
        for (const subkey of subkeys) {
            if (!keyID || subkey.getKeyID().equals(keyID)) {
                try {
                    await subkey.verify(date, config$1);
                    const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };
                    const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1);
                    if (validateEncryptionKeyPacket(subkey.keyPacket, bindingSignature, config$1)) {
                        checkKeyRequirements(subkey.keyPacket, config$1);
                        return subkey;
                    }
                }
                catch (e) {
                    exception = e;
                }
            }
        }
        try {
            // if no valid subkey for encryption, evaluate primary key
            const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1);
            if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&
                validateEncryptionKeyPacket(primaryKey, selfCertification, config$1)) {
                checkKeyRequirements(primaryKey, config$1);
                return this;
            }
        }
        catch (e) {
            exception = e;
        }
        throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);
    }
    /**
     * Checks if a signature on a key is revoked
     * @param {SignaturePacket} signature - The signature to verify
     * @param  {PublicSubkeyPacket|
     *          SecretSubkeyPacket|
     *          PublicKeyPacket|
     *          SecretKeyPacket} key, optional The key to verify the signature
     * @param {Date} [date] - Use the given date for verification, instead of the current time
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Boolean>} True if the certificate is revoked.
     * @async
     */
    async isRevoked(signature, key, date = new Date(), config$1 = config) {
        return isDataRevoked(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config$1);
    }
    /**
     * Verify primary key. Checks for revocation signatures, expiration time
     * and valid self signature. Throws if the primary key is invalid.
     * @param {Date} [date] - Use the given date for verification instead of the current time
     * @param {Object} [userID] - User ID
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @throws {Error} If key verification failed
     * @async
     */
    async verifyPrimaryKey(date = new Date(), userID = {}, config$1 = config) {
        const primaryKey = this.keyPacket;
        // check for key revocation signatures
        if (await this.isRevoked(null, null, date, config$1)) {
            throw new Error('Primary key is revoked');
        }
        // check for valid, unrevoked, unexpired self signature
        const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1);
        // check for expiration time in binding signatures
        if (isDataExpired(primaryKey, selfCertification, date)) {
            throw new Error('Primary key is expired');
        }
        if (primaryKey.version !== 6) {
            // check for expiration time in direct signatures (for V6 keys, the above already did so)
            const directSignature = await getLatestValidSignature(this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1).catch(() => { }); // invalid signatures are discarded, to avoid breaking the key
            if (directSignature && isDataExpired(primaryKey, directSignature, date)) {
                throw new Error('Primary key is expired');
            }
        }
    }
    /**
     * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.
     * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.
     * @param  {Object} [userID] - User ID to consider instead of the primary user
     * @param  {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Date | Infinity | null>}
     * @async
     */
    async getExpirationTime(userID, config$1 = config) {
        let primaryKeyExpiry;
        try {
            const selfCertification = await this.getPrimarySelfSignature(null, userID, config$1);
            const selfSigKeyExpiry = getKeyExpirationTime(this.keyPacket, selfCertification);
            const selfSigExpiry = selfCertification.getExpirationTime();
            const directSignature = this.keyPacket.version !== 6 && // For V6 keys, the above already returns the direct-key signature.
                await getLatestValidSignature(this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config$1).catch(() => { });
            if (directSignature) {
                const directSigKeyExpiry = getKeyExpirationTime(this.keyPacket, directSignature);
                // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,
                // causing a discountinous validy period for the key
                primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);
            }
            else {
                primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;
            }
        }
        catch {
            primaryKeyExpiry = null;
        }
        return util.normalizeDate(primaryKeyExpiry);
    }
    /**
     * For V4 keys, returns the self-signature of the primary user.
     * For V5 keys, returns the latest valid direct-key self-signature.
     * This self-signature is to be used to check the key expiration,
     * algorithm preferences, and so on.
     * @param {Date} [date] - Use the given date for verification instead of the current time
     * @param {Object} [userID] - User ID to get instead of the primary user for V4 keys, if it exists
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<SignaturePacket>} The primary self-signature
     * @async
     */
    async getPrimarySelfSignature(date = new Date(), userID = {}, config$1 = config) {
        const primaryKey = this.keyPacket;
        if (primaryKey.version === 6) {
            return getLatestValidSignature(this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1);
        }
        const { selfCertification } = await this.getPrimaryUser(date, userID, config$1);
        return selfCertification;
    }
    /**
     * Returns primary user and most significant (latest valid) self signature
     * - if multiple primary users exist, returns the one with the latest self signature
     * - otherwise, returns the user with the latest self signature
     * @param {Date} [date] - Use the given date for verification instead of the current time
     * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<{
     *   user: User,
     *   selfCertification: SignaturePacket
     * }>} The primary user and the self signature
     * @async
     */
    async getPrimaryUser(date = new Date(), userID = {}, config$1 = config) {
        const primaryKey = this.keyPacket;
        const users = [];
        let exception;
        for (let i = 0; i < this.users.length; i++) {
            try {
                const user = this.users[i];
                if (!user.userID) {
                    continue;
                }
                if ((userID.name !== undefined && user.userID.name !== userID.name) ||
                    (userID.email !== undefined && user.userID.email !== userID.email) ||
                    (userID.comment !== undefined && user.userID.comment !== userID.comment)) {
                    throw new Error('Could not find user that matches that user ID');
                }
                const dataToVerify = { userID: user.userID, key: primaryKey };
                const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config$1);
                users.push({ index: i, user, selfCertification });
            }
            catch (e) {
                exception = e;
            }
        }
        if (!users.length) {
            // eslint-disable-next-line @typescript-eslint/only-throw-error
            throw exception || new Error('Could not find primary user');
        }
        // Update `revoked` status, whose value is discarded here but used below;
        // see https://github.com/openpgpjs/openpgpjs/issues/880 for Promise.all motivation
        await Promise.all(users.map(async (a) => {
            a.selfCertification.revoked || await a.user.isRevoked(a.selfCertification, null, date, config$1);
        }));
        // sort by primary user flag and signature creation time
        const primaryUser = users.sort(function (a, b) {
            const A = a.selfCertification;
            const B = b.selfCertification;
            return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;
        }).pop();
        const { user, selfCertification: cert } = primaryUser;
        if (cert.revoked || await user.isRevoked(cert, null, date, config$1)) {
            throw new Error('Primary user is revoked');
        }
        return primaryUser;
    }
    /**
     * Update key with new components from specified key with same key ID:
     * users, subkeys, certificates are merged into the destination key,
     * duplicates and expired signatures are ignored.
     *
     * If the source key is a private key and the destination key is public,
     * a private key is returned.
     * @param {Key} sourceKey - Source key to merge
     * @param {Date} [date] - Date to verify validity of signatures and keys
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Key>} updated key
     * @async
     */
    async update(sourceKey, date = new Date(), config$1 = config) {
        if (!this.hasSameFingerprintAs(sourceKey)) {
            throw new Error('Primary key fingerprints must be equal to update the key');
        }
        if (!this.isPrivate() && sourceKey.isPrivate()) {
            // check for equal subkey packets
            const equal = (this.subkeys.length === sourceKey.subkeys.length) &&
                (this.subkeys.every(destSubkey => {
                    return sourceKey.subkeys.some(srcSubkey => {
                        return destSubkey.hasSameFingerprintAs(srcSubkey);
                    });
                }));
            if (!equal) {
                throw new Error('Cannot update public key with private key if subkeys mismatch');
            }
            return sourceKey.update(this, config$1);
        }
        // from here on, either:
        // - destination key is private, source key is public
        // - the keys are of the same type
        // hence we don't need to convert the destination key type
        const updatedKey = this.clone();
        // revocation signatures
        await mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {
            return isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config$1);
        });
        // direct signatures
        await mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);
        // update users
        await Promise.all(sourceKey.users.map(async (srcUser) => {
            // multiple users with the same ID/attribute are not explicitly disallowed by the spec
            // hence we support them, just in case
            const usersToUpdate = updatedKey.users.filter(dstUser => ((srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||
                (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))));
            if (usersToUpdate.length > 0) {
                await Promise.all(usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config$1)));
            }
            else {
                const newUser = srcUser.clone();
                newUser.mainKey = updatedKey;
                updatedKey.users.push(newUser);
            }
        }));
        // update subkeys
        await Promise.all(sourceKey.subkeys.map(async (srcSubkey) => {
            // multiple subkeys with same fingerprint might be preset
            const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (dstSubkey.hasSameFingerprintAs(srcSubkey)));
            if (subkeysToUpdate.length > 0) {
                await Promise.all(subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config$1)));
            }
            else {
                const newSubkey = srcSubkey.clone();
                newSubkey.mainKey = updatedKey;
                updatedKey.subkeys.push(newSubkey);
            }
        }));
        return updatedKey;
    }
    /**
     * Get revocation certificate from a revoked key.
     *   (To get a revocation certificate for an unrevoked key, call revoke() first.)
     * @param {Date} date - Use the given date instead of the current time
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<String>} Armored revocation certificate.
     * @async
     */
    async getRevocationCertificate(date = new Date(), config$1 = config) {
        const dataToVerify = { key: this.keyPacket };
        const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config$1);
        const packetlist = new PacketList();
        packetlist.push(revocationSignature);
        // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.
        const emitChecksum = this.keyPacket.version !== 6;
        return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate', emitChecksum, config$1);
    }
    /**
     * Applies a revocation certificate to a key
     * This adds the first signature packet in the armored text to the key,
     * if it is a valid revocation signature.
     * @param {String} revocationCertificate - armored revocation certificate
     * @param {Date} [date] - Date to verify the certificate
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Key>} Revoked key.
     * @async
     */
    async applyRevocationCertificate(revocationCertificate, date = new Date(), config$1 = config) {
        const input = await unarmor(revocationCertificate);
        const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config$1);
        const revocationSignature = packetlist.findPacket(enums.packet.signature);
        if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {
            throw new Error('Could not find revocation signature packet');
        }
        if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {
            throw new Error('Revocation signature does not match key');
        }
        try {
            await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config$1);
        }
        catch (e) {
            throw util.wrapError('Could not verify revocation signature', e);
        }
        const key = this.clone();
        key.revocationSignatures.push(revocationSignature);
        return key;
    }
    /**
     * Signs primary user of key
     * @param {Array<PrivateKey>} privateKeys - decrypted private keys for signing
     * @param {Date} [date] - Use the given date for verification instead of the current time
     * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Key>} Key with new certificate signature.
     * @async
     */
    async signPrimaryUser(privateKeys, date, userID, config$1 = config) {
        const { index, user } = await this.getPrimaryUser(date, userID, config$1);
        const userSign = await user.certify(privateKeys, date, config$1);
        const key = this.clone();
        key.users[index] = userSign;
        return key;
    }
    /**
     * Signs all users of key
     * @param {Array<PrivateKey>} privateKeys - decrypted private keys for signing
     * @param {Date} [date] - Use the given date for signing, instead of the current time
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Key>} Key with new certificate signature.
     * @async
     */
    async signAllUsers(privateKeys, date = new Date(), config$1 = config) {
        const key = this.clone();
        key.users = await Promise.all(this.users.map(function (user) {
            return user.certify(privateKeys, date, config$1);
        }));
        return key;
    }
    /**
     * Verifies primary user of key
     * - if no arguments are given, verifies the self certificates;
     * - otherwise, verifies all certificates signed with given keys.
     * @param {Array<PublicKey>} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key
     * @param {Date} [date] - Use the given date for verification instead of the current time
     * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Array<{
     *   keyID: module:type/keyid~KeyID,
     *   valid: Boolean|null
     * }>>} List of signer's keyID and validity of signature.
     *      Signature validity is null if the verification keys do not correspond to the certificate.
     * @async
     */
    async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config$1 = config) {
        const primaryKey = this.keyPacket;
        const { user } = await this.getPrimaryUser(date, userID, config$1);
        const results = verificationKeys ?
            await user.verifyAllCertifications(verificationKeys, date, config$1) :
            [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }];
        return results;
    }
    /**
     * Verifies all users of key
     * - if no arguments are given, verifies the self certificates;
     * - otherwise, verifies all certificates signed with given keys.
     * @param {Array<PublicKey>} [verificationKeys] - array of keys to verify certificate signatures
     * @param {Date} [date] - Use the given date for verification instead of the current time
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Array<{
     *   userID: String,
     *   keyID: module:type/keyid~KeyID,
     *   valid: Boolean|null
     * }>>} List of userID, signer's keyID and validity of signature.
     *      Signature validity is null if the verification keys do not correspond to the certificate.
     * @async
     */
    async verifyAllUsers(verificationKeys, date = new Date(), config$1 = config) {
        const primaryKey = this.keyPacket;
        const results = [];
        await Promise.all(this.users.map(async (user) => {
            const signatures = verificationKeys ?
                await user.verifyAllCertifications(verificationKeys, date, config$1) :
                [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }];
            results.push(...signatures.map(signature => ({
                userID: user.userID ? user.userID.userID : null,
                userAttribute: user.userAttribute,
                keyID: signature.keyID,
                valid: signature.valid
            })));
        }));
        return results;
    }
}
['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {
    Key.prototype[name] = Subkey.prototype[name];
});

/** @access public */
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
/**
 * Class that represents an OpenPGP Public Key
 */
class PublicKey extends Key {
    /**
     * @param {PacketList} packetlist - The packets that form this key
     */
    constructor(packetlist) {
        super();
        this.keyPacket = null;
        this.revocationSignatures = [];
        this.directSignatures = [];
        this.users = [];
        this.subkeys = [];
        if (packetlist) {
            this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));
            if (!this.keyPacket) {
                throw new Error('Invalid key: missing public-key packet');
            }
        }
    }
    /**
     * Returns true if this is a private key
     * @returns {false}
     */
    isPrivate() {
        return false;
    }
    /**
     * Returns key as public key (shallow copy)
     * @returns {PublicKey} New public Key
     */
    toPublic() {
        return this;
    }
    /**
     * Returns ASCII armored text of key
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {ReadableStream<String>} ASCII armor.
     */
    armor(config$1 = config) {
        // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.
        const emitChecksum = this.keyPacket.version !== 6;
        return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config$1);
    }
}

/** @access public */
/**
 * Class that represents an OpenPGP Private key
 */
class PrivateKey extends PublicKey {
    /**
   * @param {PacketList} packetlist - The packets that form this key
   */
    constructor(packetlist) {
        super();
        this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));
        if (!this.keyPacket) {
            throw new Error('Invalid key: missing private-key packet');
        }
    }
    /**
     * Returns true if this is a private key
     * @returns {Boolean}
     */
    isPrivate() {
        return true;
    }
    /**
     * Returns key as public key (shallow copy)
     * @returns {PublicKey} New public Key
     */
    toPublic() {
        const packetlist = new PacketList();
        const keyPackets = this.toPacketList();
        for (const keyPacket of keyPackets) {
            switch (keyPacket.constructor.tag) {
                case enums.packet.secretKey: {
                    const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);
                    packetlist.push(pubKeyPacket);
                    break;
                }
                case enums.packet.secretSubkey: {
                    const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);
                    packetlist.push(pubSubkeyPacket);
                    break;
                }
                default:
                    packetlist.push(keyPacket);
            }
        }
        return new PublicKey(packetlist);
    }
    /**
     * Returns ASCII armored text of key
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {ReadableStream<String>} ASCII armor.
     */
    armor(config$1 = config) {
        // An ASCII-armored Transferable Public Key packet sequence of a v6 key MUST NOT contain a CRC24 footer.
        const emitChecksum = this.keyPacket.version !== 6;
        return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, emitChecksum, config$1);
    }
    /**
     * Returns all keys that are available for decryption, matching the keyID when given
     * This is useful to retrieve keys for session key decryption
     * @param  {module:type/keyid~KeyID} keyID, optional
     * @param  {Date}              date, optional
     * @param  {String}            userID, optional
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Array<Key|Subkey>>} Array of decryption keys.
     * @throws {Error} if no decryption key is found
     * @async
     */
    async getDecryptionKeys(keyID, date = new Date(), userID = {}, config$1 = config) {
        const primaryKey = this.keyPacket;
        const keys = [];
        let exception = null;
        for (let i = 0; i < this.subkeys.length; i++) {
            if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {
                if (this.subkeys[i].keyPacket.isDummy()) {
                    exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption');
                    continue;
                }
                try {
                    const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };
                    const bindingSignature = await getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1);
                    if (validateDecryptionKeyPacket(this.subkeys[i].keyPacket, bindingSignature, config$1)) {
                        keys.push(this.subkeys[i]);
                    }
                }
                catch (e) {
                    exception = e;
                }
            }
        }
        // evaluate primary key
        const selfCertification = await this.getPrimarySelfSignature(date, userID, config$1);
        if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) && validateDecryptionKeyPacket(primaryKey, selfCertification, config$1)) {
            if (primaryKey.isDummy()) {
                exception = exception || new Error('Gnu-dummy key packets cannot be used for decryption');
            }
            else {
                keys.push(this);
            }
        }
        if (keys.length === 0) {
            // eslint-disable-next-line @typescript-eslint/only-throw-error
            throw exception || new Error('No decryption key packets found');
        }
        return keys;
    }
    /**
     * Returns true if the primary key or any subkey is decrypted.
     * A dummy key is considered encrypted.
     */
    isDecrypted() {
        return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());
    }
    /**
     * Check whether the private and public primary key parameters correspond
     * Together with verification of binding signatures, this guarantees key integrity
     * In case of gnu-dummy primary key, it is enough to validate any signing subkeys
     *   otherwise all encryption subkeys are validated
     * If only gnu-dummy keys are found, we cannot properly validate so we throw an error
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @throws {Error} if validation was not successful and the key cannot be trusted
     * @async
     */
    async validate(config$1 = config) {
        if (!this.isPrivate()) {
            throw new Error('Cannot validate a public key');
        }
        let signingKeyPacket;
        if (!this.keyPacket.isDummy()) {
            signingKeyPacket = this.keyPacket;
        }
        else {
            /**
             * It is enough to validate any signing keys
             * since its binding signatures are also checked
             */
            const signingKey = await this.getSigningKey(null, null, undefined, { ...config$1, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });
            // This could again be a dummy key
            if (signingKey && !signingKey.keyPacket.isDummy()) {
                signingKeyPacket = signingKey.keyPacket;
            }
        }
        if (signingKeyPacket) {
            return signingKeyPacket.validate();
        }
        else {
            const keys = this.getKeys();
            const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);
            if (allDummies) {
                throw new Error('Cannot validate an all-gnu-dummy key');
            }
            return Promise.all(keys.map(key => key.keyPacket.validate()));
        }
    }
    /**
     * Clear private key parameters
     */
    clearPrivateParams() {
        this.getKeys().forEach(({ keyPacket }) => {
            if (keyPacket.isDecrypted()) {
                keyPacket.clearPrivateParams();
            }
        });
    }
    /**
     * Revokes the key
     * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation
     * @param  {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
     * @param  {String} reasonForRevocation.string optional, string explaining the reason for revocation
     * @param {Date} date - optional, override the creationtime of the revocation signature
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<PrivateKey>} New key with revocation signature.
     * @async
     */
    async revoke({ flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason, string: reasonForRevocationString = '' } = {}, date = new Date(), config$1 = config) {
        if (!this.isPrivate()) {
            throw new Error('Need private key for revoking');
        }
        const dataToSign = { key: this.keyPacket };
        const key = this.clone();
        key.revocationSignatures.push(await createSignaturePacket(dataToSign, [], this.keyPacket, {
            signatureType: enums.signature.keyRevocation,
            reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),
            reasonForRevocationString
        }, date, undefined, undefined, undefined, config$1));
        return key;
    }
    /**
     * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.
     * Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519.
     * Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.
     * @param {ecc|rsa|curve25519|curve448} options.type The subkey algorithm: ECC, RSA, Curve448 or Curve25519 (new format).
     *                                                   Note: Curve448 and Curve25519 are not widely supported yet.
     * @param {String}  options.curve      (optional) Elliptic curve for ECC keys
     * @param {Integer} options.rsaBits    (optional) Number of bits for RSA subkeys
     * @param {Number}  options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires
     * @param {Date}    options.date       (optional) Override the creation date of the key and the key signatures
     * @param {Boolean} options.sign       (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false
     * @param {Object}  options.config     (optional) custom configuration settings to overwrite those in [config]{@link module:config}
     * @returns {Promise<PrivateKey>}
     * @async
     */
    async addSubkey(options = {}) {
        const config$1 = { ...config, ...options.config };
        if (options.passphrase) {
            throw new Error('Subkey could not be encrypted here, please encrypt whole key');
        }
        if (options.rsaBits < config$1.minRSABits) {
            throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${options.rsaBits}`);
        }
        const secretKeyPacket = this.keyPacket;
        if (secretKeyPacket.isDummy()) {
            throw new Error('Cannot add subkey to gnu-dummy primary key');
        }
        if (!secretKeyPacket.isDecrypted()) {
            throw new Error('Key is not decrypted');
        }
        const defaultOptions = secretKeyPacket.getAlgorithmInfo();
        defaultOptions.type = getDefaultSubkeyType(defaultOptions.algorithm);
        defaultOptions.rsaBits = defaultOptions.bits || 4096;
        defaultOptions.curve = defaultOptions.curve || 'curve25519Legacy';
        options = sanitizeKeyOptions(options, defaultOptions);
        // Every subkey for a v4 primary key MUST be a v4 subkey.
        // Every subkey for a v6 primary key MUST be a v6 subkey.
        // For v5 keys, since we dropped generation support, a v4 subkey is added.
        // The config is always overwritten since we cannot tell if the defaultConfig was changed by the user.
        const keyPacket = await generateSecretSubkey(options, { ...config$1, v6Keys: this.keyPacket.version === 6 });
        checkKeyRequirements(keyPacket, config$1);
        const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config$1);
        const packetList = this.toPacketList();
        packetList.push(keyPacket, bindingSignature);
        return new PrivateKey(packetList);
    }
}
function getDefaultSubkeyType(algoName) {
    const algo = enums.write(enums.publicKey, algoName);
    // NB: no encryption-only algos, since they cannot be in primary keys
    switch (algo) {
        case enums.publicKey.rsaEncrypt:
        case enums.publicKey.rsaEncryptSign:
        case enums.publicKey.rsaSign:
        case enums.publicKey.dsa:
            return 'rsa';
        case enums.publicKey.ecdsa:
        case enums.publicKey.eddsaLegacy:
            return 'ecc';
        case enums.publicKey.ed25519:
            return 'curve25519';
        case enums.publicKey.ed448:
            return 'curve448';
        default:
            throw new Error('Unsupported algorithm');
    }
}

/**
 * @module key/factory
 * @access private
 */
// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2015-2016 Decentral
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// A Key can contain the following packets
const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([
    PublicKeyPacket,
    PublicSubkeyPacket,
    SecretKeyPacket,
    SecretSubkeyPacket,
    UserIDPacket,
    UserAttributePacket,
    SignaturePacket
]);
/**
 * Creates a PublicKey or PrivateKey depending on the packetlist in input
 * @param {PacketList} - packets to parse
 * @return {Key} parsed key
 * @throws if no key packet was found
 */
function createKey(packetlist) {
    for (const packet of packetlist) {
        switch (packet.constructor.tag) {
            case enums.packet.secretKey:
                return new PrivateKey(packetlist);
            case enums.packet.publicKey:
                return new PublicKey(packetlist);
        }
    }
    throw new Error('No key packet found');
}
/**
 * Generates a new OpenPGP key. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys.
 * By default, primary and subkeys will be of same type.
 * @param {ecc|rsa|curve448|curve25519} options.type                  The primary key algorithm type: ECC, RSA, Curve448 or Curve25519 (new format).
 * @param {String}  options.curve                 Elliptic curve for ECC keys
 * @param {Integer} options.rsaBits               Number of bits for RSA keys
 * @param {Array<String|Object>} options.userIDs  User IDs as strings or objects: 'Jo Doe <info@jo.com>' or { name:'Jo Doe', email:'info@jo.com' }
 * @param {String}  options.passphrase            Passphrase used to encrypt the resulting private key
 * @param {Number}  options.keyExpirationTime     (optional) Number of seconds from the key creation time after which the key expires
 * @param {Date}    options.date                  Creation date of the key and the key signatures
 * @param {Object} config - Full configuration
 * @param {Array<Object>} options.subkeys         (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
 *                                                  sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt
 * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}
 * @async
 * @static
 * @private
 */
async function generate(options, config) {
    options.sign = true; // primary key is always a signing key
    options = sanitizeKeyOptions(options);
    options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options));
    let promises = [generateSecretKey(options, config)];
    promises = promises.concat(options.subkeys.map(options => generateSecretSubkey(options, config)));
    const packets = await Promise.all(promises);
    const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);
    const revocationCertificate = await key.getRevocationCertificate(options.date, config);
    key.revocationSignatures = [];
    return { key, revocationCertificate };
}
/**
 * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.
 * @param {PrivateKey} options.privateKey         The private key to reformat
 * @param {Array<String|Object>} options.userIDs  User IDs as strings or objects: 'Jo Doe <info@jo.com>' or { name:'Jo Doe', email:'info@jo.com' }
 * @param {String} options.passphrase             Passphrase used to encrypt the resulting private key
 * @param {Number} options.keyExpirationTime      Number of seconds from the key creation time after which the key expires
 * @param {Date}   options.date                   Override the creation date of the key signatures
 * @param {Array<Object>} options.subkeys         (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
 * @param {Object} config - Full configuration
 *
 * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}
 * @async
 * @static
 * @private
 */
async function reformat(options, config) {
    options = sanitize(options);
    const { privateKey } = options;
    if (!privateKey.isPrivate()) {
        throw new Error('Cannot reformat a public key');
    }
    if (privateKey.keyPacket.isDummy()) {
        throw new Error('Cannot reformat a gnu-dummy primary key');
    }
    const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());
    if (!isDecrypted) {
        throw new Error('Key is not decrypted');
    }
    const secretKeyPacket = privateKey.keyPacket;
    if (!options.subkeys) {
        options.subkeys = await Promise.all(privateKey.subkeys.map(async (subkey) => {
            const secretSubkeyPacket = subkey.keyPacket;
            const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };
            const bindingSignature = await (getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)).catch(() => ({}));
            return {
                sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)
            };
        }));
    }
    const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);
    if (options.subkeys.length !== secretSubkeyPackets.length) {
        throw new Error('Number of subkey options does not match number of subkeys');
    }
    options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));
    const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);
    const revocationCertificate = await key.getRevocationCertificate(options.date, config);
    key.revocationSignatures = [];
    return { key, revocationCertificate };
    function sanitize(options, subkeyDefaults = {}) {
        options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;
        options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
        options.date = options.date || subkeyDefaults.date;
        return options;
    }
}
/**
 * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection
 * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.
 * @param {SecretKeyPacket} secretKeyPacket
 * @param {Array<SecretSubkeyPacket>} secretSubkeyPackets
 * @param {Object} options
 * @param {Object} config - Full configuration
 * @returns {Promise<PrivateKey>}
 */
async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {
    // set passphrase protection
    if (options.passphrase) {
        await secretKeyPacket.encrypt(options.passphrase, config);
    }
    await Promise.all(secretSubkeyPackets.map(async function (secretSubkeyPacket, index) {
        const subkeyPassphrase = options.subkeys[index].passphrase;
        if (subkeyPassphrase) {
            await secretSubkeyPacket.encrypt(subkeyPassphrase, config);
        }
    }));
    const packetlist = new PacketList();
    packetlist.push(secretKeyPacket);
    function createPreferredAlgos(algos, preferredAlgo) {
        return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];
    }
    function getKeySignatureProperties() {
        const signatureProperties = {};
        signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];
        const symmetricAlgorithms = createPreferredAlgos([
            // prefer aes256, aes128, no aes192 (no Web Crypto support in Chrome: https://www.chromium.org/blink/webcrypto#TOC-AES-support)
            enums.symmetric.aes256,
            enums.symmetric.aes128
        ], config.preferredSymmetricAlgorithm);
        signatureProperties.preferredSymmetricAlgorithms = symmetricAlgorithms;
        if (config.aeadProtect) {
            const aeadAlgorithms = createPreferredAlgos([
                enums.aead.gcm,
                enums.aead.eax,
                enums.aead.ocb
            ], config.preferredAEADAlgorithm);
            signatureProperties.preferredCipherSuites = aeadAlgorithms.flatMap(aeadAlgorithm => {
                return symmetricAlgorithms.map(symmetricAlgorithm => {
                    return [symmetricAlgorithm, aeadAlgorithm];
                });
            });
        }
        signatureProperties.preferredHashAlgorithms = createPreferredAlgos([
            enums.hash.sha512,
            enums.hash.sha256,
            enums.hash.sha3_512,
            enums.hash.sha3_256
        ], config.preferredHashAlgorithm);
        signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([
            enums.compression.uncompressed,
            enums.compression.zlib,
            enums.compression.zip
        ], config.preferredCompressionAlgorithm);
        // integrity protection always enabled
        signatureProperties.features = [0];
        signatureProperties.features[0] |= enums.features.modificationDetection;
        if (config.aeadProtect) {
            signatureProperties.features[0] |= enums.features.seipdv2;
        }
        if (options.keyExpirationTime > 0) {
            signatureProperties.keyExpirationTime = options.keyExpirationTime;
            signatureProperties.keyNeverExpires = false;
        }
        return signatureProperties;
    }
    if (secretKeyPacket.version === 6) { // add direct key signature with key prefs
        const dataToSign = {
            key: secretKeyPacket
        };
        const signatureProperties = getKeySignatureProperties();
        signatureProperties.signatureType = enums.signature.key;
        const signaturePacket = await createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, options.signatureNotations, undefined, config);
        packetlist.push(signaturePacket);
    }
    await Promise.all(options.userIDs.map(async function (userID, index) {
        const userIDPacket = UserIDPacket.fromObject(userID);
        const dataToSign = {
            userID: userIDPacket,
            key: secretKeyPacket
        };
        const signatureProperties = secretKeyPacket.version !== 6 ? getKeySignatureProperties() : {};
        signatureProperties.signatureType = enums.signature.certPositive;
        if (index === 0) {
            signatureProperties.isPrimaryUserID = true;
        }
        const signaturePacket = await createSignaturePacket(dataToSign, [], secretKeyPacket, signatureProperties, options.date, undefined, options.signatureNotations, undefined, config);
        return { userIDPacket, signaturePacket };
    })).then(list => {
        list.forEach(({ userIDPacket, signaturePacket }) => {
            packetlist.push(userIDPacket);
            packetlist.push(signaturePacket);
        });
    });
    await Promise.all(secretSubkeyPackets.map(async function (secretSubkeyPacket, index) {
        const subkeyOptions = options.subkeys[index];
        const subkeySignaturePacket = await createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);
        return { secretSubkeyPacket, subkeySignaturePacket };
    })).then(packets => {
        packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {
            packetlist.push(secretSubkeyPacket);
            packetlist.push(subkeySignaturePacket);
        });
    });
    // Add revocation signature packet for creating a revocation certificate.
    // This packet should be removed before returning the key.
    const dataToSign = { key: secretKeyPacket };
    packetlist.push(await createSignaturePacket(dataToSign, [], secretKeyPacket, {
        signatureType: enums.signature.keyRevocation,
        reasonForRevocationFlag: enums.reasonForRevocation.noReason,
        reasonForRevocationString: ''
    }, options.date, undefined, undefined, undefined, config));
    if (options.passphrase) {
        secretKeyPacket.clearPrivateParams();
    }
    secretSubkeyPackets.map(function (secretSubkeyPacket, index) {
        const subkeyPassphrase = options.subkeys[index].passphrase;
        if (subkeyPassphrase) {
            secretSubkeyPacket.clearPrivateParams();
        }
    });
    return new PrivateKey(packetlist);
}
/**
 * Reads an (optionally armored) OpenPGP key and returns a key object
 * @param {Object} options
 * @param {String} [options.armoredKey] - Armored key to be parsed
 * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<Key>} Key object.
 * @async
 * @static
 */
async function readKey({ armoredKey, binaryKey, config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    if (!armoredKey && !binaryKey) {
        throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');
    }
    if (armoredKey && !util.isString(armoredKey)) {
        throw new Error('readKey: options.armoredKey must be a string');
    }
    if (binaryKey && !util.isUint8Array(binaryKey)) {
        throw new Error('readKey: options.binaryKey must be a Uint8Array');
    }
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    let input;
    if (armoredKey) {
        const { type, data } = await unarmor(armoredKey);
        if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {
            throw new Error('Armored text not of type key');
        }
        input = data;
    }
    else {
        input = binaryKey;
    }
    const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1);
    const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);
    if (keyIndex.length === 0) {
        throw new Error('No key packet found');
    }
    const firstKeyPacketList = packetlist.slice(keyIndex[0], keyIndex[1]);
    return createKey(firstKeyPacketList);
}
/**
 * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object
 * @param {Object} options
 * @param {String} [options.armoredKey] - Armored key to be parsed
 * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<PrivateKey>} Key object.
 * @async
 * @static
 */
async function readPrivateKey({ armoredKey, binaryKey, config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    if (!armoredKey && !binaryKey) {
        throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');
    }
    if (armoredKey && !util.isString(armoredKey)) {
        throw new Error('readPrivateKey: options.armoredKey must be a string');
    }
    if (binaryKey && !util.isUint8Array(binaryKey)) {
        throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');
    }
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    let input;
    if (armoredKey) {
        const { type, data } = await unarmor(armoredKey);
        if (!(type === enums.armor.privateKey)) {
            throw new Error('Armored text not of type private key');
        }
        input = data;
    }
    else {
        input = binaryKey;
    }
    const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1);
    const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);
    for (let i = 0; i < keyIndex.length; i++) {
        if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) {
            continue;
        }
        const firstPrivateKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);
        return new PrivateKey(firstPrivateKeyList);
    }
    throw new Error('No secret key packet found');
}
/**
 * Reads an (optionally armored) OpenPGP key block and returns a list of key objects
 * @param {Object} options
 * @param {String} [options.armoredKeys] - Armored keys to be parsed
 * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<Array<Key>>} Key objects.
 * @async
 * @static
 */
async function readKeys({ armoredKeys, binaryKeys, config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    let input = armoredKeys || binaryKeys;
    if (!input) {
        throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');
    }
    if (armoredKeys && !util.isString(armoredKeys)) {
        throw new Error('readKeys: options.armoredKeys must be a string');
    }
    if (binaryKeys && !util.isUint8Array(binaryKeys)) {
        throw new Error('readKeys: options.binaryKeys must be a Uint8Array');
    }
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    if (armoredKeys) {
        const { type, data } = await unarmor(armoredKeys);
        if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {
            throw new Error('Armored text not of type key');
        }
        input = data;
    }
    const keys = [];
    const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1);
    const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);
    if (keyIndex.length === 0) {
        throw new Error('No key packet found');
    }
    for (let i = 0; i < keyIndex.length; i++) {
        const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);
        const newKey = createKey(oneKeyList);
        keys.push(newKey);
    }
    return keys;
}
/**
 * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects
 * @param {Object} options
 * @param {String} [options.armoredKeys] - Armored keys to be parsed
 * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<Array<PrivateKey>>} Key objects.
 * @async
 * @static
 */
async function readPrivateKeys({ armoredKeys, binaryKeys, config: config$1 }) {
    config$1 = { ...config, ...config$1 };
    let input = armoredKeys || binaryKeys;
    if (!input) {
        throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');
    }
    if (armoredKeys && !util.isString(armoredKeys)) {
        throw new Error('readPrivateKeys: options.armoredKeys must be a string');
    }
    if (binaryKeys && !util.isUint8Array(binaryKeys)) {
        throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');
    }
    if (armoredKeys) {
        const { type, data } = await unarmor(armoredKeys);
        if (type !== enums.armor.privateKey) {
            throw new Error('Armored text not of type private key');
        }
        input = data;
    }
    const keys = [];
    const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1);
    const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);
    for (let i = 0; i < keyIndex.length; i++) {
        if (packetlist[keyIndex[i]].constructor.tag === enums.packet.publicKey) {
            continue;
        }
        const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);
        const newKey = new PrivateKey(oneKeyList);
        keys.push(newKey);
    }
    if (keys.length === 0) {
        throw new Error('No secret key packet found');
    }
    return keys;
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// A Message can contain the following packets
const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([
    LiteralDataPacket,
    CompressedDataPacket,
    AEADEncryptedDataPacket,
    SymEncryptedIntegrityProtectedDataPacket,
    SymmetricallyEncryptedDataPacket,
    PublicKeyEncryptedSessionKeyPacket,
    SymEncryptedSessionKeyPacket,
    OnePassSignaturePacket,
    SignaturePacket
]);
// A SKESK packet can contain the following packets
const allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);
// A detached signature can contain the following packets
const allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
/**
 * Class that represents an OpenPGP message.
 * Can be an encrypted message, signed message, compressed message or literal message
 * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}
 */
class Message {
    /**
     * @param {PacketList} packetlist - The packets that form this message
     */
    constructor(packetlist) {
        this.packets = packetlist || new PacketList();
    }
    /**
     * Returns the key IDs of the keys to which the session key is encrypted
     * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
     */
    getEncryptionKeyIDs() {
        const keyIDs = [];
        const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
        pkESKeyPacketlist.forEach(function (packet) {
            keyIDs.push(packet.publicKeyID);
        });
        return keyIDs;
    }
    /**
     * Returns the key IDs of the keys that signed the message
     * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
     */
    getSigningKeyIDs() {
        const msg = this.unwrapCompressed();
        // search for one pass signatures
        const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);
        if (onePassSigList.length > 0) {
            return onePassSigList.map(packet => packet.issuerKeyID);
        }
        // if nothing found look for signature packets
        const signatureList = msg.packets.filterByTag(enums.packet.signature);
        return signatureList.map(packet => packet.issuerKeyID);
    }
    /**
     * Decrypt the message. Either a private key, a session key, or a password must be specified.
     * @param {Array<PrivateKey>} [decryptionKeys] - Private keys with decrypted secret data
     * @param {Array<String>} [passwords] - Passwords used to decrypt
     * @param {Array<Object>} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
     * @param {Date} [date] - Use the given date for key verification instead of the current time
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Message>} New message with decrypted content.
     * @async
     */
    async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config$1 = config) {
        const symEncryptedPacketlist = this.packets.filterByTag(enums.packet.symmetricallyEncryptedData, enums.packet.symEncryptedIntegrityProtectedData, enums.packet.aeadEncryptedData);
        if (symEncryptedPacketlist.length === 0) {
            throw new Error('No encrypted data found');
        }
        const symEncryptedPacket = symEncryptedPacketlist[0];
        const expectedSymmetricAlgorithm = symEncryptedPacket.cipherAlgorithm;
        const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date, config$1);
        let exception = null;
        const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => {
            if (!util.isUint8Array(data) || (!symEncryptedPacket.cipherAlgorithm && !util.isString(algorithmName))) {
                throw new Error('Invalid session key for decryption.');
            }
            try {
                const algo = symEncryptedPacket.cipherAlgorithm || enums.write(enums.symmetric, algorithmName);
                await symEncryptedPacket.decrypt(algo, data, config$1);
            }
            catch (e) {
                util.printDebugError(e);
                exception = e;
            }
        }));
        // We don't await stream.cancel here because it only returns when the other copy is canceled too.
        cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.
        symEncryptedPacket.encrypted = null;
        await decryptedPromise;
        if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {
            throw exception || new Error('Decryption failed.');
        }
        const resultMsg = new Message(symEncryptedPacket.packets);
        symEncryptedPacket.packets = new PacketList(); // remove packets after decryption
        return resultMsg;
    }
    /**
     * Decrypt encrypted session keys either with private keys or passwords.
     * @param {Array<PrivateKey>} [decryptionKeys] - Private keys with decrypted secret data
     * @param {Array<String>} [passwords] - Passwords used to decrypt
     * @param {enums.symmetric} [expectedSymmetricAlgorithm] - The symmetric algorithm the SEIPDv2 / AEAD packet is encrypted with (if applicable)
     * @param {Date} [date] - Use the given date for key verification, instead of current time
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Array<{
     *   data: Uint8Array,
     *   algorithm: String
     * }>>} array of object with potential sessionKey, algorithm pairs
     * @async
     */
    async decryptSessionKeys(decryptionKeys, passwords, expectedSymmetricAlgorithm, date = new Date(), config$1 = config) {
        let decryptedSessionKeyPackets = [];
        let exception;
        if (passwords) {
            const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);
            if (skeskPackets.length === 0) {
                throw new Error('No symmetrically encrypted session key packet found.');
            }
            await Promise.all(passwords.map(async function (password, i) {
                let packets;
                if (i) {
                    packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config$1);
                }
                else {
                    packets = skeskPackets;
                }
                await Promise.all(packets.map(async function (skeskPacket) {
                    try {
                        await skeskPacket.decrypt(password, config$1);
                        decryptedSessionKeyPackets.push(skeskPacket);
                    }
                    catch (err) {
                        util.printDebugError(err);
                        if (err instanceof Argon2OutOfMemoryError) {
                            exception = err;
                        }
                    }
                }));
            }));
        }
        else if (decryptionKeys) {
            const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
            if (pkeskPackets.length === 0) {
                throw new Error('No public key encrypted session key packet found.');
            }
            await Promise.all(pkeskPackets.map(async function (pkeskPacket) {
                await Promise.all(decryptionKeys.map(async function (decryptionKey) {
                    let decryptionKeyPackets;
                    try {
                        // do not check key expiration to allow decryption of old messages
                        decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config$1)).map(key => key.keyPacket);
                    }
                    catch (err) {
                        exception = err;
                        return;
                    }
                    let algos = [
                        enums.symmetric.aes256, // Old OpenPGP.js default fallback
                        enums.symmetric.aes128, // RFC4880bis fallback
                        enums.symmetric.tripledes, // RFC4880 fallback
                        enums.symmetric.cast5 // Golang OpenPGP fallback
                    ];
                    try {
                        const selfCertification = await decryptionKey.getPrimarySelfSignature(date, undefined, config$1); // TODO: Pass userID from somewhere.
                        if (selfCertification.preferredSymmetricAlgorithms) {
                            algos = algos.concat(selfCertification.preferredSymmetricAlgorithms);
                        }
                    }
                    catch { }
                    await Promise.all(decryptionKeyPackets.map(async function (decryptionKeyPacket) {
                        if (!decryptionKeyPacket.isDecrypted()) {
                            throw new Error('Decryption key is not decrypted.');
                        }
                        // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set.
                        const doConstantTimeDecryption = config$1.constantTimePKCS1Decryption && (pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt ||
                            pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign ||
                            pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign ||
                            pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal);
                        if (doConstantTimeDecryption) {
                            // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message,
                            // either with the successfully decrypted session key, or with a randomly generated one.
                            // Since the SEIP/AEAD's symmetric algorithm and key size are stored in the encrypted portion of the PKESK, and the execution flow cannot depend on
                            // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`:
                            // - If the PKESK decryption succeeds, and the session key cipher is in the supported set, then we try to decrypt the data with the decrypted session key as well as with the
                            // randomly generated keys of the remaining key types.
                            // - If the PKESK decryptions fails, or if it succeeds but support for the cipher is not enabled, then we discard the session key and try to decrypt the data using only the randomly
                            // generated session keys.
                            // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail.
                            const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times
                            await Promise.all((expectedSymmetricAlgorithm ?
                                [expectedSymmetricAlgorithm] :
                                Array.from(config$1.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms)).map(async (sessionKeyAlgorithm) => {
                                const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket();
                                pkeskPacketCopy.read(serialisedPKESK);
                                const randomSessionKey = {
                                    sessionKeyAlgorithm,
                                    sessionKey: generateSessionKey$1(sessionKeyAlgorithm)
                                };
                                try {
                                    await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey);
                                    decryptedSessionKeyPackets.push(pkeskPacketCopy);
                                }
                                catch (err) {
                                    // `decrypt` can still throw some non-security-sensitive errors
                                    util.printDebugError(err);
                                    exception = err;
                                }
                            }));
                        }
                        else {
                            try {
                                await pkeskPacket.decrypt(decryptionKeyPacket);
                                const symmetricAlgorithm = expectedSymmetricAlgorithm || pkeskPacket.sessionKeyAlgorithm;
                                if (symmetricAlgorithm && !algos.includes(enums.write(enums.symmetric, symmetricAlgorithm))) {
                                    throw new Error('A non-preferred symmetric algorithm was used.');
                                }
                                decryptedSessionKeyPackets.push(pkeskPacket);
                            }
                            catch (err) {
                                util.printDebugError(err);
                                exception = err;
                            }
                        }
                    }));
                }));
                cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory.
                pkeskPacket.encrypted = null;
            }));
        }
        else {
            throw new Error('No key or password specified.');
        }
        if (decryptedSessionKeyPackets.length > 0) {
            // Return only unique session keys
            if (decryptedSessionKeyPackets.length > 1) {
                const seen = new Set();
                decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => {
                    const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);
                    if (seen.has(k)) {
                        return false;
                    }
                    seen.add(k);
                    return true;
                });
            }
            return decryptedSessionKeyPackets.map(packet => ({
                data: packet.sessionKey,
                algorithm: packet.sessionKeyAlgorithm && enums.read(enums.symmetric, packet.sessionKeyAlgorithm)
            }));
        }
        throw exception || new Error('Session key decryption failed.');
    }
    /**
     * Get literal data that is the body of the message
     * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.
     */
    getLiteralData() {
        const msg = this.unwrapCompressed();
        const literal = msg.packets.findPacket(enums.packet.literalData);
        return (literal && literal.getBytes()) || null;
    }
    /**
     * Get filename from literal data packet
     * @returns {(String|null)} Filename of literal data packet as string.
     */
    getFilename() {
        const msg = this.unwrapCompressed();
        const literal = msg.packets.findPacket(enums.packet.literalData);
        return (literal && literal.getFilename()) || null;
    }
    /**
     * Get literal data as text
     * @returns {(String|null)} Literal body of the message interpreted as text.
     */
    getText() {
        const msg = this.unwrapCompressed();
        const literal = msg.packets.findPacket(enums.packet.literalData);
        if (literal) {
            return literal.getText();
        }
        return null;
    }
    /**
     * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.
     * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) to select algorithm preferences for
     * @param {Date} [date] - Date to select algorithm preferences at
     * @param {Array<Object>} [userIDs] - User IDs to select algorithm preferences for
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.
     * @async
     */
    static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config$1 = config) {
        const { symmetricAlgo, aeadAlgo } = await getPreferredCipherSuite(encryptionKeys, date, userIDs, config$1);
        const symmetricAlgoName = enums.read(enums.symmetric, symmetricAlgo);
        const aeadAlgoName = aeadAlgo ? enums.read(enums.aead, aeadAlgo) : undefined;
        await Promise.all(encryptionKeys.map(key => key.getEncryptionKey()
            .catch(() => null) // ignore key strength requirements
            .then(maybeKey => {
            if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519 || maybeKey.keyPacket.algorithm === enums.publicKey.x448) &&
                !aeadAlgoName && !util.isAES(symmetricAlgo)) { // if AEAD is defined, then PKESK v6 are used, and the algo info is encrypted
                throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 and X448 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.');
            }
        })));
        const sessionKeyData = generateSessionKey$1(symmetricAlgo);
        return { data: sessionKeyData, algorithm: symmetricAlgoName, aeadAlgorithm: aeadAlgoName };
    }
    /**
     * Encrypt the message either with public keys, passwords, or both at once.
     * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) for message encryption
     * @param {Array<String>} [passwords] - Password(s) for message encryption
     * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
     * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs
     * @param {Array<module:type/keyid~KeyID>} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]
     * @param {Date} [date] - Override the creation date of the literal package
     * @param {Array<Object>} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Message>} New message with encrypted content.
     * @async
     */
    async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) {
        if (sessionKey) {
            if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {
                throw new Error('Invalid session key for encryption.');
            }
        }
        else if (encryptionKeys && encryptionKeys.length) {
            sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config$1);
        }
        else if (passwords && passwords.length) {
            sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config$1);
        }
        else {
            throw new Error('No keys, passwords, or session key provided.');
        }
        const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey;
        const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config$1);
        const symEncryptedPacket = SymEncryptedIntegrityProtectedDataPacket.fromObject({
            version: aeadAlgorithmName ? 2 : 1,
            aeadAlgorithm: aeadAlgorithmName ? enums.write(enums.aead, aeadAlgorithmName) : null
        });
        symEncryptedPacket.packets = this.packets;
        const algorithm = enums.write(enums.symmetric, algorithmName);
        await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config$1);
        msg.packets.push(symEncryptedPacket);
        symEncryptedPacket.packets = new PacketList(); // remove packets after encryption
        return msg;
    }
    /**
     * Encrypt a session key either with public keys, passwords, or both at once.
     * @param {Uint8Array} sessionKey - session key for encryption
     * @param {String} algorithmName - session key algorithm
     * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb'
     * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) for message encryption
     * @param {Array<String>} [passwords] - For message encryption
     * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs
     * @param {Array<module:type/keyid~KeyID>} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]
     * @param {Date} [date] - Override the date
     * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Message>} New message with encrypted content.
     * @async
     */
    static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) {
        const packetlist = new PacketList();
        const symmetricAlgorithm = enums.write(enums.symmetric, algorithmName);
        const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName);
        if (encryptionKeys) {
            const results = await Promise.all(encryptionKeys.map(async function (primaryKey, i) {
                const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config$1);
                const pkESKeyPacket = PublicKeyEncryptedSessionKeyPacket.fromObject({
                    version: aeadAlgorithm ? 6 : 3,
                    encryptionKeyPacket: encryptionKey.keyPacket,
                    anonymousRecipient: wildcard,
                    sessionKey,
                    sessionKeyAlgorithm: symmetricAlgorithm
                });
                await pkESKeyPacket.encrypt(encryptionKey.keyPacket);
                delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption
                return pkESKeyPacket;
            }));
            packetlist.push(...results);
        }
        if (passwords) {
            const testDecrypt = async function (keyPacket, password) {
                try {
                    await keyPacket.decrypt(password, config$1);
                    return 1;
                }
                catch {
                    return 0;
                }
            };
            const sum = (accumulator, currentValue) => accumulator + currentValue;
            const encryptPassword = async function (sessionKey, algorithm, aeadAlgorithm, password) {
                const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config$1);
                symEncryptedSessionKeyPacket.sessionKey = sessionKey;
                symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;
                if (aeadAlgorithm) {
                    symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;
                }
                await symEncryptedSessionKeyPacket.encrypt(password, config$1);
                if (config$1.passwordCollisionCheck) {
                    const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));
                    if (results.reduce(sum) !== 1) {
                        return encryptPassword(sessionKey, algorithm, password);
                    }
                }
                delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption
                return symEncryptedSessionKeyPacket;
            };
            const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symmetricAlgorithm, aeadAlgorithm, pwd)));
            packetlist.push(...results);
        }
        return new Message(packetlist);
    }
    /**
     * Sign the message (the literal data packet of the message)
     * @param {Array<PrivateKey>} signingKeys - private keys with decrypted secret key data for signing
     * @param {Array<Key>} recipientKeys - recipient keys to get the signing preferences from
     * @param {Signature} [signature] - Any existing detached signature to add to the message
     * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
     * @param {Date} [date] - Override the creation time of the signature
     * @param {Array<UserID>} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
     * @param {Array<UserID>} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from
     * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Message>} New message with signed content.
     * @async
     */
    async sign(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config$1 = config) {
        const packetlist = new PacketList();
        const literalDataPacket = this.packets.findPacket(enums.packet.literalData);
        if (!literalDataPacket) {
            throw new Error('No literal data packet to sign.');
        }
        const signaturePackets = await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, false, config$1); // this returns the existing signature packets as well
        const onePassSignaturePackets = signaturePackets.map((signaturePacket, i) => OnePassSignaturePacket.fromSignaturePacket(signaturePacket, i === 0))
            .reverse(); // innermost OPS refers to the first signature packet
        packetlist.push(...onePassSignaturePackets);
        packetlist.push(literalDataPacket);
        packetlist.push(...signaturePackets);
        return new Message(packetlist);
    }
    /**
     * Compresses the message (the literal and -if signed- signature data packets of the message)
     * @param {module:enums.compression} algo - compression algorithm
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Message} New message with compressed content.
     */
    compress(algo, config$1 = config) {
        if (algo === enums.compression.uncompressed) {
            return this;
        }
        const compressed = new CompressedDataPacket(config$1);
        compressed.algorithm = algo;
        compressed.packets = this.packets;
        const packetList = new PacketList();
        packetList.push(compressed);
        return new Message(packetList);
    }
    /**
     * Create a detached signature for the message (the literal data packet of the message)
     * @param {Array<PrivateKey>} signingKeys - private keys with decrypted secret key data for signing
     * @param {Array<Key>} recipientKeys - recipient keys to get the signing preferences from
     * @param {Signature} [signature] - Any existing detached signature
     * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
     * @param {Date} [date] - Override the creation time of the signature
     * @param {Array<UserID>} [signingUserIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
     * @param {Array<UserID>} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from
     * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Signature>} New detached signature of message content.
     * @async
     */
    async signDetached(signingKeys = [], recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config$1 = config) {
        const literalDataPacket = this.packets.findPacket(enums.packet.literalData);
        if (!literalDataPacket) {
            throw new Error('No literal data packet to sign.');
        }
        return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, true, config$1));
    }
    /**
     * Verify message signatures
     * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
     * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Array<{
     *   keyID: module:type/keyid~KeyID,
     *   signature: Promise<Signature>,
     *   verified: Promise<true>
     * }>>} List of signer's keyID and validity of signatures.
     * @async
     */
    async verify(verificationKeys, date = new Date(), config$1 = config) {
        const msg = this.unwrapCompressed();
        const literalDataList = msg.packets.filterByTag(enums.packet.literalData);
        if (literalDataList.length !== 1) {
            throw new Error('Can only verify message with one literal data packet.');
        }
        let packets = msg.packets;
        if (isArrayStream(packets.stream)) {
            packets = packets.concat(await readToEnd(packets.stream, _ => _ || []));
        }
        const onePassSigList = packets.filterByTag(enums.packet.onePassSignature).reverse();
        const signatureList = packets.filterByTag(enums.packet.signature);
        if (onePassSigList.length && !signatureList.length && util.isStream(packets.stream) && !isArrayStream(packets.stream)) {
            await Promise.all(onePassSigList.map(async (onePassSig) => {
                onePassSig.correspondingSig = new Promise((resolve, reject) => {
                    onePassSig.correspondingSigResolve = resolve;
                    onePassSig.correspondingSigReject = reject;
                });
                onePassSig.signatureData = fromAsync(async () => (await onePassSig.correspondingSig).signatureData);
                onePassSig.hashed = readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));
                onePassSig.hashed.catch(() => { });
            }));
            packets.stream = transformPair(packets.stream, async (readable, writable) => {
                const reader = getReader(readable);
                const writer = getWriter(writable);
                try {
                    for (let i = 0; i < onePassSigList.length; i++) {
                        const { value: signature } = await reader.read();
                        onePassSigList[i].correspondingSigResolve(signature);
                    }
                    await reader.readToEnd();
                    await writer.ready;
                    await writer.close();
                }
                catch (e) {
                    onePassSigList.forEach(onePassSig => {
                        onePassSig.correspondingSigReject(e);
                    });
                    await writer.abort(e);
                }
            });
            return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config$1);
        }
        return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config$1);
    }
    /**
     * Verify detached message signature
     * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
     * @param {Signature} signature
     * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Array<{
     *   keyID: module:type/keyid~KeyID,
     *   signature: Promise<Signature>,
     *   verified: Promise<true>
     * }>>} List of signer's keyID and validity of signature.
     * @async needed to avoid breaking change until next major release
     */
    // eslint-disable-next-line @typescript-eslint/require-await
    async verifyDetached(signature, verificationKeys, date = new Date(), config$1 = config) {
        const msg = this.unwrapCompressed();
        const literalDataList = msg.packets.filterByTag(enums.packet.literalData);
        if (literalDataList.length !== 1) {
            throw new Error('Can only verify message with one literal data packet.');
        }
        const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets
        return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config$1);
    }
    /**
     * Unwrap compressed message
     * @returns {Message} Message Content of compressed message.
     */
    unwrapCompressed() {
        const compressed = this.packets.filterByTag(enums.packet.compressedData);
        if (compressed.length) {
            return new Message(compressed[0].packets);
        }
        return this;
    }
    /**
     * Append signature to unencrypted message object
     * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     */
    async appendSignature(detachedSignature, config$1 = config) {
        await this.packets.read(util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data, allowedDetachedSignaturePackets, config$1);
    }
    /**
     * Returns binary encoded message
     * @returns {ReadableStream<Uint8Array>} Binary message.
     */
    write() {
        return this.packets.write();
    }
    /**
     * Returns ASCII armored text of message
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {ReadableStream<String>} ASCII armor.
     */
    armor(config$1 = config) {
        const trailingPacket = this.packets[this.packets.length - 1];
        // An ASCII-armored Encrypted Message packet sequence that ends in an v2 SEIPD packet MUST NOT contain a CRC24 footer.
        // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.
        const emitChecksum = trailingPacket.constructor.tag === SymEncryptedIntegrityProtectedDataPacket.tag ?
            trailingPacket.version !== 2 :
            this.packets.some(packet => packet.constructor.tag === SignaturePacket.tag && packet.version !== 6);
        return armor(enums.armor.message, this.write(), null, null, null, emitChecksum, config$1);
    }
}
/**
 * Create signature packets for the message
 * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign
 * @param {Array<PrivateKey>} [signingKeys] - private keys with decrypted secret key data for signing
 * @param {Array<Key>} [recipientKeys] - recipient keys to get the signing preferences from
 * @param {Signature} [signature] - Any existing detached signature to append
 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
 * @param {Date} [date] - Override the creationtime of the signature
 * @param {Array<UserID>} [signingUserIDs] - User IDs to sign to, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
 * @param {Array<UserID>} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from
 * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]
 * @param {Array} [signatureSalts] - A list of signature salts matching the number of signingKeys that should be used for v6 signatures
 * @param {Boolean} [detached] - Whether to create detached signature packets
 * @param {Object} [config] - Full configuration, defaults to openpgp.config
 * @returns {Promise<PacketList>} List of signature packets.
 * @async
 * @private
 */
async function createSignaturePackets(literalDataPacket, signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], detached = false, config$1 = config) {
    const packetlist = new PacketList();
    // If data packet was created from Uint8Array, use binary, otherwise use text
    const signatureType = literalDataPacket.text === null ?
        enums.signature.binary : enums.signature.text;
    await Promise.all(signingKeys.map(async (primaryKey, i) => {
        const signingUserID = signingUserIDs[i];
        if (!primaryKey.isPrivate()) {
            throw new Error('Need private key for signing');
        }
        const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, signingUserID, config$1);
        return createSignaturePacket(literalDataPacket, recipientKeys.length ? recipientKeys : [primaryKey], signingKey.keyPacket, { signatureType }, date, recipientUserIDs, notations, detached, config$1);
    })).then(signatureList => {
        packetlist.push(...signatureList);
    });
    if (signature) {
        const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);
        packetlist.push(...existingSigPacketlist);
    }
    return packetlist;
}
/**
 * Create object containing signer's keyID and validity of signature
 * @param {SignaturePacket} signature - Signature packet
 * @param {Array<LiteralDataPacket>} literalDataList - Array of literal data packets
 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
 * @param {Date} [date] - Check signature validity with respect to the given date
 * @param {Boolean} [detached] - Whether to verify detached signature packets
 * @param {Object} [config] - Full configuration, defaults to openpgp.config
 * @returns {{
 *   keyID: module:type/keyid~KeyID,
 *   signature: Promise<Signature>,
 *   verified: Promise<true>
 * }} signer's keyID and validity of signature
 * @async
 * @private
 */
function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) {
    let primaryKey;
    let unverifiedSigningKey;
    for (const key of verificationKeys) {
        const issuerKeys = key.getKeys(signature.issuerKeyID);
        if (issuerKeys.length > 0) {
            primaryKey = key;
            unverifiedSigningKey = issuerKeys[0];
            break;
        }
    }
    const isOnePassSignature = signature instanceof OnePassSignaturePacket;
    const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;
    const verifiedSig = {
        keyID: signature.issuerKeyID,
        verified: (async () => {
            if (!unverifiedSigningKey) {
                throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);
            }
            await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config$1);
            const signaturePacket = await signaturePacketPromise;
            if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {
                throw new Error('Key is newer than the signature');
            }
            // We pass the signature creation time to check whether the key was expired at the time of signing.
            // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before
            try {
                await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config$1);
            }
            catch (e) {
                // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature,
                // making the key invalid at the time of signing.
                // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled.
                // Note: we do not support the edge case of a key that was reformatted and it has expired.
                if (config$1.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) {
                    await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config$1);
                }
                else {
                    throw e;
                }
            }
            return true;
        })(),
        signature: (async () => {
            const signaturePacket = await signaturePacketPromise;
            const packetlist = new PacketList();
            signaturePacket && packetlist.push(signaturePacket);
            return new Signature(packetlist);
        })()
    };
    // Mark potential promise rejections as "handled". This is needed because in
    // some cases, we reject them before the user has a reasonable chance to
    // handle them (e.g. `await readToEnd(result.data); await result.verified` and
    // the data stream errors).
    verifiedSig.signature.catch(() => { });
    verifiedSig.verified.catch(() => { });
    return verifiedSig;
}
/**
 * Create list of objects containing signer's keyID and validity of signature
 * @param {Array<SignaturePacket>} signatureList - Array of signature packets
 * @param {Array<LiteralDataPacket>} literalDataList - Array of literal data packets
 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
 * @param {Date} date - Verify the signature against the given date,
 *                    i.e. check signature creation time < date < expiration time
 * @param {Boolean} [detached] - Whether to verify detached signature packets
 * @param {Object} [config] - Full configuration, defaults to openpgp.config
 * @returns {Array<{
 *   keyID: module:type/keyid~KeyID,
 *   signature: Promise<Signature>,
 *   verified: Promise<true>
 * }>} list of signer's keyID and validity of signatures (one entry per signature packet in input)
 * @private
 */
function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) {
    return signatureList
        .filter(signature => ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType)))
        .map(signature => createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config$1));
}
/**
 * Reads an (optionally armored) OpenPGP message and returns a Message object
 * @param {Object} options
 * @param {String | ReadableStream<String>} [options.armoredMessage] - Armored message to be parsed
 * @param {Uint8Array | ReadableStream<Uint8Array>} [options.binaryMessage] - Binary to be parsed
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<Message>} New message object.
 * @async
 * @static
 */
async function readMessage({ armoredMessage, binaryMessage, config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    let input = armoredMessage || binaryMessage;
    if (!input) {
        throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');
    }
    if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {
        throw new Error('readMessage: options.armoredMessage must be a string or stream');
    }
    if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {
        throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');
    }
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    const streamType = util.isStream(input);
    if (armoredMessage) {
        const { type, data } = await unarmor(input);
        if (type !== enums.armor.message) {
            throw new Error('Armored text not of type message');
        }
        input = data;
    }
    const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config$1, new MessageGrammarValidator());
    const message = new Message(packetlist);
    message.fromStream = streamType;
    return message;
}
/**
 * Creates new message object from text or binary data.
 * @param {Object} options
 * @param {String | ReadableStream<String>} [options.text] - The text message contents
 * @param {Uint8Array | ReadableStream<Uint8Array>} [options.binary] - The binary message contents
 * @param {String} [options.filename=""] - Name of the file (if any)
 * @param {Date} [options.date=current date] - Date of the message, or modification date of the file
 * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type
 * @returns {Promise<Message>} New message object.
 * @async not necessary, but needed to align with readMessage
 * @static
 */
// eslint-disable-next-line @typescript-eslint/require-await
async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {
    const input = text !== undefined ? text : binary;
    if (input === undefined) {
        throw new Error('createMessage: must pass options object containing `text` or `binary`');
    }
    if (text && !util.isString(text) && !util.isStream(text)) {
        throw new Error('createMessage: options.text must be a string or stream');
    }
    if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {
        throw new Error('createMessage: options.binary must be a Uint8Array or stream');
    }
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    const streamType = util.isStream(input);
    const literalDataPacket = new LiteralDataPacket(date);
    if (text !== undefined) {
        literalDataPacket.setText(input, enums.write(enums.literal, format));
    }
    else {
        literalDataPacket.setBytes(input, enums.write(enums.literal, format));
    }
    if (filename !== undefined) {
        literalDataPacket.setFilename(filename);
    }
    const literalDataPacketlist = new PacketList();
    literalDataPacketlist.push(literalDataPacket);
    const message = new Message(literalDataPacketlist);
    message.fromStream = streamType;
    return message;
}

/** @access public */
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// A Cleartext message can contain the following packets
const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
/**
 * Class that represents an OpenPGP cleartext signed message.
 * See {@link https://tools.ietf.org/html/rfc4880#section-7}
 */
class CleartextMessage {
    /**
     * @param {String} text - The cleartext of the signed message
     * @param {Signature} signature - The detached signature or an empty signature for unsigned messages
     */
    constructor(text, signature) {
        // remove trailing whitespace and normalize EOL to canonical form <CR><LF>
        this.text = util.removeTrailingSpaces(text).replace(/\r?\n/g, '\r\n');
        if (signature && !(signature instanceof Signature)) {
            throw new Error('Invalid signature input');
        }
        this.signature = signature || new Signature(new PacketList());
    }
    /**
     * Returns the key IDs of the keys that signed the cleartext message
     * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
     */
    getSigningKeyIDs() {
        const keyIDs = [];
        const signatureList = this.signature.packets;
        signatureList.forEach(function (packet) {
            keyIDs.push(packet.issuerKeyID);
        });
        return keyIDs;
    }
    /**
     * Sign the cleartext message
     * @param {Array<Key>} signingKeys - private keys with decrypted secret key data for signing
     * @param {Array<Key>} recipientKeys - recipient keys to get the signing preferences from
     * @param {Signature} [signature] - Any existing detached signature
     * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]
     * @param {Date} [date] - The creation time of the signature that should be created
     * @param {Array} [signingKeyIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
     * @param {Array} [recipientUserIDs] - User IDs associated with `recipientKeys` to get the signing preferences from
     * @param {Array} [notations] - Notation Data to add to the signatures, e.g. [{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<CleartextMessage>} New cleartext message with signed content.
     * @async
     */
    async sign(signingKeys, recipientKeys = [], signature = null, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], notations = [], config$1 = config) {
        const literalDataPacket = new LiteralDataPacket();
        literalDataPacket.setText(this.text);
        const newSignature = new Signature(await createSignaturePackets(literalDataPacket, signingKeys, recipientKeys, signature, signingKeyIDs, date, signingUserIDs, recipientUserIDs, notations, true, config$1));
        return new CleartextMessage(this.text, newSignature);
    }
    /**
     * Verify signatures of cleartext signed message
     * @param {Array<Key>} keys - Array of keys to verify signatures
     * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {Promise<Array<{
     *   keyID: module:type/keyid~KeyID,
     *   signature: Promise<Signature>,
     *   verified: Promise<true>
     * }>>} List of signer's keyID and validity of signature.
     * @async
     */
    verify(keys, date = new Date(), config$1 = config) {
        const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets
        const literalDataPacket = new LiteralDataPacket();
        // we assume that cleartext signature is generated based on UTF8 cleartext
        literalDataPacket.setText(this.text);
        return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config$1);
    }
    /**
     * Get cleartext
     * @returns {String} Cleartext of message.
     */
    getText() {
        // normalize end of line to \n
        return this.text.replace(/\r\n/g, '\n');
    }
    /**
     * Returns ASCII armored text of cleartext signed message
     * @param {Object} [config] - Full configuration, defaults to openpgp.config
     * @returns {String | ReadableStream<String>} ASCII armor.
     */
    armor(config$1 = config) {
        // emit header and checksum if one of the signatures has a version not 6
        const emitHeaderAndChecksum = this.signature.packets.some(packet => packet.version !== 6);
        const hash = emitHeaderAndChecksum ?
            Array.from(new Set(this.signature.packets.map(packet => enums.read(enums.hash, packet.hashAlgorithm).toUpperCase()))).join() :
            null;
        const body = {
            hash,
            text: this.text,
            data: this.signature.packets.write()
        };
        // An ASCII-armored sequence of Signature packets that only includes v6 Signature packets MUST NOT contain a CRC24 footer.
        return armor(enums.armor.signed, body, undefined, undefined, undefined, emitHeaderAndChecksum, config$1);
    }
}
/**
 * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object
 * @param {Object} options
 * @param {String} options.cleartextMessage - Text to be parsed
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<CleartextMessage>} New cleartext message object.
 * @async
 * @static
 */
async function readCleartextMessage({ cleartextMessage, config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    if (!cleartextMessage) {
        throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');
    }
    if (!util.isString(cleartextMessage)) {
        throw new Error('readCleartextMessage: options.cleartextMessage must be a string');
    }
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    const input = await unarmor(cleartextMessage);
    if (input.type !== enums.armor.signed) {
        throw new Error('No cleartext signed message.');
    }
    const packetlist = await PacketList.fromBinary(input.data, allowedPackets, config$1);
    verifyHeaders(input.headers, packetlist);
    const signature = new Signature(packetlist);
    return new CleartextMessage(input.text, signature);
}
/**
 * Compare hash algorithm specified in the armor header with signatures
 * @param {Array<String>} headers - Armor headers
 * @param {PacketList} packetlist - The packetlist with signature packets
 * @private
 */
function verifyHeaders(headers, packetlist) {
    const checkHashAlgos = function (hashAlgos) {
        const check = packet => algo => packet.hashAlgorithm === algo;
        for (let i = 0; i < packetlist.length; i++) {
            if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {
                return false;
            }
        }
        return true;
    };
    const hashAlgos = [];
    headers.forEach(header => {
        const hashHeader = header.match(/^Hash: (.+)$/); // get header value
        if (hashHeader) {
            const parsedHashIDs = hashHeader[1]
                .replace(/\s/g, '') // remove whitespace
                .split(',')
                .map(hashName => {
                try {
                    return enums.write(enums.hash, hashName.toLowerCase());
                }
                catch {
                    throw new Error('Unknown hash algorithm in armor header: ' + hashName.toLowerCase());
                }
            });
            hashAlgos.push(...parsedHashIDs);
        }
        else {
            throw new Error('Only "Hash" header allowed in cleartext signed message');
        }
    });
    if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {
        throw new Error('Hash algorithm mismatch in armor header and signature');
    }
}
/**
 * Creates a new CleartextMessage object from text
 * @param {Object} options
 * @param {String} options.text
 * @static
 * @async not necessary, but needed to align with createMessage
 */
// eslint-disable-next-line @typescript-eslint/require-await
async function createCleartextMessage({ text, ...rest }) {
    if (!text) {
        throw new Error('createCleartextMessage: must pass options object containing `text`');
    }
    if (!util.isString(text)) {
        throw new Error('createCleartextMessage: options.text must be a string');
    }
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    return new CleartextMessage(text);
}

/** @access public */
// OpenPGP.js - An OpenPGP implementation in javascript
// Copyright (C) 2016 Tankred Hase
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//////////////////////
//                  //
//   Key handling   //
//                  //
//////////////////////
/**
 * Generates a new OpenPGP key pair. Supports RSA and ECC keys, as well as the newer Curve448 and Curve25519 keys.
 * By default, primary and subkeys will be of same type.
 * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.
 * @param {Object} options
 * @param {Object|Array<Object>} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`
 * @param {'ecc'|'rsa'|'curve448'|'curve25519'} [options.type='ecc'] - The primary key algorithm type: ECC (default for v4 keys), RSA, Curve448 or Curve25519 (new format, default for v6 keys).
 *                                                                     Note: Curve448 and Curve25519 (new format) are not widely supported yet.
 * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted or empty, the key won't be encrypted.
 * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys
 * @param {String} [options.curve='curve25519Legacy'] - Elliptic curve for ECC keys:
 *                                             curve25519Legacy (default), nistP256, nistP384, nistP521, secp256k1,
 *                                             brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1
 * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures
 * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires
 * @param {Array<Object>} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`
 *                                             default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt
 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys
 * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the primary self-signature, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<Object>} The generated key object in the form:
 *                                     { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }
 * @async
 * @static
 */
async function generateKey({ userIDs = [], passphrase, type, curve, rsaBits = 4096, keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', signatureNotations = [], config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    checkConfig(config$1);
    if (!type && !curve) {
        type = config$1.v6Keys ? 'curve25519' : 'ecc'; // default to new curve25519 for v6 keys (legacy curve25519 cannot be used with them)
        curve = 'curve25519Legacy'; // unused with type != 'ecc'
    }
    else {
        type = type || 'ecc';
        curve = curve || 'curve25519Legacy';
    }
    userIDs = toArray(userIDs);
    signatureNotations = toArray(signatureNotations);
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    if (userIDs.length === 0 && !config$1.v6Keys) {
        throw new Error('UserIDs are required for V4 keys');
    }
    if (type === 'rsa' && rsaBits < config$1.minRSABits) {
        throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${rsaBits}`);
    }
    const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys, signatureNotations };
    try {
        const { key, revocationCertificate } = await generate(options, config$1);
        key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config$1));
        return {
            privateKey: formatObject(key, format, config$1),
            publicKey: formatObject(key.toPublic(), format, config$1),
            revocationCertificate
        };
    }
    catch (err) {
        throw util.wrapError('Error generating keypair', err);
    }
}
/**
 * Reformats signature packets for a key and rewraps key object.
 * @param {Object} options
 * @param {PrivateKey} options.privateKey - Private key to reformat
 * @param {Object|Array<Object>} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`
 * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted or empty, the key won't be encrypted.
 * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires
 * @param {Date}   [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended
 *                                  to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key.
 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys
 * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the primary self-signature, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<Object>} The generated key object in the form:
 *                                     { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }
 * @async
 * @static
 */
async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', signatureNotations = [], config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    checkConfig(config$1);
    userIDs = toArray(userIDs);
    signatureNotations = toArray(signatureNotations);
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    if (userIDs.length === 0 && privateKey.keyPacket.version !== 6) {
        throw new Error('UserIDs are required for V4 keys');
    }
    const options = { privateKey, userIDs, passphrase, keyExpirationTime, date, signatureNotations };
    try {
        const { key: reformattedKey, revocationCertificate } = await reformat(options, config$1);
        return {
            privateKey: formatObject(reformattedKey, format, config$1),
            publicKey: formatObject(reformattedKey.toPublic(), format, config$1),
            revocationCertificate
        };
    }
    catch (err) {
        throw util.wrapError('Error reformatting keypair', err);
    }
}
/**
 * Revokes a key. Requires either a private key or a revocation certificate.
 *   If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.
 * @param {Object} options
 * @param {Key} options.key - Public or private key to revoke
 * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with
 * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation
 * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation
 * @param {String} [options.reasonForRevocation.string=""] - String explaining the reason for revocation
 * @param {Date} [options.date] - Use the given date instead of the current time to verify validity of revocation certificate (if provided), or as creation time of the revocation signature
 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<Object>} The revoked key in the form:
 *                              { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or
 *                              { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise
 * @async
 * @static
 */
async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    checkConfig(config$1);
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    try {
        const revokedKey = revocationCertificate ?
            await key.applyRevocationCertificate(revocationCertificate, date, config$1) :
            await key.revoke(reasonForRevocation, date, config$1);
        return revokedKey.isPrivate() ? {
            privateKey: formatObject(revokedKey, format, config$1),
            publicKey: formatObject(revokedKey.toPublic(), format, config$1)
        } : {
            privateKey: null,
            publicKey: formatObject(revokedKey, format, config$1)
        };
    }
    catch (err) {
        throw util.wrapError('Error revoking key', err);
    }
}
/**
 * Unlock a private key with the given passphrase.
 * This method does not change the original key.
 * @param {Object} options
 * @param {PrivateKey} options.privateKey - The private key to decrypt
 * @param {String|Array<String>} options.passphrase - The user's passphrase(s)
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<PrivateKey>} The unlocked key object.
 * @async
 */
async function decryptKey({ privateKey, passphrase, config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    checkConfig(config$1);
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    if (!privateKey.isPrivate()) {
        throw new Error('Cannot decrypt a public key');
    }
    const clonedPrivateKey = privateKey.clone(true);
    const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];
    try {
        await Promise.all(clonedPrivateKey.getKeys().map(key => (
        // try to decrypt each key with any of the given passphrases
        util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase, config$1))))));
        await clonedPrivateKey.validate(config$1);
        return clonedPrivateKey;
    }
    catch (err) {
        clonedPrivateKey.clearPrivateParams();
        throw util.wrapError('Error decrypting private key', err);
    }
}
/**
 * Lock a private key with the given passphrase.
 * This method does not change the original key.
 * @param {Object} options
 * @param {PrivateKey} options.privateKey - The private key to encrypt
 * @param {String|Array<String>} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<PrivateKey>} The locked key object.
 * @async
 */
async function encryptKey({ privateKey, passphrase, config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    checkConfig(config$1);
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    if (!privateKey.isPrivate()) {
        throw new Error('Cannot encrypt a public key');
    }
    const clonedPrivateKey = privateKey.clone(true);
    const keys = clonedPrivateKey.getKeys();
    const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);
    if (passphrases.length !== keys.length) {
        throw new Error('Invalid number of passphrases given for key encryption');
    }
    try {
        await Promise.all(keys.map(async (key, i) => {
            const { keyPacket } = key;
            await keyPacket.encrypt(passphrases[i], config$1);
            keyPacket.clearPrivateParams();
        }));
        return clonedPrivateKey;
    }
    catch (err) {
        clonedPrivateKey.clearPrivateParams();
        throw util.wrapError('Error encrypting private key', err);
    }
}
///////////////////////////////////////////
//                                       //
//   Message encryption and decryption   //
//                                       //
///////////////////////////////////////////
/**
 * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys`
 *   must be specified. If signing keys are specified, those will be used to sign the message.
 * @param {Object} options
 * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}
 * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message
 * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed
 * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message
 * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`
 * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message
 * @param {Signature} [options.signature] - A detached signature to add to the encrypted message
 * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs
 * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each `signingKeyIDs[i]` corresponds to `signingKeys[i]`
 * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each `encryptionKeyIDs[i]` corresponds to `encryptionKeys[i]`
 * @param {Date} [options.date=current date] - Override the creation date of the message signature
 * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`
 * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Robert Receiver', email: 'robert@openpgp.org' }]`
 * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<MaybeStream<String>|MaybeStream<Uint8Array>>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).
 * @async
 * @static
 */
async function encrypt({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    checkConfig(config$1);
    checkMessage(message);
    checkOutputMessageFormat(format);
    encryptionKeys = toArray(encryptionKeys);
    signingKeys = toArray(signingKeys);
    passwords = toArray(passwords);
    signingKeyIDs = toArray(signingKeyIDs);
    encryptionKeyIDs = toArray(encryptionKeyIDs);
    signingUserIDs = toArray(signingUserIDs);
    encryptionUserIDs = toArray(encryptionUserIDs);
    signatureNotations = toArray(signatureNotations);
    if (rest.detached) {
        throw new Error("The `detached` option has been removed from openpgp.encrypt, separately call openpgp.sign instead. Don't forget to remove the `privateKeys` option as well.");
    }
    if (rest.publicKeys)
        throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');
    if (rest.privateKeys)
        throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');
    if (rest.armor !== undefined)
        throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    if (!signingKeys) {
        signingKeys = [];
    }
    try {
        if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified
            message = await message.sign(signingKeys, encryptionKeys, signature, signingKeyIDs, date, signingUserIDs, encryptionKeyIDs, signatureNotations, config$1);
        }
        message = message.compress(await getPreferredCompressionAlgo(encryptionKeys, date, encryptionUserIDs, config$1), config$1);
        message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1);
        if (format === 'object')
            return message;
        // serialize data
        const armor = format === 'armored';
        const data = armor ? message.armor(config$1) : message.write();
        return await convertStream(data);
    }
    catch (err) {
        throw util.wrapError('Error encrypting message', err);
    }
}
/**
 * Decrypts a message with the user's private key, a session key or a password.
 * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).
 * @param {Object} options
 * @param {Message} options.message - The message object with the encrypted data
 * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key
 * @param {String|String[]} [options.passwords] - Passwords to decrypt the message
 * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }
 * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures
 * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys
 * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.
 * @param {Signature} [options.signature] - Detached signature for verification
 * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<Object>} Object containing decrypted and verified message in the form:
 *
 *     {
 *       data: MaybeStream<String>, (if format was 'utf8', the default)
 *       data: MaybeStream<Uint8Array>, (if format was 'binary')
 *       filename: String,
 *       signatures: [
 *         {
 *           keyID: module:type/keyid~KeyID,
 *           verified: Promise<true>,
 *           signature: Promise<Signature>
 *         }, ...
 *       ]
 *     }
 *
 *     where `signatures` contains a separate entry for each signature packet found in the input message.
 * @async
 * @static
 */
async function decrypt({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    checkConfig(config$1);
    checkMessage(message);
    verificationKeys = toArray(verificationKeys);
    decryptionKeys = toArray(decryptionKeys);
    passwords = toArray(passwords);
    sessionKeys = toArray(sessionKeys);
    if (rest.privateKeys)
        throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');
    if (rest.publicKeys)
        throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    try {
        const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config$1);
        if (!verificationKeys) {
            verificationKeys = [];
        }
        const result = {};
        result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config$1) : await decrypted.verify(verificationKeys, date, config$1);
        result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();
        result.filename = decrypted.getFilename();
        linkStreams(result, message, ...new Set([decrypted, decrypted.unwrapCompressed()]));
        if (expectSigned) {
            if (verificationKeys.length === 0) {
                throw new Error('Verification keys are required to verify message signatures');
            }
            if (result.signatures.length === 0) {
                throw new Error('Message is not signed');
            }
            result.data = concat([
                result.data,
                fromAsync(async () => {
                    await util.anyPromise(result.signatures.map(sig => sig.verified));
                    return format === 'binary' ? new Uint8Array() : '';
                })
            ]);
        }
        result.data = await convertStream(result.data);
        return result;
    }
    catch (err) {
        throw util.wrapError('Error decrypting message', err);
    }
}
//////////////////////////////////////////
//                                      //
//   Message signing and verification   //
//                                      //
//////////////////////////////////////////
/**
 * Signs a message.
 * @param {Object} options
 * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed
 * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext
 * @param {Key|Key[]} options.recipientKeys - Array of keys or single to get the signing preferences from
 * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message
 * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature
 * @param {KeyID|KeyID[]} [options.signingKeyIDs=latest-created valid signing (sub)keys] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
 * @param {Date} [options.date=current date] - Override the creation date of the signature
 * @param {Object|Object[]} [options.signingUserIDs=primary user IDs] - Array of user IDs to sign with, one per key in `signingKeys`, e.g. `[{ name: 'Steve Sender', email: 'steve@openpgp.org' }]`
 * @param {Object|Object[]} [options.recipientUserIDs=primary user IDs] - Array of user IDs to get the signing preferences from, one per key in `recipientKeys`
 * @param {Object|Object[]} [options.signatureNotations=[]] - Array of notations to add to the signatures, e.g. `[{ name: 'test@example.org', value: new TextEncoder().encode('test'), humanReadable: true, critical: false }]`
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<MaybeStream<String|Uint8Array>>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).
 * @async
 * @static
 */
async function sign({ message, signingKeys, recipientKeys = [], format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], recipientUserIDs = [], signatureNotations = [], config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    checkConfig(config$1);
    checkCleartextOrMessage(message);
    checkOutputMessageFormat(format);
    signingKeys = toArray(signingKeys);
    signingKeyIDs = toArray(signingKeyIDs);
    signingUserIDs = toArray(signingUserIDs);
    recipientKeys = toArray(recipientKeys);
    recipientUserIDs = toArray(recipientUserIDs);
    signatureNotations = toArray(signatureNotations);
    if (rest.privateKeys)
        throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');
    if (rest.armor !== undefined)
        throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    if (message instanceof CleartextMessage && format === 'binary')
        throw new Error('Cannot return signed cleartext message in binary format');
    if (message instanceof CleartextMessage && detached)
        throw new Error('Cannot detach-sign a cleartext message');
    if (!signingKeys || signingKeys.length === 0) {
        throw new Error('No signing keys provided');
    }
    try {
        let signature;
        if (detached) {
            signature = await message.signDetached(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config$1);
        }
        else {
            signature = await message.sign(signingKeys, recipientKeys, undefined, signingKeyIDs, date, signingUserIDs, recipientUserIDs, signatureNotations, config$1);
        }
        if (format === 'object')
            return signature;
        const armor = format === 'armored';
        signature = armor ? signature.armor(config$1) : signature.write();
        if (detached) {
            signature = transformPair(message.packets.write(), async (readable, writable) => {
                await Promise.all([
                    pipe(signature, writable),
                    readToEnd(readable).catch(() => { })
                ]);
            });
        }
        return await convertStream(signature);
    }
    catch (err) {
        throw util.wrapError('Error signing message', err);
    }
}
/**
 * Verifies signatures of cleartext signed message
 * @param {Object} options
 * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures
 * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures
 * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys
 * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.
 * @param {Signature} [options.signature] - Detached signature for verification
 * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<Object>} Object containing verified message in the form:
 *
 *     {
 *       data: MaybeStream<String>, (if `message` was a CleartextMessage)
 *       data: MaybeStream<Uint8Array>, (if `message` was a Message)
 *       signatures: [
 *         {
 *           keyID: module:type/keyid~KeyID,
 *           verified: Promise<true>,
 *           signature: Promise<Signature>
 *         }, ...
 *       ]
 *     }
 *
 *     where `signatures` contains a separate entry for each signature packet found in the input message.
 * @async
 * @static
 */
async function verify({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    checkConfig(config$1);
    checkCleartextOrMessage(message);
    verificationKeys = toArray(verificationKeys);
    if (rest.publicKeys)
        throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    if (message instanceof CleartextMessage && format === 'binary')
        throw new Error("Can't return cleartext message data as binary");
    if (message instanceof CleartextMessage && signature)
        throw new Error("Can't verify detached cleartext signature");
    try {
        const result = {};
        if (signature) {
            result.signatures = await message.verifyDetached(signature, verificationKeys, date, config$1);
        }
        else {
            result.signatures = await message.verify(verificationKeys, date, config$1);
        }
        result.data = format === 'binary' ? message.getLiteralData() : message.getText();
        if (message.fromStream && !signature) {
            linkStreams(result, ...new Set([message, message.unwrapCompressed()]));
        }
        if (expectSigned) {
            if (result.signatures.length === 0) {
                throw new Error('Message is not signed');
            }
            result.data = concat([
                result.data,
                fromAsync(async () => {
                    await util.anyPromise(result.signatures.map(sig => sig.verified));
                    return format === 'binary' ? new Uint8Array() : '';
                })
            ]);
        }
        result.data = await convertStream(result.data);
        return result;
    }
    catch (err) {
        throw util.wrapError('Error verifying signed message', err);
    }
}
///////////////////////////////////////////////
//                                           //
//   Session key encryption and decryption   //
//                                           //
///////////////////////////////////////////////
/**
 * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any.
 * @param {Object} options
 * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key used to select algorithm preferences for. If no keys are given, the algorithm will be [config.preferredSymmetricAlgorithm]{@link module:config.preferredSymmetricAlgorithm}
 * @param {Date} [options.date=current date] - Date to select algorithm preferences at
 * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.
 * @async
 * @static
 */
async function generateSessionKey({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    checkConfig(config$1);
    encryptionKeys = toArray(encryptionKeys);
    encryptionUserIDs = toArray(encryptionUserIDs);
    if (rest.publicKeys)
        throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    try {
        const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config$1);
        return sessionKeys;
    }
    catch (err) {
        throw util.wrapError('Error generating session key', err);
    }
}
/**
 * Encrypt a symmetric session key with public keys, passwords, or both at once.
 * At least one of `encryptionKeys` or `passwords` must be specified.
 * @param {Object} options
 * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)
 * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'
 * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'
 * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key
 * @param {String|String[]} [options.passwords] - Passwords for the message
 * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value
 * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs
 * @param {KeyID|KeyID[]} [options.encryptionKeyIDs=latest-created valid encryption (sub)keys] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]
 * @param {Date} [options.date=current date] - Override the date
 * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - Array of user IDs to encrypt for, one per key in `encryptionKeys`, e.g. `[{ name: 'Phil Zimmermann', email: 'phil@openpgp.org' }]`
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<String|Uint8Array>} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).
 * @async
 * @static
 */
async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    checkConfig(config$1);
    checkBinary(data);
    checkString(algorithm, 'algorithm');
    checkOutputMessageFormat(format);
    encryptionKeys = toArray(encryptionKeys);
    passwords = toArray(passwords);
    encryptionKeyIDs = toArray(encryptionKeyIDs);
    encryptionUserIDs = toArray(encryptionUserIDs);
    if (rest.publicKeys)
        throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) {
        throw new Error('No encryption keys or passwords provided.');
    }
    try {
        const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1);
        return formatObject(message, format, config$1);
    }
    catch (err) {
        throw util.wrapError('Error encrypting session key', err);
    }
}
/**
 * Decrypt symmetric session keys using private keys or passwords (not both).
 * One of `decryptionKeys` or `passwords` must be specified.
 * @param {Object} options
 * @param {Message} options.message - A message object containing the encrypted session key packets
 * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data
 * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key
 * @param {Date} [options.date] - Date to use for key verification instead of the current time
 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
 * @returns {Promise<Object[]>} Array of decrypted session key, algorithm pairs in the form:
 *                                            { data:Uint8Array, algorithm:String }
 * @throws if no session key could be found or decrypted
 * @async
 * @static
 */
async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config: config$1, ...rest }) {
    config$1 = { ...config, ...config$1 };
    checkConfig(config$1);
    checkMessage(message);
    decryptionKeys = toArray(decryptionKeys);
    passwords = toArray(passwords);
    if (rest.privateKeys)
        throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');
    const unknownOptions = Object.keys(rest);
    if (unknownOptions.length > 0)
        throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
    try {
        const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, undefined, date, config$1);
        return sessionKeys;
    }
    catch (err) {
        throw util.wrapError('Error decrypting session keys', err);
    }
}
//////////////////////////
//                      //
//   Helper functions   //
//                      //
//////////////////////////
/**
 * Input validation
 * @private
 */
function checkString(data, name) {
    if (!util.isString(data)) {
        throw new Error('Parameter [' + (name) + '] must be of type String');
    }
}
function checkBinary(data, name) {
    if (!util.isUint8Array(data)) {
        throw new Error('Parameter [' + ('data') + '] must be of type Uint8Array');
    }
}
function checkMessage(message) {
    if (!(message instanceof Message)) {
        throw new Error('Parameter [message] needs to be of type Message');
    }
}
function checkCleartextOrMessage(message) {
    if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {
        throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');
    }
}
function checkOutputMessageFormat(format) {
    if (format !== 'armored' && format !== 'binary' && format !== 'object') {
        throw new Error(`Unsupported format ${format}`);
    }
}
const defaultConfigPropsCount = Object.keys(config).length;
function checkConfig(config$1) {
    const inputConfigProps = Object.keys(config$1);
    if (inputConfigProps.length !== defaultConfigPropsCount) {
        for (const inputProp of inputConfigProps) {
            if (config[inputProp] === undefined) {
                throw new Error(`Unknown config property: ${inputProp}`);
            }
        }
    }
}
/**
 * Normalize parameter to an array if it is not undefined.
 * @param {Object} param - the parameter to be normalized
 * @returns {Array<Object>|undefined} The resulting array or undefined.
 * @private
 */
function toArray(param) {
    if (param && !util.isArray(param)) {
        param = [param];
    }
    return param;
}
/**
 * Convert data to or from Stream
 * @param {Object} data - the data to convert
 * @returns {Promise<Object>} The data in the respective format.
 * @async
 * @private
 */
async function convertStream(data) {
    const streamType = util.isStream(data);
    if (streamType === 'array') {
        return readToEnd(data);
    }
    return data;
}
/**
 * Link result.data to the input message stream for cancellation.
 * Also, forward errors in the input message and intermediate messages to result.data.
 * @param {Object} result - the data to convert
 * @param {Message} message - message object provided by the user
 * @param {Message} intermediateMessages - intermediate message object with packet streams to link
 * @returns {Object}
 * @private
 */
function linkStreams(result, inputMessage, ...intermediateMessages) {
    result.data = transformPair(inputMessage.packets.stream, async (readable, writable) => {
        await pipe(result.data, writable, {
            preventClose: true
        });
        const writer = getWriter(writable);
        try {
            // Forward errors in the message streams to result.data.
            await readToEnd(readable, _ => _);
            await Promise.all(intermediateMessages.map(intermediate => readToEnd(intermediate.packets.stream, _ => _)));
            // if result.data throws, the writable will be in errored state, and `close()` fails, but its ok.
            await writer.close();
        }
        catch (e) {
            await writer.abort(e);
        }
    });
}
/**
 * Convert the object to the given format
 * @param {Key|Message} object
 * @param {'armored'|'binary'|'object'} format
 * @param {Object} config - Full configuration
 * @returns {String|Uint8Array|Object}
 * @access private
 */
function formatObject(object, format, config) {
    switch (format) {
        case 'object':
            return object;
        case 'armored':
            return object.armor(config);
        case 'binary':
            return object.write();
        default:
            throw new Error(`Unsupported format ${format}`);
    }
}

/**
 * Internal webcrypto alias.
 * We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.
 * Falls back to Node.js built-in crypto for Node.js <=v14.
 * See utils.ts for details.
 * @module
 */
// @ts-ignore
const crypto$2 = nc && typeof nc === 'object' && 'webcrypto' in nc
    ? nc.webcrypto
    : nc && typeof nc === 'object' && 'randomBytes' in nc
        ? nc
        : undefined;

/**
 * Utilities for hex, bytes, CSPRNG.
 * @module
 */
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is positive integer. */
function anumber(n) {
    if (!Number.isSafeInteger(n) || n < 0)
        throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/** Asserts something is hash */
function ahash(h) {
    if (typeof h !== 'function' || typeof h.create !== 'function')
        throw new Error('Hash should be wrapped by utils.createHasher');
    anumber(h.outputLen);
    anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
function aexists(instance, checkFinished = true) {
    if (instance.destroyed)
        throw new Error('Hash instance has been destroyed');
    if (checkFinished && instance.finished)
        throw new Error('Hash#digest() has already been called');
}
/** Asserts output is properly-sized byte array */
function aoutput(out, instance) {
    abytes(out);
    const min = instance.outputLen;
    if (out.length < min) {
        throw new Error('digestInto() expects output buffer of length at least ' + min);
    }
}
/** Cast u8 / u16 / u32 to u32. */
function u32(arr) {
    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
function clean(...arrays) {
    for (let i = 0; i < arrays.length; i++) {
        arrays[i].fill(0);
    }
}
/** Create DataView of an array for easy byte-level manipulation. */
function createView(arr) {
    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
function rotr(word, shift) {
    return (word << (32 - shift)) | (word >>> shift);
}
/** The rotate left (circular left shift) operation for uint32 */
function rotl(word, shift) {
    return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/** The byte swap operation for uint32 */
function byteSwap(word) {
    return (((word << 24) & 0xff000000) |
        ((word << 8) & 0xff0000) |
        ((word >>> 8) & 0xff00) |
        ((word >>> 24) & 0xff));
}
/** In place byte swap for Uint32Array */
function byteSwap32(arr) {
    for (let i = 0; i < arr.length; i++) {
        arr[i] = byteSwap(arr[i]);
    }
    return arr;
}
const swap32IfBE = isLE
    ? (u) => u
    : byteSwap32;
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
const hasHexBuiltin = /* @__PURE__ */ (() => 
// @ts-ignore
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
 * Convert byte array to hex string. Uses built-in function, when available.
 * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
 */
function bytesToHex(bytes) {
    abytes(bytes);
    // @ts-ignore
    if (hasHexBuiltin)
        return bytes.toHex();
    // pre-caching improves the speed 6x
    let hex = '';
    for (let i = 0; i < bytes.length; i++) {
        hex += hexes[bytes[i]];
    }
    return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
    if (ch >= asciis._0 && ch <= asciis._9)
        return ch - asciis._0; // '2' => 50-48
    if (ch >= asciis.A && ch <= asciis.F)
        return ch - (asciis.A - 10); // 'B' => 66-(65-10)
    if (ch >= asciis.a && ch <= asciis.f)
        return ch - (asciis.a - 10); // 'b' => 98-(97-10)
    return;
}
/**
 * Convert hex string to byte array. Uses built-in function, when available.
 * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
 */
function hexToBytes(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    // @ts-ignore
    if (hasHexBuiltin)
        return Uint8Array.fromHex(hex);
    const hl = hex.length;
    const al = hl / 2;
    if (hl % 2)
        throw new Error('hex string expected, got unpadded hex of length ' + hl);
    const array = new Uint8Array(al);
    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
        const n1 = asciiToBase16(hex.charCodeAt(hi));
        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
        if (n1 === undefined || n2 === undefined) {
            const char = hex[hi] + hex[hi + 1];
            throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
        }
        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
    }
    return array;
}
/**
 * Converts string to bytes using UTF8 encoding.
 * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
 */
function utf8ToBytes(str) {
    if (typeof str !== 'string')
        throw new Error('string expected');
    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
 * Normalizes (non-hex) string or Uint8Array to Uint8Array.
 * Warning: when Uint8Array is passed, it would NOT get copied.
 * Keep in mind for future mutable operations.
 */
function toBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/** Copies several Uint8Arrays into one. */
function concatBytes(...arrays) {
    let sum = 0;
    for (let i = 0; i < arrays.length; i++) {
        const a = arrays[i];
        abytes(a);
        sum += a.length;
    }
    const res = new Uint8Array(sum);
    for (let i = 0, pad = 0; i < arrays.length; i++) {
        const a = arrays[i];
        res.set(a, pad);
        pad += a.length;
    }
    return res;
}
/** For runtime check if class implements interface */
class Hash {
}
/** Wraps hash function, creating an interface on top of it */
function createHasher(hashCons) {
    const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
    const tmp = hashCons();
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = () => hashCons();
    return hashC;
}
function createXOFer(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
const wrapConstructor = createHasher;
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
function randomBytes(bytesLength = 32) {
    if (crypto$2 && typeof crypto$2.getRandomValues === 'function') {
        return crypto$2.getRandomValues(new Uint8Array(bytesLength));
    }
    // Legacy Node.js compatibility
    if (crypto$2 && typeof crypto$2.randomBytes === 'function') {
        return Uint8Array.from(crypto$2.randomBytes(bytesLength));
    }
    throw new Error('crypto.getRandomValues must be defined');
}

/**
 * Hex, bytes and number utilities.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n$6 = /* @__PURE__ */ BigInt(0);
const _1n$7 = /* @__PURE__ */ BigInt(1);
// tmp name until v2
function _abool2(value, title = '') {
    if (typeof value !== 'boolean') {
        const prefix = title && `"${title}"`;
        throw new Error(prefix + 'expected boolean, got type=' + typeof value);
    }
    return value;
}
// tmp name until v2
/** Asserts something is Uint8Array. */
function _abytes2(value, length, title = '') {
    const bytes = isBytes(value);
    const len = value?.length;
    const needsLen = length !== undefined;
    if (!bytes || (needsLen && len !== length)) {
        const prefix = title && `"${title}" `;
        const ofLen = needsLen ? ` of length ${length}` : '';
        const got = bytes ? `length=${len}` : `type=${typeof value}`;
        throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
    }
    return value;
}
// Used in weierstrass, der
function numberToHexUnpadded(num) {
    const hex = num.toString(16);
    return hex.length & 1 ? '0' + hex : hex;
}
function hexToNumber(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    return hex === '' ? _0n$6 : BigInt('0x' + hex); // Big Endian
}
// BE: Big Endian, LE: Little Endian
function bytesToNumberBE(bytes) {
    return hexToNumber(bytesToHex(bytes));
}
function bytesToNumberLE(bytes) {
    abytes(bytes);
    return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
}
function numberToBytesBE(n, len) {
    return hexToBytes(n.toString(16).padStart(len * 2, '0'));
}
function numberToBytesLE(n, len) {
    return numberToBytesBE(n, len).reverse();
}
/**
 * Takes hex string or Uint8Array, converts to Uint8Array.
 * Validates output length.
 * Will throw error for other types.
 * @param title descriptive title for an error e.g. 'secret key'
 * @param hex hex string or Uint8Array
 * @param expectedLength optional, will compare to result array's length
 * @returns
 */
function ensureBytes(title, hex, expectedLength) {
    let res;
    if (typeof hex === 'string') {
        try {
            res = hexToBytes(hex);
        }
        catch (e) {
            throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
        }
    }
    else if (isBytes(hex)) {
        // Uint8Array.from() instead of hash.slice() because node.js Buffer
        // is instance of Uint8Array, and its slice() creates **mutable** copy
        res = Uint8Array.from(hex);
    }
    else {
        throw new Error(title + ' must be hex string or Uint8Array');
    }
    const len = res.length;
    if (typeof expectedLength === 'number' && len !== expectedLength)
        throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
    return res;
}
/**
 * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
 * and Buffer#slice creates mutable copy. Never use Buffers!
 */
function copyBytes(bytes) {
    return Uint8Array.from(bytes);
}
/**
 * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
 * Should be safe to use for things expected to be ASCII.
 * Returns exact same result as utf8ToBytes for ASCII or throws.
 */
function asciiToBytes(ascii) {
    return Uint8Array.from(ascii, (c, i) => {
        const charCode = c.charCodeAt(0);
        if (c.length !== 1 || charCode > 127) {
            throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
        }
        return charCode;
    });
}
/**
 * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
 */
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
// Is positive bigint
const isPosBig = (n) => typeof n === 'bigint' && _0n$6 <= n;
function inRange(n, min, max) {
    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
/**
 * Asserts min <= n < max. NOTE: It's < max and not <= max.
 * @example
 * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
 */
function aInRange(title, n, min, max) {
    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
    // consider P=256n, min=0n, max=P
    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`
    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`
    // - our way is the cleanest:               `inRange('x', x, 0n, P)
    if (!inRange(n, min, max))
        throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
}
// Bit operations
/**
 * Calculates amount of bits in a bigint.
 * Same as `n.toString(2).length`
 * TODO: merge with nLength in modular
 */
function bitLen(n) {
    let len;
    for (len = 0; n > _0n$6; n >>= _1n$7, len += 1)
        ;
    return len;
}
/**
 * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
 * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
 */
const bitMask = (n) => (_1n$7 << BigInt(n)) - _1n$7;
/**
 * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
 * @returns function that will call DRBG until 2nd arg returns something meaningful
 * @example
 *   const drbg = createHmacDRBG<Key>(32, 32, hmac);
 *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
 */
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
    if (typeof hashLen !== 'number' || hashLen < 2)
        throw new Error('hashLen must be a number');
    if (typeof qByteLen !== 'number' || qByteLen < 2)
        throw new Error('qByteLen must be a number');
    if (typeof hmacFn !== 'function')
        throw new Error('hmacFn must be a function');
    // Step B, Step C: set hashLen to 8*ceil(hlen/8)
    const u8n = (len) => new Uint8Array(len); // creates Uint8Array
    const u8of = (byte) => Uint8Array.of(byte); // another shortcut
    let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
    let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
    let i = 0; // Iterations counter, will throw when over 1000
    const reset = () => {
        v.fill(1);
        k.fill(0);
        i = 0;
    };
    const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
    const reseed = (seed = u8n(0)) => {
        // HMAC-DRBG reseed() function. Steps D-G
        k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
        v = h(); // v = hmac(k || v)
        if (seed.length === 0)
            return;
        k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
        v = h(); // v = hmac(k || v)
    };
    const gen = () => {
        // HMAC-DRBG generate() function
        if (i++ >= 1000)
            throw new Error('drbg: tried 1000 values');
        let len = 0;
        const out = [];
        while (len < qByteLen) {
            v = h();
            const sl = v.slice();
            out.push(sl);
            len += v.length;
        }
        return concatBytes(...out);
    };
    const genUntil = (seed, pred) => {
        reset();
        reseed(seed); // Steps D-G
        let res = undefined; // Step H: grind until k is in [1..n-1]
        while (!(res = pred(gen())))
            reseed();
        reset();
        return res;
    };
    return genUntil;
}
function _validateObject(object, fields, optFields = {}) {
    if (!object || typeof object !== 'object')
        throw new Error('expected valid options object');
    function checkField(fieldName, expectedType, isOpt) {
        const val = object[fieldName];
        if (isOpt && val === undefined)
            return;
        const current = typeof val;
        if (current !== expectedType || val === null)
            throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
    }
    Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
    Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
/**
 * Memoizes (caches) computation result.
 * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
 */
function memoized(fn) {
    const map = new WeakMap();
    return (arg, ...args) => {
        const val = map.get(arg);
        if (val !== undefined)
            return val;
        const computed = fn(arg, ...args);
        map.set(arg, computed);
        return computed;
    };
}

/**
 * Utils for modular division and fields.
 * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
 * There is no division: it is replaced by modular multiplicative inverse.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// prettier-ignore
const _0n$5 = BigInt(0), _1n$6 = BigInt(1), _2n$6 = /* @__PURE__ */ BigInt(2), _3n$2 = /* @__PURE__ */ BigInt(3);
// prettier-ignore
const _4n$1 = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n$1 = /* @__PURE__ */ BigInt(7);
// prettier-ignore
const _8n$1 = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
// Calculates a modulo b
function mod(a, b) {
    const result = a % b;
    return result >= _0n$5 ? result : b + result;
}
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
function pow2(x, power, modulo) {
    let res = x;
    while (power-- > _0n$5) {
        res *= res;
        res %= modulo;
    }
    return res;
}
/**
 * Inverses number over modulo.
 * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
 */
function invert(number, modulo) {
    if (number === _0n$5)
        throw new Error('invert: expected non-zero number');
    if (modulo <= _0n$5)
        throw new Error('invert: expected positive modulus, got ' + modulo);
    // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
    let a = mod(number, modulo);
    let b = modulo;
    // prettier-ignore
    let x = _0n$5, u = _1n$6;
    while (a !== _0n$5) {
        // JIT applies optimization if those two lines follow each other
        const q = b / a;
        const r = b % a;
        const m = x - u * q;
        // prettier-ignore
        b = a, a = r, x = u, u = m;
    }
    const gcd = b;
    if (gcd !== _1n$6)
        throw new Error('invert: does not exist');
    return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
    if (!Fp.eql(Fp.sqr(root), n))
        throw new Error('Cannot find square root');
}
// Not all roots are possible! Example which will throw:
// const NUM =
// n = 72057594037927816n;
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
function sqrt3mod4(Fp, n) {
    const p1div4 = (Fp.ORDER + _1n$6) / _4n$1;
    const root = Fp.pow(n, p1div4);
    assertIsSquare(Fp, root, n);
    return root;
}
function sqrt5mod8(Fp, n) {
    const p5div8 = (Fp.ORDER - _5n) / _8n$1;
    const n2 = Fp.mul(n, _2n$6);
    const v = Fp.pow(n2, p5div8);
    const nv = Fp.mul(n, v);
    const i = Fp.mul(Fp.mul(nv, _2n$6), v);
    const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
    assertIsSquare(Fp, root, n);
    return root;
}
// Based on RFC9380, Kong algorithm
// prettier-ignore
function sqrt9mod16(P) {
    const Fp_ = Field(P);
    const tn = tonelliShanks(P);
    const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
    const c2 = tn(Fp_, c1); //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
    const c3 = tn(Fp_, Fp_.neg(c1)); //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
    const c4 = (P + _7n$1) / _16n; //  4. c4 = (q + 7) / 16        # Integer arithmetic
    return (Fp, n) => {
        let tv1 = Fp.pow(n, c4); //  1. tv1 = x^c4
        let tv2 = Fp.mul(tv1, c1); //  2. tv2 = c1 * tv1
        const tv3 = Fp.mul(tv1, c2); //  3. tv3 = c2 * tv1
        const tv4 = Fp.mul(tv1, c3); //  4. tv4 = c3 * tv1
        const e1 = Fp.eql(Fp.sqr(tv2), n); //  5.  e1 = (tv2^2) == x
        const e2 = Fp.eql(Fp.sqr(tv3), n); //  6.  e2 = (tv3^2) == x
        tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x
        tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x
        const e3 = Fp.eql(Fp.sqr(tv2), n); //  9.  e3 = (tv2^2) == x
        const root = Fp.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2
        assertIsSquare(Fp, root, n);
        return root;
    };
}
/**
 * Tonelli-Shanks square root search algorithm.
 * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
 * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
 * @param P field order
 * @returns function that takes field Fp (created from P) and number n
 */
function tonelliShanks(P) {
    // Initialization (precomputation).
    // Caching initialization could boost perf by 7%.
    if (P < _3n$2)
        throw new Error('sqrt is not defined for small field');
    // Factor P - 1 = Q * 2^S, where Q is odd
    let Q = P - _1n$6;
    let S = 0;
    while (Q % _2n$6 === _0n$5) {
        Q /= _2n$6;
        S++;
    }
    // Find the first quadratic non-residue Z >= 2
    let Z = _2n$6;
    const _Fp = Field(P);
    while (FpLegendre(_Fp, Z) === 1) {
        // Basic primality test for P. After x iterations, chance of
        // not finding quadratic non-residue is 2^x, so 2^1000.
        if (Z++ > 1000)
            throw new Error('Cannot find square root: probably non-prime P');
    }
    // Fast-path; usually done before Z, but we do "primality test".
    if (S === 1)
        return sqrt3mod4;
    // Slow-path
    // TODO: test on Fp2 and others
    let cc = _Fp.pow(Z, Q); // c = z^Q
    const Q1div2 = (Q + _1n$6) / _2n$6;
    return function tonelliSlow(Fp, n) {
        if (Fp.is0(n))
            return n;
        // Check if n is a quadratic residue using Legendre symbol
        if (FpLegendre(Fp, n) !== 1)
            throw new Error('Cannot find square root');
        // Initialize variables for the main loop
        let M = S;
        let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
        let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
        let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
        // Main loop
        // while t != 1
        while (!Fp.eql(t, Fp.ONE)) {
            if (Fp.is0(t))
                return Fp.ZERO; // if t=0 return R=0
            let i = 1;
            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
            let t_tmp = Fp.sqr(t); // t^(2^1)
            while (!Fp.eql(t_tmp, Fp.ONE)) {
                i++;
                t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
                if (i === M)
                    throw new Error('Cannot find square root');
            }
            // Calculate the exponent for b: 2^(M - i - 1)
            const exponent = _1n$6 << BigInt(M - i - 1); // bigint is important
            const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
            // Update variables
            M = i;
            c = Fp.sqr(b); // c = b^2
            t = Fp.mul(t, c); // t = (t * b^2)
            R = Fp.mul(R, b); // R = R*b
        }
        return R;
    };
}
/**
 * Square root for a finite field. Will try optimized versions first:
 *
 * 1. P ≡ 3 (mod 4)
 * 2. P ≡ 5 (mod 8)
 * 3. P ≡ 9 (mod 16)
 * 4. Tonelli-Shanks algorithm
 *
 * Different algorithms can give different roots, it is up to user to decide which one they want.
 * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
 */
function FpSqrt(P) {
    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)
    if (P % _4n$1 === _3n$2)
        return sqrt3mod4;
    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
    if (P % _8n$1 === _5n)
        return sqrt5mod8;
    // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
    if (P % _16n === _9n)
        return sqrt9mod16(P);
    // Tonelli-Shanks algorithm
    return tonelliShanks(P);
}
// prettier-ignore
const FIELD_FIELDS = [
    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
    'eql', 'add', 'sub', 'mul', 'pow', 'div',
    'addN', 'subN', 'mulN', 'sqrN'
];
function validateField(field) {
    const initial = {
        ORDER: 'bigint',
        MASK: 'bigint',
        BYTES: 'number',
        BITS: 'number',
    };
    const opts = FIELD_FIELDS.reduce((map, val) => {
        map[val] = 'function';
        return map;
    }, initial);
    _validateObject(field, opts);
    // const max = 16384;
    // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
    // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
    return field;
}
// Generic field functions
/**
 * Same as `pow` but for Fp: non-constant-time.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 */
function FpPow(Fp, num, power) {
    if (power < _0n$5)
        throw new Error('invalid exponent, negatives unsupported');
    if (power === _0n$5)
        return Fp.ONE;
    if (power === _1n$6)
        return num;
    let p = Fp.ONE;
    let d = num;
    while (power > _0n$5) {
        if (power & _1n$6)
            p = Fp.mul(p, d);
        d = Fp.sqr(d);
        power >>= _1n$6;
    }
    return p;
}
/**
 * Efficiently invert an array of Field elements.
 * Exception-free. Will return `undefined` for 0 elements.
 * @param passZero map 0 to 0 (instead of undefined)
 */
function FpInvertBatch(Fp, nums, passZero = false) {
    const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
    // Walk from first to last, multiply them by each other MOD p
    const multipliedAcc = nums.reduce((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = acc;
        return Fp.mul(acc, num);
    }, Fp.ONE);
    // Invert last element
    const invertedAcc = Fp.inv(multipliedAcc);
    // Walk from last to first, multiply them by inverted each other MOD p
    nums.reduceRight((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = Fp.mul(acc, inverted[i]);
        return Fp.mul(acc, num);
    }, invertedAcc);
    return inverted;
}
/**
 * Legendre symbol.
 * Legendre constant is used to calculate Legendre symbol (a | p)
 * which denotes the value of a^((p-1)/2) (mod p).
 *
 * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue
 * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue
 * * (a | p) ≡ 0    if a ≡ 0 (mod p)
 */
function FpLegendre(Fp, n) {
    // We can use 3rd argument as optional cache of this value
    // but seems unneeded for now. The operation is very fast.
    const p1mod2 = (Fp.ORDER - _1n$6) / _2n$6;
    const powered = Fp.pow(n, p1mod2);
    const yes = Fp.eql(powered, Fp.ONE);
    const zero = Fp.eql(powered, Fp.ZERO);
    const no = Fp.eql(powered, Fp.neg(Fp.ONE));
    if (!yes && !zero && !no)
        throw new Error('invalid Legendre symbol result');
    return yes ? 1 : zero ? 0 : -1;
}
// CURVE.n lengths
function nLength(n, nBitLength) {
    // Bit size, byte size of CURVE.n
    if (nBitLength !== undefined)
        anumber(nBitLength);
    const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
    const nByteLength = Math.ceil(_nBitLength / 8);
    return { nBitLength: _nBitLength, nByteLength };
}
/**
 * Creates a finite field. Major performance optimizations:
 * * 1. Denormalized operations like mulN instead of mul.
 * * 2. Identical object shape: never add or remove keys.
 * * 3. `Object.freeze`.
 * Fragile: always run a benchmark on a change.
 * Security note: operations don't check 'isValid' for all elements for performance reasons,
 * it is caller responsibility to check this.
 * This is low-level code, please make sure you know what you're doing.
 *
 * Note about field properties:
 * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
 * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
 *
 * @param ORDER field order, probably prime, or could be composite
 * @param bitLen how many bits the field consumes
 * @param isLE (default: false) if encoding / decoding should be in little-endian
 * @param redef optional faster redefinitions of sqrt and other methods
 */
function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
isLE = false, opts = {}) {
    if (ORDER <= _0n$5)
        throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
    let _nbitLength = undefined;
    let _sqrt = undefined;
    let modFromBytes = false;
    let allowedLengths = undefined;
    if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
        if (opts.sqrt || isLE)
            throw new Error('cannot specify opts in two arguments');
        const _opts = bitLenOrOpts;
        if (_opts.BITS)
            _nbitLength = _opts.BITS;
        if (_opts.sqrt)
            _sqrt = _opts.sqrt;
        if (typeof _opts.isLE === 'boolean')
            isLE = _opts.isLE;
        if (typeof _opts.modFromBytes === 'boolean')
            modFromBytes = _opts.modFromBytes;
        allowedLengths = _opts.allowedLengths;
    }
    else {
        if (typeof bitLenOrOpts === 'number')
            _nbitLength = bitLenOrOpts;
        if (opts.sqrt)
            _sqrt = opts.sqrt;
    }
    const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
    if (BYTES > 2048)
        throw new Error('invalid field: expected ORDER of <= 2048 bytes');
    let sqrtP; // cached sqrtP
    const f = Object.freeze({
        ORDER,
        isLE,
        BITS,
        BYTES,
        MASK: bitMask(BITS),
        ZERO: _0n$5,
        ONE: _1n$6,
        allowedLengths: allowedLengths,
        create: (num) => mod(num, ORDER),
        isValid: (num) => {
            if (typeof num !== 'bigint')
                throw new Error('invalid field element: expected bigint, got ' + typeof num);
            return _0n$5 <= num && num < ORDER; // 0 is valid element, but it's not invertible
        },
        is0: (num) => num === _0n$5,
        // is valid and invertible
        isValidNot0: (num) => !f.is0(num) && f.isValid(num),
        isOdd: (num) => (num & _1n$6) === _1n$6,
        neg: (num) => mod(-num, ORDER),
        eql: (lhs, rhs) => lhs === rhs,
        sqr: (num) => mod(num * num, ORDER),
        add: (lhs, rhs) => mod(lhs + rhs, ORDER),
        sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
        mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
        pow: (num, power) => FpPow(f, num, power),
        div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
        // Same as above, but doesn't normalize
        sqrN: (num) => num * num,
        addN: (lhs, rhs) => lhs + rhs,
        subN: (lhs, rhs) => lhs - rhs,
        mulN: (lhs, rhs) => lhs * rhs,
        inv: (num) => invert(num, ORDER),
        sqrt: _sqrt ||
            ((n) => {
                if (!sqrtP)
                    sqrtP = FpSqrt(ORDER);
                return sqrtP(f, n);
            }),
        toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
        fromBytes: (bytes, skipValidation = true) => {
            if (allowedLengths) {
                if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
                    throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
                }
                const padded = new Uint8Array(BYTES);
                // isLE add 0 to right, !isLE to the left.
                padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
                bytes = padded;
            }
            if (bytes.length !== BYTES)
                throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
            let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
            if (modFromBytes)
                scalar = mod(scalar, ORDER);
            if (!skipValidation)
                if (!f.isValid(scalar))
                    throw new Error('invalid field element: outside of range 0..ORDER');
            // NOTE: we don't validate scalar here, please use isValid. This done such way because some
            // protocol may allow non-reduced scalar that reduced later or changed some other way.
            return scalar;
        },
        // TODO: we don't need it here, move out to separate fn
        invertBatch: (lst) => FpInvertBatch(f, lst),
        // We can't move this out because Fp6, Fp12 implement it
        // and it's unclear what to return in there.
        cmov: (a, b, c) => (c ? b : a),
    });
    return Object.freeze(f);
}
/**
 * Returns total number of bytes consumed by the field element.
 * For example, 32 bytes for usual 256-bit weierstrass curve.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of field
 */
function getFieldBytesLength(fieldOrder) {
    if (typeof fieldOrder !== 'bigint')
        throw new Error('field order must be bigint');
    const bitLength = fieldOrder.toString(2).length;
    return Math.ceil(bitLength / 8);
}
/**
 * Returns minimal amount of bytes that can be safely reduced
 * by field order.
 * Should be 2^-128 for 128-bit curve such as P256.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of target hash
 */
function getMinHashLength(fieldOrder) {
    const length = getFieldBytesLength(fieldOrder);
    return length + Math.ceil(length / 2);
}
/**
 * "Constant-time" private key generation utility.
 * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
 * and convert them into private scalar, with the modulo bias being negligible.
 * Needs at least 48 bytes of input for 32-byte private key.
 * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
 * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
 * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
 * @param hash hash output from SHA3 or a similar function
 * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
 * @param isLE interpret hash bytes as LE num
 * @returns valid private scalar
 */
function mapHashToField(key, fieldOrder, isLE = false) {
    const len = key.length;
    const fieldLen = getFieldBytesLength(fieldOrder);
    const minLen = getMinHashLength(fieldOrder);
    // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
    if (len < 16 || len < minLen || len > 1024)
        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
    // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
    const reduced = mod(num, fieldOrder - _1n$6) + _1n$6;
    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}

/**
 * Internal Merkle-Damgard hash utils.
 * @module
 */
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
function setBigUint64(view, byteOffset, value, isLE) {
    if (typeof view.setBigUint64 === 'function')
        return view.setBigUint64(byteOffset, value, isLE);
    const _32n = BigInt(32);
    const _u32_max = BigInt(0xffffffff);
    const wh = Number((value >> _32n) & _u32_max);
    const wl = Number(value & _u32_max);
    const h = isLE ? 4 : 0;
    const l = isLE ? 0 : 4;
    view.setUint32(byteOffset + h, wh, isLE);
    view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
function Chi$1(a, b, c) {
    return (a & b) ^ (~a & c);
}
/** Majority function, true if any two inputs is true. */
function Maj(a, b, c) {
    return (a & b) ^ (a & c) ^ (b & c);
}
/**
 * Merkle-Damgard hash construction base class.
 * Could be used to create MD5, RIPEMD, SHA1, SHA2.
 */
class HashMD extends Hash {
    constructor(blockLen, outputLen, padOffset, isLE) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView(this.buffer);
    }
    update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { view, buffer, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len;) {
            const take = Math.min(blockLen - this.pos, len - pos);
            // Fast path: we have at least one block in input, cast it to view and process
            if (take === blockLen) {
                const dataView = createView(data);
                for (; blockLen <= len - pos; pos += blockLen)
                    this.process(dataView, pos);
                continue;
            }
            buffer.set(data.subarray(pos, pos + take), this.pos);
            this.pos += take;
            pos += take;
            if (this.pos === blockLen) {
                this.process(view, 0);
                this.pos = 0;
            }
        }
        this.length += data.length;
        this.roundClean();
        return this;
    }
    digestInto(out) {
        aexists(this);
        aoutput(out, this);
        this.finished = true;
        // Padding
        // We can avoid allocation of buffer for padding completely if it
        // was previously not allocated here. But it won't change performance.
        const { buffer, view, blockLen, isLE } = this;
        let { pos } = this;
        // append the bit '1' to the message
        buffer[pos++] = 0b10000000;
        clean(this.buffer.subarray(pos));
        // we have less than padOffset left in buffer, so we cannot put length in
        // current block, need process it and pad again
        if (this.padOffset > blockLen - pos) {
            this.process(view, 0);
            pos = 0;
        }
        // Pad until full block byte with zeros
        for (let i = pos; i < blockLen; i++)
            buffer[i] = 0;
        // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
        // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
        // So we just write lowest 64 bits of that value.
        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
        this.process(view, 0);
        const oview = createView(out);
        const len = this.outputLen;
        // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
        if (len % 4)
            throw new Error('_sha2: outputLen should be aligned to 32bit');
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
            throw new Error('_sha2: outputLen bigger than state');
        for (let i = 0; i < outLen; i++)
            oview.setUint32(4 * i, state[i], isLE);
    }
    digest() {
        const { buffer, outputLen } = this;
        this.digestInto(buffer);
        const res = buffer.slice(0, outputLen);
        this.destroy();
        return res;
    }
    _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer, length, finished, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
            to.buffer.set(buffer);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
}
/**
 * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
 * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
 */
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);

/**
 * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
 * @todo re-check https://issues.chromium.org/issues/42212588
 * @module
 */
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
    if (le)
        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
    const len = lst.length;
    let Ah = new Uint32Array(len);
    let Al = new Uint32Array(len);
    for (let i = 0; i < len; i++) {
        const { h, l } = fromBig(lst[i], le);
        [Ah[i], Al[i]] = [h, l];
    }
    return [Ah, Al];
}
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add$1(Ah, Al, Bh, Bl) {
    const l = (Al >>> 0) + (Bl >>> 0);
    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;

/**
 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
 * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
 * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
 * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
 * @module
 */
/**
 * Round constants:
 * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
 */
// prettier-ignore
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
/** Reusable temporary buffer. "W" comes straight from spec. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
class SHA256 extends HashMD {
    constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        this.A = SHA256_IV[0] | 0;
        this.B = SHA256_IV[1] | 0;
        this.C = SHA256_IV[2] | 0;
        this.D = SHA256_IV[3] | 0;
        this.E = SHA256_IV[4] | 0;
        this.F = SHA256_IV[5] | 0;
        this.G = SHA256_IV[6] | 0;
        this.H = SHA256_IV[7] | 0;
    }
    get() {
        const { A, B, C, D, E, F, G, H } = this;
        return [A, B, C, D, E, F, G, H];
    }
    // prettier-ignore
    set(A, B, C, D, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4)
            SHA256_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
            const W15 = SHA256_W[i - 15];
            const W2 = SHA256_W[i - 2];
            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
        }
        // Compression function main loop, 64 rounds
        let { A, B, C, D, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
            const T1 = (H + sigma1 + Chi$1(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
            const T2 = (sigma0 + Maj(A, B, C)) | 0;
            H = G;
            G = F;
            F = E;
            E = (D + T1) | 0;
            D = C;
            C = B;
            B = A;
            A = (T1 + T2) | 0;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        F = (F + this.F) | 0;
        G = (G + this.G) | 0;
        H = (H + this.H) | 0;
        this.set(A, B, C, D, E, F, G, H);
    }
    roundClean() {
        clean(SHA256_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
class SHA224 extends SHA256 {
    constructor() {
        super(28);
        this.A = SHA224_IV[0] | 0;
        this.B = SHA224_IV[1] | 0;
        this.C = SHA224_IV[2] | 0;
        this.D = SHA224_IV[3] | 0;
        this.E = SHA224_IV[4] | 0;
        this.F = SHA224_IV[5] | 0;
        this.G = SHA224_IV[6] | 0;
        this.H = SHA224_IV[7] | 0;
    }
}
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
// Round contants
// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
// prettier-ignore
const K512 = /* @__PURE__ */ (() => split([
    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
// Reusable temporary buffers
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
class SHA512 extends HashMD {
    constructor(outputLen = 64) {
        super(128, outputLen, 16, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        // h -- high 32 bits, l -- low 32 bits
        this.Ah = SHA512_IV[0] | 0;
        this.Al = SHA512_IV[1] | 0;
        this.Bh = SHA512_IV[2] | 0;
        this.Bl = SHA512_IV[3] | 0;
        this.Ch = SHA512_IV[4] | 0;
        this.Cl = SHA512_IV[5] | 0;
        this.Dh = SHA512_IV[6] | 0;
        this.Dl = SHA512_IV[7] | 0;
        this.Eh = SHA512_IV[8] | 0;
        this.El = SHA512_IV[9] | 0;
        this.Fh = SHA512_IV[10] | 0;
        this.Fl = SHA512_IV[11] | 0;
        this.Gh = SHA512_IV[12] | 0;
        this.Gl = SHA512_IV[13] | 0;
        this.Hh = SHA512_IV[14] | 0;
        this.Hl = SHA512_IV[15] | 0;
    }
    // prettier-ignore
    get() {
        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
    }
    // prettier-ignore
    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
        this.Ah = Ah | 0;
        this.Al = Al | 0;
        this.Bh = Bh | 0;
        this.Bl = Bl | 0;
        this.Ch = Ch | 0;
        this.Cl = Cl | 0;
        this.Dh = Dh | 0;
        this.Dl = Dl | 0;
        this.Eh = Eh | 0;
        this.El = El | 0;
        this.Fh = Fh | 0;
        this.Fl = Fl | 0;
        this.Gh = Gh | 0;
        this.Gl = Gl | 0;
        this.Hh = Hh | 0;
        this.Hl = Hl | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4) {
            SHA512_W_H[i] = view.getUint32(offset);
            SHA512_W_L[i] = view.getUint32((offset += 4));
        }
        for (let i = 16; i < 80; i++) {
            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
            const W15h = SHA512_W_H[i - 15] | 0;
            const W15l = SHA512_W_L[i - 15] | 0;
            const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
            const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
            const W2h = SHA512_W_H[i - 2] | 0;
            const W2l = SHA512_W_L[i - 2] | 0;
            const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
            const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
            // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
            const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
            const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
            SHA512_W_H[i] = SUMh | 0;
            SHA512_W_L[i] = SUMl | 0;
        }
        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        // Compression function main loop, 80 rounds
        for (let i = 0; i < 80; i++) {
            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
            const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
            const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const CHIh = (Eh & Fh) ^ (~Eh & Gh);
            const CHIl = (El & Fl) ^ (~El & Gl);
            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
            // prettier-ignore
            const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
            const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
            const T1l = T1ll | 0;
            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
            const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
            const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
            Hh = Gh | 0;
            Hl = Gl | 0;
            Gh = Fh | 0;
            Gl = Fl | 0;
            Fh = Eh | 0;
            Fl = El | 0;
            ({ h: Eh, l: El } = add$1(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
            Dh = Ch | 0;
            Dl = Cl | 0;
            Ch = Bh | 0;
            Cl = Bl | 0;
            Bh = Ah | 0;
            Bl = Al | 0;
            const All = add3L(T1l, sigma0l, MAJl);
            Ah = add3H(All, T1h, sigma0h, MAJh);
            Al = All | 0;
        }
        // Add the compressed chunk to the current hash value
        ({ h: Ah, l: Al } = add$1(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
        ({ h: Bh, l: Bl } = add$1(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
        ({ h: Ch, l: Cl } = add$1(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
        ({ h: Dh, l: Dl } = add$1(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
        ({ h: Eh, l: El } = add$1(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
        ({ h: Fh, l: Fl } = add$1(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
        ({ h: Gh, l: Gl } = add$1(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
        ({ h: Hh, l: Hl } = add$1(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
    }
    roundClean() {
        clean(SHA512_W_H, SHA512_W_L);
    }
    destroy() {
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    }
}
class SHA384 extends SHA512 {
    constructor() {
        super(48);
        this.Ah = SHA384_IV[0] | 0;
        this.Al = SHA384_IV[1] | 0;
        this.Bh = SHA384_IV[2] | 0;
        this.Bl = SHA384_IV[3] | 0;
        this.Ch = SHA384_IV[4] | 0;
        this.Cl = SHA384_IV[5] | 0;
        this.Dh = SHA384_IV[6] | 0;
        this.Dl = SHA384_IV[7] | 0;
        this.Eh = SHA384_IV[8] | 0;
        this.El = SHA384_IV[9] | 0;
        this.Fh = SHA384_IV[10] | 0;
        this.Fl = SHA384_IV[11] | 0;
        this.Gh = SHA384_IV[12] | 0;
        this.Gl = SHA384_IV[13] | 0;
        this.Hh = SHA384_IV[14] | 0;
        this.Hl = SHA384_IV[15] | 0;
    }
}
/**
 * SHA2-256 hash function from RFC 4634.
 *
 * It is the fastest JS hash, even faster than Blake3.
 * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
 * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
 */
const sha256$1 = /* @__PURE__ */ createHasher(() => new SHA256());
/** SHA2-224 hash function from RFC 4634 */
const sha224$1 = /* @__PURE__ */ createHasher(() => new SHA224());
/** SHA2-512 hash function from RFC 4634. */
const sha512$1 = /* @__PURE__ */ createHasher(() => new SHA512());
/** SHA2-384 hash function from RFC 4634. */
const sha384$1 = /* @__PURE__ */ createHasher(() => new SHA384());

/**
 * HMAC: RFC2104 message authentication code.
 * @module
 */
class HMAC extends Hash {
    constructor(hash, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash(hash);
        const key = toBytes(_key);
        this.iHash = hash.create();
        if (typeof this.iHash.update !== 'function')
            throw new Error('Expected instance of class which extends utils.Hash');
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad = new Uint8Array(blockLen);
        // blockLen can be bigger than outputLen
        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36;
        this.iHash.update(pad);
        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
        this.oHash = hash.create();
        // Undo internal XOR && apply outer XOR
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36 ^ 0x5c;
        this.oHash.update(pad);
        clean(pad);
    }
    update(buf) {
        aexists(this);
        this.iHash.update(buf);
        return this;
    }
    digestInto(out) {
        aexists(this);
        abytes(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
    }
    digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
    }
    _cloneInto(to) {
        // Create new instance without calling constructor since key already in state and we don't know it.
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
    destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
    }
}
/**
 * HMAC: RFC2104 message authentication code.
 * @param hash - function that would be used e.g. sha256
 * @param key - message key
 * @param message - message data
 * @example
 * import { hmac } from '@noble/hashes/hmac';
 * import { sha256 } from '@noble/hashes/sha2';
 * const mac1 = hmac(sha256, 'key', 'message');
 */
const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);

/**
 * Methods for elliptic curve multiplication by scalars.
 * Contains wNAF, pippenger.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n$4 = BigInt(0);
const _1n$5 = BigInt(1);
function negateCt(condition, item) {
    const neg = item.negate();
    return condition ? neg : item;
}
/**
 * Takes a bunch of Projective Points but executes only one
 * inversion on all of them. Inversion is very slow operation,
 * so this improves performance massively.
 * Optimization: converts a list of projective points to a list of identical points with Z=1.
 */
function normalizeZ(c, points) {
    const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
    return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
    if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
        throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
}
function calcWOpts(W, scalarBits) {
    validateW(W, scalarBits);
    const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
    const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
    const maxNumber = 2 ** W; // W=8 256
    const mask = bitMask(W); // W=8 255 == mask 0b11111111
    const shiftBy = BigInt(W); // W=8 8
    return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n, window, wOpts) {
    const { windowSize, mask, maxNumber, shiftBy } = wOpts;
    let wbits = Number(n & mask); // extract W bits.
    let nextN = n >> shiftBy; // shift number by W bits.
    // What actually happens here:
    // const highestBit = Number(mask ^ (mask >> 1n));
    // let wbits2 = wbits - 1; // skip zero
    // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
    // split if bits > max: +224 => 256-32
    if (wbits > windowSize) {
        // we skip zero, which means instead of `>= size-1`, we do `> size`
        wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
        nextN += _1n$5; // +256 (carry)
    }
    const offsetStart = window * windowSize;
    const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
    const isZero = wbits === 0; // is current window slice a 0?
    const isNeg = wbits < 0; // is current window slice negative?
    const isNegF = window % 2 !== 0; // fake random statement for noise
    const offsetF = offsetStart; // fake offset for noise
    return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints(points, c) {
    if (!Array.isArray(points))
        throw new Error('array expected');
    points.forEach((p, i) => {
        if (!(p instanceof c))
            throw new Error('invalid point at index ' + i);
    });
}
function validateMSMScalars(scalars, field) {
    if (!Array.isArray(scalars))
        throw new Error('array of scalars expected');
    scalars.forEach((s, i) => {
        if (!field.isValid(s))
            throw new Error('invalid scalar at index ' + i);
    });
}
// Since points in different groups cannot be equal (different object constructor),
// we can have single place to store precomputes.
// Allows to make points frozen / immutable.
const pointPrecomputes = new WeakMap();
const pointWindowSizes = new WeakMap();
function getW$1(P) {
    // To disable precomputes:
    // return 1;
    return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
    if (n !== _0n$4)
        throw new Error('invalid wNAF');
}
/**
 * Elliptic curve multiplication of Point by scalar. Fragile.
 * Table generation takes **30MB of ram and 10ms on high-end CPU**,
 * but may take much longer on slow devices. Actual generation will happen on
 * first call of `multiply()`. By default, `BASE` point is precomputed.
 *
 * Scalars should always be less than curve order: this should be checked inside of a curve itself.
 * Creates precomputation tables for fast multiplication:
 * - private scalar is split by fixed size windows of W bits
 * - every window point is collected from window's table & added to accumulator
 * - since windows are different, same point inside tables won't be accessed more than once per calc
 * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
 * - +1 window is neccessary for wNAF
 * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
 *
 * @todo Research returning 2d JS array of windows, instead of a single window.
 * This would allow windows to be in different memory locations
 */
class wNAF {
    // Parametrized with a given Point class (not individual point)
    constructor(Point, bits) {
        this.BASE = Point.BASE;
        this.ZERO = Point.ZERO;
        this.Fn = Point.Fn;
        this.bits = bits;
    }
    // non-const time multiplication ladder
    _unsafeLadder(elm, n, p = this.ZERO) {
        let d = elm;
        while (n > _0n$4) {
            if (n & _1n$5)
                p = p.add(d);
            d = d.double();
            n >>= _1n$5;
        }
        return p;
    }
    /**
     * Creates a wNAF precomputation window. Used for caching.
     * Default window size is set by `utils.precompute()` and is equal to 8.
     * Number of precomputed points depends on the curve size:
     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
     * - 𝑊 is the window size
     * - 𝑛 is the bitlength of the curve order.
     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
     * @param point Point instance
     * @param W window size
     * @returns precomputed point tables flattened to a single array
     */
    precomputeWindow(point, W) {
        const { windows, windowSize } = calcWOpts(W, this.bits);
        const points = [];
        let p = point;
        let base = p;
        for (let window = 0; window < windows; window++) {
            base = p;
            points.push(base);
            // i=1, bc we skip 0
            for (let i = 1; i < windowSize; i++) {
                base = base.add(p);
                points.push(base);
            }
            p = base.double();
        }
        return points;
    }
    /**
     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
     * More compact implementation:
     * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
     * @returns real and fake (for const-time) points
     */
    wNAF(W, precomputes, n) {
        // Scalar should be smaller than field order
        if (!this.Fn.isValid(n))
            throw new Error('invalid scalar');
        // Accumulators
        let p = this.ZERO;
        let f = this.BASE;
        // This code was first written with assumption that 'f' and 'p' will never be infinity point:
        // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
        // there is negate now: it is possible that negated element from low value
        // would be the same as high element, which will create carry into next window.
        // It's not obvious how this can fail, but still worth investigating later.
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
            const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // bits are 0: add garbage to fake point
                // Important part for const-time getPublicKey: add random "noise" point to f.
                f = f.add(negateCt(isNegF, precomputes[offsetF]));
            }
            else {
                // bits are 1: add to result point
                p = p.add(negateCt(isNeg, precomputes[offset]));
            }
        }
        assert0(n);
        // Return both real and fake points: JIT won't eliminate f.
        // At this point there is a way to F be infinity-point even if p is not,
        // which makes it less const-time: around 1 bigint multiply.
        return { p, f };
    }
    /**
     * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
     * @param acc accumulator point to add result of multiplication
     * @returns point
     */
    wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            if (n === _0n$4)
                break; // Early-exit, skip 0 value
            const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // Window bits are 0: skip processing.
                // Move to next window.
                continue;
            }
            else {
                const item = precomputes[offset];
                acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
            }
        }
        assert0(n);
        return acc;
    }
    getPrecomputes(W, point, transform) {
        // Calculate precomputes on a first run, reuse them after
        let comp = pointPrecomputes.get(point);
        if (!comp) {
            comp = this.precomputeWindow(point, W);
            if (W !== 1) {
                // Doing transform outside of if brings 15% perf hit
                if (typeof transform === 'function')
                    comp = transform(comp);
                pointPrecomputes.set(point, comp);
            }
        }
        return comp;
    }
    cached(point, scalar, transform) {
        const W = getW$1(point);
        return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
    }
    unsafe(point, scalar, transform, prev) {
        const W = getW$1(point);
        if (W === 1)
            return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
        return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
    }
    // We calculate precomputes for elliptic curve point multiplication
    // using windowed method. This specifies window size and
    // stores precomputed values. Usually only base point would be precomputed.
    createCache(P, W) {
        validateW(W, this.bits);
        pointWindowSizes.set(P, W);
        pointPrecomputes.delete(P);
    }
    hasCache(elm) {
        return getW$1(elm) !== 1;
    }
}
/**
 * Endomorphism-specific multiplication for Koblitz curves.
 * Cost: 128 dbl, 0-256 adds.
 */
function mulEndoUnsafe(Point, point, k1, k2) {
    let acc = point;
    let p1 = Point.ZERO;
    let p2 = Point.ZERO;
    while (k1 > _0n$4 || k2 > _0n$4) {
        if (k1 & _1n$5)
            p1 = p1.add(acc);
        if (k2 & _1n$5)
            p2 = p2.add(acc);
        acc = acc.double();
        k1 >>= _1n$5;
        k2 >>= _1n$5;
    }
    return { p1, p2 };
}
/**
 * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
 * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
 * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @param scalars array of L scalars (aka secret keys / bigints)
 */
function pippenger(c, fieldN, points, scalars) {
    // If we split scalars by some window (let's say 8 bits), every chunk will only
    // take 256 buckets even if there are 4096 scalars, also re-uses double.
    // TODO:
    // - https://eprint.iacr.org/2024/750.pdf
    // - https://tches.iacr.org/index.php/TCHES/article/view/10287
    // 0 is accepted in scalars
    validateMSMPoints(points, c);
    validateMSMScalars(scalars, fieldN);
    const plength = points.length;
    const slength = scalars.length;
    if (plength !== slength)
        throw new Error('arrays of points and scalars must have equal length');
    // if (plength === 0) throw new Error('array must be of length >= 2');
    const zero = c.ZERO;
    const wbits = bitLen(BigInt(plength));
    let windowSize = 1; // bits
    if (wbits > 12)
        windowSize = wbits - 3;
    else if (wbits > 4)
        windowSize = wbits - 2;
    else if (wbits > 0)
        windowSize = 2;
    const MASK = bitMask(windowSize);
    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
    let sum = zero;
    for (let i = lastBits; i >= 0; i -= windowSize) {
        buckets.fill(zero);
        for (let j = 0; j < slength; j++) {
            const scalar = scalars[j];
            const wbits = Number((scalar >> BigInt(i)) & MASK);
            buckets[wbits] = buckets[wbits].add(points[j]);
        }
        let resI = zero; // not using this will do small speed-up, but will lose ct
        // Skip first bucket, because it is zero
        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
            sumI = sumI.add(buckets[j]);
            resI = resI.add(sumI);
        }
        sum = sum.add(resI);
        if (i !== 0)
            for (let j = 0; j < windowSize; j++)
                sum = sum.double();
    }
    return sum;
}
function createField(order, field, isLE) {
    if (field) {
        if (field.ORDER !== order)
            throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
        validateField(field);
        return field;
    }
    else {
        return Field(order, { isLE });
    }
}
/** Validates CURVE opts and creates fields */
function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
    if (FpFnLE === undefined)
        FpFnLE = type === 'edwards';
    if (!CURVE || typeof CURVE !== 'object')
        throw new Error(`expected valid ${type} CURVE object`);
    for (const p of ['p', 'n', 'h']) {
        const val = CURVE[p];
        if (!(typeof val === 'bigint' && val > _0n$4))
            throw new Error(`CURVE.${p} must be positive bigint`);
    }
    const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
    const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
    const _b = type === 'weierstrass' ? 'b' : 'd';
    const params = ['Gx', 'Gy', 'a', _b];
    for (const p of params) {
        // @ts-ignore
        if (!Fp.isValid(CURVE[p]))
            throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
    }
    CURVE = Object.freeze(Object.assign({}, CURVE));
    return { CURVE, Fp, Fn };
}

/**
 * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
 *
 * ### Design rationale for types
 *
 * * Interaction between classes from different curves should fail:
 *   `k256.Point.BASE.add(p256.Point.BASE)`
 * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
 * * Different calls of `curve()` would return different classes -
 *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
 *   it won't affect others
 *
 * TypeScript can't infer types for classes created inside a function. Classes is one instance
 * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
 * unique type for every function call.
 *
 * We can use generic types via some param, like curve opts, but that would:
 *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
 *     which is hard to debug.
 *     2. Params can be generic and we can't enforce them to be constant value:
 *     if somebody creates curve from non-constant params,
 *     it would be allowed to interact with other curves with non-constant params
 *
 * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n$5) / den;
/**
 * Splits scalar for GLV endomorphism.
 */
function _splitEndoScalar(k, basis, n) {
    // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
    // Since part can be negative, we need to do this on point.
    // TODO: verifyScalar function which consumes lambda
    const [[a1, b1], [a2, b2]] = basis;
    const c1 = divNearest(b2 * k, n);
    const c2 = divNearest(-b1 * k, n);
    // |k1|/|k2| is < sqrt(N), but can be negative.
    // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
    let k1 = k - c1 * a1 - c2 * a2;
    let k2 = -c1 * b1 - c2 * b2;
    const k1neg = k1 < _0n$3;
    const k2neg = k2 < _0n$3;
    if (k1neg)
        k1 = -k1;
    if (k2neg)
        k2 = -k2;
    // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
    // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.
    const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n$4; // Half bits of N
    if (k1 < _0n$3 || k1 >= MAX_NUM || k2 < _0n$3 || k2 >= MAX_NUM) {
        throw new Error('splitScalar (endomorphism): failed, k=' + k);
    }
    return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
    if (!['compact', 'recovered', 'der'].includes(format))
        throw new Error('Signature format must be "compact", "recovered", or "der"');
    return format;
}
function validateSigOpts(opts, def) {
    const optsn = {};
    for (let optName of Object.keys(def)) {
        // @ts-ignore
        optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
    }
    _abool2(optsn.lowS, 'lowS');
    _abool2(optsn.prehash, 'prehash');
    if (optsn.format !== undefined)
        validateSigFormat(optsn.format);
    return optsn;
}
class DERErr extends Error {
    constructor(m = '') {
        super(m);
    }
}
/**
 * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
 *
 *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
 *
 * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
 */
const DER = {
    // asn.1 DER encoding utils
    Err: DERErr,
    // Basic building block is TLV (Tag-Length-Value)
    _tlv: {
        encode: (tag, data) => {
            const { Err: E } = DER;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length & 1)
                throw new E('tlv.encode: unpadded data');
            const dataLen = data.length / 2;
            const len = numberToHexUnpadded(dataLen);
            if ((len.length / 2) & 128)
                throw new E('tlv.encode: long form length too big');
            // length of length with long form flag
            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
            const t = numberToHexUnpadded(tag);
            return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
            const { Err: E } = DER;
            let pos = 0;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length < 2 || data[pos++] !== tag)
                throw new E('tlv.decode: wrong tlv');
            const first = data[pos++];
            const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
            let length = 0;
            if (!isLong)
                length = first;
            else {
                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
                const lenLen = first & 127;
                if (!lenLen)
                    throw new E('tlv.decode(long): indefinite length not supported');
                if (lenLen > 4)
                    throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
                const lengthBytes = data.subarray(pos, pos + lenLen);
                if (lengthBytes.length !== lenLen)
                    throw new E('tlv.decode: length bytes not complete');
                if (lengthBytes[0] === 0)
                    throw new E('tlv.decode(long): zero leftmost byte');
                for (const b of lengthBytes)
                    length = (length << 8) | b;
                pos += lenLen;
                if (length < 128)
                    throw new E('tlv.decode(long): not minimal encoding');
            }
            const v = data.subarray(pos, pos + length);
            if (v.length !== length)
                throw new E('tlv.decode: wrong value length');
            return { v, l: data.subarray(pos + length) };
        },
    },
    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
    // since we always use positive integers here. It must always be empty:
    // - add zero byte if exists
    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
    _int: {
        encode(num) {
            const { Err: E } = DER;
            if (num < _0n$3)
                throw new E('integer: negative integers are not allowed');
            let hex = numberToHexUnpadded(num);
            // Pad with zero byte if negative flag is present
            if (Number.parseInt(hex[0], 16) & 0b1000)
                hex = '00' + hex;
            if (hex.length & 1)
                throw new E('unexpected DER parsing assertion: unpadded hex');
            return hex;
        },
        decode(data) {
            const { Err: E } = DER;
            if (data[0] & 128)
                throw new E('invalid signature integer: negative');
            if (data[0] === 0x00 && !(data[1] & 128))
                throw new E('invalid signature integer: unnecessary leading zero');
            return bytesToNumberBE(data);
        },
    },
    toSig(hex) {
        // parse DER signature
        const { Err: E, _int: int, _tlv: tlv } = DER;
        const data = ensureBytes('signature', hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
        if (seqLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
        if (sLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
    },
    hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER;
        const rs = tlv.encode(0x02, int.encode(sig.r));
        const ss = tlv.encode(0x02, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(0x30, seq);
    },
};
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n$3 = BigInt(0), _1n$4 = BigInt(1), _2n$5 = BigInt(2), _3n$1 = BigInt(3), _4n = BigInt(4);
function _normFnElement(Fn, key) {
    const { BYTES: expected } = Fn;
    let num;
    if (typeof key === 'bigint') {
        num = key;
    }
    else {
        let bytes = ensureBytes('private key', key);
        try {
            num = Fn.fromBytes(bytes);
        }
        catch (error) {
            throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
        }
    }
    if (!Fn.isValidNot0(num))
        throw new Error('invalid private key: out of range [1..N-1]');
    return num;
}
/**
 * Creates weierstrass Point constructor, based on specified curve options.
 *
 * @example
```js
const opts = {
  p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
  n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
  h: BigInt(1),
  a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
  b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
  Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
  Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
 */
function weierstrassN(params, extraOpts = {}) {
    const validated = _createCurveFields('weierstrass', params, extraOpts);
    const { Fp, Fn } = validated;
    let CURVE = validated.CURVE;
    const { h: cofactor, n: CURVE_ORDER } = CURVE;
    _validateObject(extraOpts, {}, {
        allowInfinityPoint: 'boolean',
        clearCofactor: 'function',
        isTorsionFree: 'function',
        fromBytes: 'function',
        toBytes: 'function',
        endo: 'object',
        wrapPrivateKey: 'boolean',
    });
    const { endo } = extraOpts;
    if (endo) {
        // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
        if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
            throw new Error('invalid endo: expected "beta": bigint and "basises": array');
        }
    }
    const lengths = getWLengths(Fp, Fn);
    function assertCompressionIsSupported() {
        if (!Fp.isOdd)
            throw new Error('compression is not supported: Field does not have .isOdd()');
    }
    // Implements IEEE P1363 point encoding
    function pointToBytes(_c, point, isCompressed) {
        const { x, y } = point.toAffine();
        const bx = Fp.toBytes(x);
        _abool2(isCompressed, 'isCompressed');
        if (isCompressed) {
            assertCompressionIsSupported();
            const hasEvenY = !Fp.isOdd(y);
            return concatBytes(pprefix(hasEvenY), bx);
        }
        else {
            return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
        }
    }
    function pointFromBytes(bytes) {
        _abytes2(bytes, undefined, 'Point');
        const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
        const length = bytes.length;
        const head = bytes[0];
        const tail = bytes.subarray(1);
        // No actual validation is done here: use .assertValidity()
        if (length === comp && (head === 0x02 || head === 0x03)) {
            const x = Fp.fromBytes(tail);
            if (!Fp.isValid(x))
                throw new Error('bad point: is not on curve, wrong x');
            const y2 = weierstrassEquation(x); // y² = x³ + ax + b
            let y;
            try {
                y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
            }
            catch (sqrtError) {
                const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
                throw new Error('bad point: is not on curve, sqrt error' + err);
            }
            assertCompressionIsSupported();
            const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
            const isHeadOdd = (head & 1) === 1; // ECDSA-specific
            if (isHeadOdd !== isYOdd)
                y = Fp.neg(y);
            return { x, y };
        }
        else if (length === uncomp && head === 0x04) {
            // TODO: more checks
            const L = Fp.BYTES;
            const x = Fp.fromBytes(tail.subarray(0, L));
            const y = Fp.fromBytes(tail.subarray(L, L * 2));
            if (!isValidXY(x, y))
                throw new Error('bad point: is not on curve');
            return { x, y };
        }
        else {
            throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
        }
    }
    const encodePoint = extraOpts.toBytes || pointToBytes;
    const decodePoint = extraOpts.fromBytes || pointFromBytes;
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
    }
    // TODO: move top-level
    /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
    function isValidXY(x, y) {
        const left = Fp.sqr(y); // y²
        const right = weierstrassEquation(x); // x³ + ax + b
        return Fp.eql(left, right);
    }
    // Validate whether the passed curve params are valid.
    // Test 1: equation y² = x³ + ax + b should work for generator point.
    if (!isValidXY(CURVE.Gx, CURVE.Gy))
        throw new Error('bad curve params: generator point');
    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
    // Guarantees curve is genus-1, smooth (non-singular).
    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n$1), _4n);
    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
    if (Fp.is0(Fp.add(_4a3, _27b2)))
        throw new Error('bad curve params: a or b');
    /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
    function acoord(title, n, banZero = false) {
        if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
            throw new Error(`bad point coordinate ${title}`);
        return n;
    }
    function aprjpoint(other) {
        if (!(other instanceof Point))
            throw new Error('ProjectivePoint expected');
    }
    function splitEndoScalarN(k) {
        if (!endo || !endo.basises)
            throw new Error('no endo');
        return _splitEndoScalar(k, endo.basises, Fn.ORDER);
    }
    // Memoized toAffine / validity check. They are heavy. Points are immutable.
    // Converts Projective point to affine (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
    const toAffineMemo = memoized((p, iz) => {
        const { X, Y, Z } = p;
        // Fast-path for normalized points
        if (Fp.eql(Z, Fp.ONE))
            return { x: X, y: Y };
        const is0 = p.is0();
        // If invZ was 0, we return zero point. However we still want to execute
        // all operations, so we replace invZ with a random number, 1.
        if (iz == null)
            iz = is0 ? Fp.ONE : Fp.inv(Z);
        const x = Fp.mul(X, iz);
        const y = Fp.mul(Y, iz);
        const zz = Fp.mul(Z, iz);
        if (is0)
            return { x: Fp.ZERO, y: Fp.ZERO };
        if (!Fp.eql(zz, Fp.ONE))
            throw new Error('invZ was invalid');
        return { x, y };
    });
    // NOTE: on exception this will crash 'cached' and no value will be set.
    // Otherwise true will be return
    const assertValidMemo = memoized((p) => {
        if (p.is0()) {
            // (0, 1, 0) aka ZERO is invalid in most contexts.
            // In BLS, ZERO can be serialized, so we allow it.
            // (0, 0, 0) is invalid representation of ZERO.
            if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
                return;
            throw new Error('bad point: ZERO');
        }
        // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
        const { x, y } = p.toAffine();
        if (!Fp.isValid(x) || !Fp.isValid(y))
            throw new Error('bad point: x or y not field elements');
        if (!isValidXY(x, y))
            throw new Error('bad point: equation left != right');
        if (!p.isTorsionFree())
            throw new Error('bad point: not in prime-order subgroup');
        return true;
    });
    function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
        k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
        k1p = negateCt(k1neg, k1p);
        k2p = negateCt(k2neg, k2p);
        return k1p.add(k2p);
    }
    /**
     * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
     * Default Point works in 2d / affine coordinates: (x, y).
     * We're doing calculations in projective, because its operations don't require costly inversion.
     */
    class Point {
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        constructor(X, Y, Z) {
            this.X = acoord('x', X);
            this.Y = acoord('y', Y, true);
            this.Z = acoord('z', Z);
            Object.freeze(this);
        }
        static CURVE() {
            return CURVE;
        }
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        static fromAffine(p) {
            const { x, y } = p || {};
            if (!p || !Fp.isValid(x) || !Fp.isValid(y))
                throw new Error('invalid affine point');
            if (p instanceof Point)
                throw new Error('projective point not allowed');
            // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
            if (Fp.is0(x) && Fp.is0(y))
                return Point.ZERO;
            return new Point(x, y, Fp.ONE);
        }
        static fromBytes(bytes) {
            const P = Point.fromAffine(decodePoint(_abytes2(bytes, undefined, 'point')));
            P.assertValidity();
            return P;
        }
        static fromHex(hex) {
            return Point.fromBytes(ensureBytes('pointHex', hex));
        }
        get x() {
            return this.toAffine().x;
        }
        get y() {
            return this.toAffine().y;
        }
        /**
         *
         * @param windowSize
         * @param isLazy true will defer table computation until the first multiplication
         * @returns
         */
        precompute(windowSize = 8, isLazy = true) {
            wnaf.createCache(this, windowSize);
            if (!isLazy)
                this.multiply(_3n$1); // random number
            return this;
        }
        // TODO: return `this`
        /** A point on curve is valid if it conforms to equation. */
        assertValidity() {
            assertValidMemo(this);
        }
        hasEvenY() {
            const { y } = this.toAffine();
            if (!Fp.isOdd)
                throw new Error("Field doesn't support isOdd");
            return !Fp.isOdd(y);
        }
        /** Compare one point to another. */
        equals(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
            return U1 && U2;
        }
        /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
        negate() {
            return new Point(this.X, Fp.neg(this.Y), this.Z);
        }
        // Renes-Costello-Batina exception-free doubling formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 3
        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
        double() {
            const { a, b } = CURVE;
            const b3 = Fp.mul(b, _3n$1);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            let t0 = Fp.mul(X1, X1); // step 1
            let t1 = Fp.mul(Y1, Y1);
            let t2 = Fp.mul(Z1, Z1);
            let t3 = Fp.mul(X1, Y1);
            t3 = Fp.add(t3, t3); // step 5
            Z3 = Fp.mul(X1, Z1);
            Z3 = Fp.add(Z3, Z3);
            X3 = Fp.mul(a, Z3);
            Y3 = Fp.mul(b3, t2);
            Y3 = Fp.add(X3, Y3); // step 10
            X3 = Fp.sub(t1, Y3);
            Y3 = Fp.add(t1, Y3);
            Y3 = Fp.mul(X3, Y3);
            X3 = Fp.mul(t3, X3);
            Z3 = Fp.mul(b3, Z3); // step 15
            t2 = Fp.mul(a, t2);
            t3 = Fp.sub(t0, t2);
            t3 = Fp.mul(a, t3);
            t3 = Fp.add(t3, Z3);
            Z3 = Fp.add(t0, t0); // step 20
            t0 = Fp.add(Z3, t0);
            t0 = Fp.add(t0, t2);
            t0 = Fp.mul(t0, t3);
            Y3 = Fp.add(Y3, t0);
            t2 = Fp.mul(Y1, Z1); // step 25
            t2 = Fp.add(t2, t2);
            t0 = Fp.mul(t2, t3);
            X3 = Fp.sub(X3, t0);
            Z3 = Fp.mul(t2, t1);
            Z3 = Fp.add(Z3, Z3); // step 30
            Z3 = Fp.add(Z3, Z3);
            return new Point(X3, Y3, Z3);
        }
        // Renes-Costello-Batina exception-free addition formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 1
        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
        add(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            const a = CURVE.a;
            const b3 = Fp.mul(CURVE.b, _3n$1);
            let t0 = Fp.mul(X1, X2); // step 1
            let t1 = Fp.mul(Y1, Y2);
            let t2 = Fp.mul(Z1, Z2);
            let t3 = Fp.add(X1, Y1);
            let t4 = Fp.add(X2, Y2); // step 5
            t3 = Fp.mul(t3, t4);
            t4 = Fp.add(t0, t1);
            t3 = Fp.sub(t3, t4);
            t4 = Fp.add(X1, Z1);
            let t5 = Fp.add(X2, Z2); // step 10
            t4 = Fp.mul(t4, t5);
            t5 = Fp.add(t0, t2);
            t4 = Fp.sub(t4, t5);
            t5 = Fp.add(Y1, Z1);
            X3 = Fp.add(Y2, Z2); // step 15
            t5 = Fp.mul(t5, X3);
            X3 = Fp.add(t1, t2);
            t5 = Fp.sub(t5, X3);
            Z3 = Fp.mul(a, t4);
            X3 = Fp.mul(b3, t2); // step 20
            Z3 = Fp.add(X3, Z3);
            X3 = Fp.sub(t1, Z3);
            Z3 = Fp.add(t1, Z3);
            Y3 = Fp.mul(X3, Z3);
            t1 = Fp.add(t0, t0); // step 25
            t1 = Fp.add(t1, t0);
            t2 = Fp.mul(a, t2);
            t4 = Fp.mul(b3, t4);
            t1 = Fp.add(t1, t2);
            t2 = Fp.sub(t0, t2); // step 30
            t2 = Fp.mul(a, t2);
            t4 = Fp.add(t4, t2);
            t0 = Fp.mul(t1, t4);
            Y3 = Fp.add(Y3, t0);
            t0 = Fp.mul(t5, t4); // step 35
            X3 = Fp.mul(t3, X3);
            X3 = Fp.sub(X3, t0);
            t0 = Fp.mul(t3, t1);
            Z3 = Fp.mul(t5, Z3);
            Z3 = Fp.add(Z3, t0); // step 40
            return new Point(X3, Y3, Z3);
        }
        subtract(other) {
            return this.add(other.negate());
        }
        is0() {
            return this.equals(Point.ZERO);
        }
        /**
         * Constant time multiplication.
         * Uses wNAF method. Windowed method may be 10% faster,
         * but takes 2x longer to generate and consumes 2x memory.
         * Uses precomputes when available.
         * Uses endomorphism for Koblitz curves.
         * @param scalar by which the point would be multiplied
         * @returns New point
         */
        multiply(scalar) {
            const { endo } = extraOpts;
            if (!Fn.isValidNot0(scalar))
                throw new Error('invalid scalar: out of range'); // 0 is invalid
            let point, fake; // Fake point is used to const-time mult
            const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
            /** See docs for {@link EndomorphismOpts} */
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
                const { p: k1p, f: k1f } = mul(k1);
                const { p: k2p, f: k2f } = mul(k2);
                fake = k1f.add(k2f);
                point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
            }
            else {
                const { p, f } = mul(scalar);
                point = p;
                fake = f;
            }
            // Normalize `z` for both points, but return only real one
            return normalizeZ(Point, [point, fake])[0];
        }
        /**
         * Non-constant-time multiplication. Uses double-and-add algorithm.
         * It's faster, but should only be used when you don't care about
         * an exposed secret key e.g. sig verification, which works over *public* keys.
         */
        multiplyUnsafe(sc) {
            const { endo } = extraOpts;
            const p = this;
            if (!Fn.isValid(sc))
                throw new Error('invalid scalar: out of range'); // 0 is valid
            if (sc === _0n$3 || p.is0())
                return Point.ZERO;
            if (sc === _1n$4)
                return p; // fast-path
            if (wnaf.hasCache(this))
                return this.multiply(sc);
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
                const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
                return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
            }
            else {
                return wnaf.unsafe(p, sc);
            }
        }
        multiplyAndAddUnsafe(Q, a, b) {
            const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
            return sum.is0() ? undefined : sum;
        }
        /**
         * Converts Projective point to affine (x, y) coordinates.
         * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
         */
        toAffine(invertedZ) {
            return toAffineMemo(this, invertedZ);
        }
        /**
         * Checks whether Point is free of torsion elements (is in prime subgroup).
         * Always torsion-free for cofactor=1 curves.
         */
        isTorsionFree() {
            const { isTorsionFree } = extraOpts;
            if (cofactor === _1n$4)
                return true;
            if (isTorsionFree)
                return isTorsionFree(Point, this);
            return wnaf.unsafe(this, CURVE_ORDER).is0();
        }
        clearCofactor() {
            const { clearCofactor } = extraOpts;
            if (cofactor === _1n$4)
                return this; // Fast-path
            if (clearCofactor)
                return clearCofactor(Point, this);
            return this.multiplyUnsafe(cofactor);
        }
        isSmallOrder() {
            // can we use this.clearCofactor()?
            return this.multiplyUnsafe(cofactor).is0();
        }
        toBytes(isCompressed = true) {
            _abool2(isCompressed, 'isCompressed');
            this.assertValidity();
            return encodePoint(Point, this, isCompressed);
        }
        toHex(isCompressed = true) {
            return bytesToHex(this.toBytes(isCompressed));
        }
        toString() {
            return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
        }
        // TODO: remove
        get px() {
            return this.X;
        }
        get py() {
            return this.X;
        }
        get pz() {
            return this.Z;
        }
        toRawBytes(isCompressed = true) {
            return this.toBytes(isCompressed);
        }
        _setWindowSize(windowSize) {
            this.precompute(windowSize);
        }
        static normalizeZ(points) {
            return normalizeZ(Point, points);
        }
        static msm(points, scalars) {
            return pippenger(Point, Fn, points, scalars);
        }
        static fromPrivateKey(privateKey) {
            return Point.BASE.multiply(_normFnElement(Fn, privateKey));
        }
    }
    // base / generator point
    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
    // zero / infinity / identity point
    Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
    // math field
    Point.Fp = Fp;
    // scalar field
    Point.Fn = Fn;
    const bits = Fn.BITS;
    const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
    Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
    return Point;
}
// Points start with byte 0x02 when y is even; otherwise 0x03
function pprefix(hasEvenY) {
    return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
}
function getWLengths(Fp, Fn) {
    return {
        secretKey: Fn.BYTES,
        publicKey: 1 + Fp.BYTES,
        publicKeyUncompressed: 1 + 2 * Fp.BYTES,
        publicKeyHasPrefix: true,
        signature: 2 * Fn.BYTES,
    };
}
/**
 * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
 * This helper ensures no signature functionality is present. Less code, smaller bundle size.
 */
function ecdh(Point, ecdhOpts = {}) {
    const { Fn } = Point;
    const randomBytes_ = ecdhOpts.randomBytes || randomBytes;
    const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
    function isValidSecretKey(secretKey) {
        try {
            return !!_normFnElement(Fn, secretKey);
        }
        catch (error) {
            return false;
        }
    }
    function isValidPublicKey(publicKey, isCompressed) {
        const { publicKey: comp, publicKeyUncompressed } = lengths;
        try {
            const l = publicKey.length;
            if (isCompressed === true && l !== comp)
                return false;
            if (isCompressed === false && l !== publicKeyUncompressed)
                return false;
            return !!Point.fromBytes(publicKey);
        }
        catch (error) {
            return false;
        }
    }
    /**
     * Produces cryptographically secure secret key from random of size
     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
     */
    function randomSecretKey(seed = randomBytes_(lengths.seed)) {
        return mapHashToField(_abytes2(seed, lengths.seed, 'seed'), Fn.ORDER);
    }
    /**
     * Computes public key for a secret key. Checks for validity of the secret key.
     * @param isCompressed whether to return compact (default), or full key
     * @returns Public key, full when isCompressed=false; short when isCompressed=true
     */
    function getPublicKey(secretKey, isCompressed = true) {
        return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
    }
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: getPublicKey(secretKey) };
    }
    /**
     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
     */
    function isProbPub(item) {
        if (typeof item === 'bigint')
            return false;
        if (item instanceof Point)
            return true;
        const { secretKey, publicKey, publicKeyUncompressed } = lengths;
        if (Fn.allowedLengths || secretKey === publicKey)
            return undefined;
        const l = ensureBytes('key', item).length;
        return l === publicKey || l === publicKeyUncompressed;
    }
    /**
     * ECDH (Elliptic Curve Diffie Hellman).
     * Computes shared public key from secret key A and public key B.
     * Checks: 1) secret key validity 2) shared key is on-curve.
     * Does NOT hash the result.
     * @param isCompressed whether to return compact (default), or full key
     * @returns shared public key
     */
    function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
        if (isProbPub(secretKeyA) === true)
            throw new Error('first arg must be private key');
        if (isProbPub(publicKeyB) === false)
            throw new Error('second arg must be public key');
        const s = _normFnElement(Fn, secretKeyA);
        const b = Point.fromHex(publicKeyB); // checks for being on-curve
        return b.multiply(s).toBytes(isCompressed);
    }
    const utils = {
        isValidSecretKey,
        isValidPublicKey,
        randomSecretKey,
        // TODO: remove
        isValidPrivateKey: isValidSecretKey,
        randomPrivateKey: randomSecretKey,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        precompute(windowSize = 8, point = Point.BASE) {
            return point.precompute(windowSize, false);
        },
    };
    return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
}
/**
 * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
 * We need `hash` for 2 features:
 * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
 * 2. k generation in `sign`, using HMAC-drbg(hash)
 *
 * ECDSAOpts are only rarely needed.
 *
 * @example
 * ```js
 * const p256_Point = weierstrass(...);
 * const p256_sha256 = ecdsa(p256_Point, sha256);
 * const p256_sha224 = ecdsa(p256_Point, sha224);
 * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
 * ```
 */
function ecdsa(Point, hash, ecdsaOpts = {}) {
    ahash(hash);
    _validateObject(ecdsaOpts, {}, {
        hmac: 'function',
        lowS: 'boolean',
        randomBytes: 'function',
        bits2int: 'function',
        bits2int_modN: 'function',
    });
    const randomBytes$1 = ecdsaOpts.randomBytes || randomBytes;
    const hmac$1 = ecdsaOpts.hmac ||
        ((key, ...msgs) => hmac(hash, key, concatBytes(...msgs)));
    const { Fp, Fn } = Point;
    const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
    const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
    const defaultSigOpts = {
        prehash: false,
        lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
        format: undefined, //'compact' as ECDSASigFormat,
        extraEntropy: false,
    };
    const defaultSigOpts_format = 'compact';
    function isBiggerThanHalfOrder(number) {
        const HALF = CURVE_ORDER >> _1n$4;
        return number > HALF;
    }
    function validateRS(title, num) {
        if (!Fn.isValidNot0(num))
            throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
        return num;
    }
    function validateSigLength(bytes, format) {
        validateSigFormat(format);
        const size = lengths.signature;
        const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
        return _abytes2(bytes, sizer, `${format} signature`);
    }
    /**
     * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
     */
    class Signature {
        constructor(r, s, recovery) {
            this.r = validateRS('r', r); // r in [1..N-1];
            this.s = validateRS('s', s); // s in [1..N-1];
            if (recovery != null)
                this.recovery = recovery;
            Object.freeze(this);
        }
        static fromBytes(bytes, format = defaultSigOpts_format) {
            validateSigLength(bytes, format);
            let recid;
            if (format === 'der') {
                const { r, s } = DER.toSig(_abytes2(bytes));
                return new Signature(r, s);
            }
            if (format === 'recovered') {
                recid = bytes[0];
                format = 'compact';
                bytes = bytes.subarray(1);
            }
            const L = Fn.BYTES;
            const r = bytes.subarray(0, L);
            const s = bytes.subarray(L, L * 2);
            return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
        }
        static fromHex(hex, format) {
            return this.fromBytes(hexToBytes(hex), format);
        }
        addRecoveryBit(recovery) {
            return new Signature(this.r, this.s, recovery);
        }
        recoverPublicKey(messageHash) {
            const FIELD_ORDER = Fp.ORDER;
            const { r, s, recovery: rec } = this;
            if (rec == null || ![0, 1, 2, 3].includes(rec))
                throw new Error('recovery id invalid');
            // ECDSA recovery is hard for cofactor > 1 curves.
            // In sign, `r = q.x mod n`, and here we recover q.x from r.
            // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
            // However, for cofactor>1, r+n may not get q.x:
            // r+n*i would need to be done instead where i is unknown.
            // To easily get i, we either need to:
            // a. increase amount of valid recid values (4, 5...); OR
            // b. prohibit non-prime-order signatures (recid > 1).
            const hasCofactor = CURVE_ORDER * _2n$5 < FIELD_ORDER;
            if (hasCofactor && rec > 1)
                throw new Error('recovery id is ambiguous for h>1 curve');
            const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
            if (!Fp.isValid(radj))
                throw new Error('recovery id 2 or 3 invalid');
            const x = Fp.toBytes(radj);
            const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
            const ir = Fn.inv(radj); // r^-1
            const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash
            const u1 = Fn.create(-h * ir); // -hr^-1
            const u2 = Fn.create(s * ir); // sr^-1
            // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
            const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
            if (Q.is0())
                throw new Error('point at infinify');
            Q.assertValidity();
            return Q;
        }
        // Signatures should be low-s, to prevent malleability.
        hasHighS() {
            return isBiggerThanHalfOrder(this.s);
        }
        toBytes(format = defaultSigOpts_format) {
            validateSigFormat(format);
            if (format === 'der')
                return hexToBytes(DER.hexFromSig(this));
            const r = Fn.toBytes(this.r);
            const s = Fn.toBytes(this.s);
            if (format === 'recovered') {
                if (this.recovery == null)
                    throw new Error('recovery bit must be present');
                return concatBytes(Uint8Array.of(this.recovery), r, s);
            }
            return concatBytes(r, s);
        }
        toHex(format) {
            return bytesToHex(this.toBytes(format));
        }
        // TODO: remove
        assertValidity() { }
        static fromCompact(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'compact');
        }
        static fromDER(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'der');
        }
        normalizeS() {
            return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
        }
        toDERRawBytes() {
            return this.toBytes('der');
        }
        toDERHex() {
            return bytesToHex(this.toBytes('der'));
        }
        toCompactRawBytes() {
            return this.toBytes('compact');
        }
        toCompactHex() {
            return bytesToHex(this.toBytes('compact'));
        }
    }
    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
    const bits2int = ecdsaOpts.bits2int ||
        function bits2int_def(bytes) {
            // Our custom check "just in case", for protection against DoS
            if (bytes.length > 8192)
                throw new Error('input is too large');
            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
            // for some cases, since bytes.length * 8 is not actual bitLength.
            const num = bytesToNumberBE(bytes); // check for == u8 done here
            const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
            return delta > 0 ? num >> BigInt(delta) : num;
        };
    const bits2int_modN = ecdsaOpts.bits2int_modN ||
        function bits2int_modN_def(bytes) {
            return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
        };
    // Pads output with zero as per spec
    const ORDER_MASK = bitMask(fnBits);
    /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
    function int2octets(num) {
        // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
        aInRange('num < 2^' + fnBits, num, _0n$3, ORDER_MASK);
        return Fn.toBytes(num);
    }
    function validateMsgAndHash(message, prehash) {
        _abytes2(message, undefined, 'message');
        return prehash ? _abytes2(hash(message), undefined, 'prehashed message') : message;
    }
    /**
     * Steps A, D of RFC6979 3.2.
     * Creates RFC6979 seed; converts msg/privKey to numbers.
     * Used only in sign, not in verify.
     *
     * Warning: we cannot assume here that message has same amount of bytes as curve order,
     * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
     */
    function prepSig(message, privateKey, opts) {
        if (['recovered', 'canonical'].some((k) => k in opts))
            throw new Error('sign() legacy options not supported');
        const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
        // We can't later call bits2octets, since nested bits2int is broken for curves
        // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
        const h1int = bits2int_modN(message);
        const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint
        const seedArgs = [int2octets(d), int2octets(h1int)];
        // extraEntropy. RFC6979 3.6: additional k' (optional).
        if (extraEntropy != null && extraEntropy !== false) {
            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
            // gen random bytes OR pass as-is
            const e = extraEntropy === true ? randomBytes$1(lengths.secretKey) : extraEntropy;
            seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
        }
        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
        const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
        // Converts signature params into point w r/s, checks result for validity.
        // To transform k => Signature:
        // q = k⋅G
        // r = q.x mod n
        // s = k^-1(m + rd) mod n
        // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
        // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
        // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
        function k2sig(kBytes) {
            // RFC 6979 Section 3.2, step 3: k = bits2int(T)
            // Important: all mod() calls here must be done over N
            const k = bits2int(kBytes); // mod n, not mod p
            if (!Fn.isValidNot0(k))
                return; // Valid scalars (including k) must be in 1..N-1
            const ik = Fn.inv(k); // k^-1 mod n
            const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
            const r = Fn.create(q.x); // r = q.x mod n
            if (r === _0n$3)
                return;
            const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
            if (s === _0n$3)
                return;
            let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$4); // recovery bit (2 or 3, when q.x > n)
            let normS = s;
            if (lowS && isBiggerThanHalfOrder(s)) {
                normS = Fn.neg(s); // if lowS was passed, ensure s is always
                recovery ^= 1; // // in the bottom half of N
            }
            return new Signature(r, normS, recovery); // use normS, not s
        }
        return { seed, k2sig };
    }
    /**
     * Signs message hash with a secret key.
     *
     * ```
     * sign(m, d) where
     *   k = rfc6979_hmac_drbg(m, d)
     *   (x, y) = G × k
     *   r = x mod n
     *   s = (m + dr) / k mod n
     * ```
     */
    function sign(message, secretKey, opts = {}) {
        message = ensureBytes('message', message);
        const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
        const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac$1);
        const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
        return sig;
    }
    function tryParsingSig(sg) {
        // Try to deduce format
        let sig = undefined;
        const isHex = typeof sg === 'string' || isBytes(sg);
        const isObj = !isHex &&
            sg !== null &&
            typeof sg === 'object' &&
            typeof sg.r === 'bigint' &&
            typeof sg.s === 'bigint';
        if (!isHex && !isObj)
            throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
        if (isObj) {
            sig = new Signature(sg.r, sg.s);
        }
        else if (isHex) {
            try {
                sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');
            }
            catch (derError) {
                if (!(derError instanceof DER.Err))
                    throw derError;
            }
            if (!sig) {
                try {
                    sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');
                }
                catch (error) {
                    return false;
                }
            }
        }
        if (!sig)
            return false;
        return sig;
    }
    /**
     * Verifies a signature against message and public key.
     * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
     * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
     *
     * ```
     * verify(r, s, h, P) where
     *   u1 = hs^-1 mod n
     *   u2 = rs^-1 mod n
     *   R = u1⋅G + u2⋅P
     *   mod(R.x, n) == r
     * ```
     */
    function verify(signature, message, publicKey, opts = {}) {
        const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
        publicKey = ensureBytes('publicKey', publicKey);
        message = validateMsgAndHash(ensureBytes('message', message), prehash);
        if ('strict' in opts)
            throw new Error('options.strict was renamed to lowS');
        const sig = format === undefined
            ? tryParsingSig(signature)
            : Signature.fromBytes(ensureBytes('sig', signature), format);
        if (sig === false)
            return false;
        try {
            const P = Point.fromBytes(publicKey);
            if (lowS && sig.hasHighS())
                return false;
            const { r, s } = sig;
            const h = bits2int_modN(message); // mod n, not mod p
            const is = Fn.inv(s); // s^-1 mod n
            const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
            const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
            const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
            if (R.is0())
                return false;
            const v = Fn.create(R.x); // v = r.x mod n
            return v === r;
        }
        catch (e) {
            return false;
        }
    }
    function recoverPublicKey(signature, message, opts = {}) {
        const { prehash } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash);
        return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
    }
    return Object.freeze({
        keygen,
        getPublicKey,
        getSharedSecret,
        utils,
        lengths,
        Point,
        sign,
        verify,
        recoverPublicKey,
        Signature,
        hash,
    });
}
function _weierstrass_legacy_opts_to_new(c) {
    const CURVE = {
        a: c.a,
        b: c.b,
        p: c.Fp.ORDER,
        n: c.n,
        h: c.h,
        Gx: c.Gx,
        Gy: c.Gy,
    };
    const Fp = c.Fp;
    let allowedLengths = c.allowedPrivateKeyLengths
        ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
        : undefined;
    const Fn = Field(CURVE.n, {
        BITS: c.nBitLength,
        allowedLengths: allowedLengths,
        modFromBytes: c.wrapPrivateKey,
    });
    const curveOpts = {
        Fp,
        Fn,
        allowInfinityPoint: c.allowInfinityPoint,
        endo: c.endo,
        isTorsionFree: c.isTorsionFree,
        clearCofactor: c.clearCofactor,
        fromBytes: c.fromBytes,
        toBytes: c.toBytes,
    };
    return { CURVE, curveOpts };
}
function _ecdsa_legacy_opts_to_new(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const ecdsaOpts = {
        hmac: c.hmac,
        randomBytes: c.randomBytes,
        lowS: c.lowS,
        bits2int: c.bits2int,
        bits2int_modN: c.bits2int_modN,
    };
    return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
    const Point = _ecdsa.Point;
    return Object.assign({}, _ecdsa, {
        ProjectivePoint: Point,
        CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
    });
}
// _ecdsa_legacy
function weierstrass(c) {
    const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    const signs = ecdsa(Point, hash, ecdsaOpts);
    return _ecdsa_new_output_to_legacy(c, signs);
}

/**
 * Utilities for short weierstrass curves, combined with noble-hashes.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
function createCurve(curveDef, defHash) {
    const create = (hash) => weierstrass({ ...curveDef, hash: hash });
    return { ...create(defHash), create };
}

/**
 * Internal module for NIST P256, P384, P521 curves.
 * Do not use for now.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// p = 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n - 1n
// a = Fp256.create(BigInt('-3'));
const p256_CURVE = {
    p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
    n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
    h: BigInt(1),
    a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
    b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
    Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
    Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
// p = 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n
const p384_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'),
    n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'),
    h: BigInt(1),
    a: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc'),
    b: BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'),
    Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'),
    Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'),
};
// p = 2n**521n - 1n
const p521_CURVE = {
    p: BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'),
    n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'),
    h: BigInt(1),
    a: BigInt('0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'),
    b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'),
    Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'),
    Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'),
};
const Fp256 = Field(p256_CURVE.p);
const Fp384 = Field(p384_CURVE.p);
const Fp521 = Field(p521_CURVE.p);
/** NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods. */
const p256$1 = createCurve({ ...p256_CURVE, Fp: Fp256, lowS: false }, sha256$1);
// export const p256_oprf: OPRF = createORPF({
//   name: 'P256-SHA256',
//   Point: p256.Point,
//   hash: sha256,
//   hashToGroup: p256_hasher.hashToCurve,
//   hashToScalar: p256_hasher.hashToScalar,
// });
/** NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. */
const p384$1 = createCurve({ ...p384_CURVE, Fp: Fp384, lowS: false }, sha384$1);
// export const p384_oprf: OPRF = createORPF({
//   name: 'P384-SHA384',
//   Point: p384.Point,
//   hash: sha384,
//   hashToGroup: p384_hasher.hashToCurve,
//   hashToScalar: p384_hasher.hashToScalar,
// });
// const Fn521 = Field(p521_CURVE.n, { allowedScalarLengths: [65, 66] });
/** NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. */
const p521$1 = createCurve({ ...p521_CURVE, Fp: Fp521, lowS: false, allowedPrivateKeyLengths: [130, 131, 132] }, sha512$1);
// export const p521_oprf: OPRF = createORPF({
//   name: 'P521-SHA512',
//   Point: p521.Point,
//   hash: sha512,
//   hashToGroup: p521_hasher.hashToCurve,
//   hashToScalar: p521_hasher.hashToScalar, // produces L=98 just like in RFC
// });

/**
 * NIST secp256r1 aka p256.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
/** @deprecated use `import { p256 } from '@noble/curves/nist.js';` */
const p256 = p256$1;

/**
 * NIST secp384r1 aka p384.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
/** @deprecated use `import { p384 } from '@noble/curves/nist.js';` */
const p384 = p384$1;

/**
 * NIST secp521r1 aka p521.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
/** @deprecated use `import { p521 } from '@noble/curves/nist.js';` */
const p521 = p521$1;

/**
 * SHA3 (keccak) hash function, based on a new "Sponge function" design.
 * Different from older hashes, the internal state is bigger than output size.
 *
 * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
 * [Website](https://keccak.team/keccak.html),
 * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).
 *
 * Check out `sha3-addons` module for cSHAKE, k12, and others.
 * @module
 */
// No __PURE__ annotations in sha3 header:
// EVERYTHING is in fact used on every export.
// Various per round constants calculations
const _0n$2 = BigInt(0);
const _1n$3 = BigInt(1);
const _2n$4 = BigInt(2);
const _7n = BigInt(7);
const _256n = BigInt(256);
const _0x71n = BigInt(0x71);
const SHA3_PI = [];
const SHA3_ROTL = [];
const _SHA3_IOTA = [];
for (let round = 0, R = _1n$3, x = 1, y = 0; round < 24; round++) {
    // Pi
    [x, y] = [y, (2 * x + 3 * y) % 5];
    SHA3_PI.push(2 * (5 * y + x));
    // Rotational
    SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
    // Iota
    let t = _0n$2;
    for (let j = 0; j < 7; j++) {
        R = ((R << _1n$3) ^ ((R >> _7n) * _0x71n)) % _256n;
        if (R & _2n$4)
            t ^= _1n$3 << ((_1n$3 << /* @__PURE__ */ BigInt(j)) - _1n$3);
    }
    _SHA3_IOTA.push(t);
}
const IOTAS = split(_SHA3_IOTA, true);
const SHA3_IOTA_H = IOTAS[0];
const SHA3_IOTA_L = IOTAS[1];
// Left rotation (without 0, 32, 64)
const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
/** `keccakf1600` internal function, additionally allows to adjust round count. */
function keccakP(s, rounds = 24) {
    const B = new Uint32Array(5 * 2);
    // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
    for (let round = 24 - rounds; round < 24; round++) {
        // Theta θ
        for (let x = 0; x < 10; x++)
            B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
        for (let x = 0; x < 10; x += 2) {
            const idx1 = (x + 8) % 10;
            const idx0 = (x + 2) % 10;
            const B0 = B[idx0];
            const B1 = B[idx0 + 1];
            const Th = rotlH(B0, B1, 1) ^ B[idx1];
            const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
            for (let y = 0; y < 50; y += 10) {
                s[x + y] ^= Th;
                s[x + y + 1] ^= Tl;
            }
        }
        // Rho (ρ) and Pi (π)
        let curH = s[2];
        let curL = s[3];
        for (let t = 0; t < 24; t++) {
            const shift = SHA3_ROTL[t];
            const Th = rotlH(curH, curL, shift);
            const Tl = rotlL(curH, curL, shift);
            const PI = SHA3_PI[t];
            curH = s[PI];
            curL = s[PI + 1];
            s[PI] = Th;
            s[PI + 1] = Tl;
        }
        // Chi (χ)
        for (let y = 0; y < 50; y += 10) {
            for (let x = 0; x < 10; x++)
                B[x] = s[y + x];
            for (let x = 0; x < 10; x++)
                s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
        }
        // Iota (ι)
        s[0] ^= SHA3_IOTA_H[round];
        s[1] ^= SHA3_IOTA_L[round];
    }
    clean(B);
}
/** Keccak sponge function. */
class Keccak extends Hash {
    // NOTE: we accept arguments in bytes instead of bits here.
    constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
        super();
        this.pos = 0;
        this.posOut = 0;
        this.finished = false;
        this.destroyed = false;
        this.enableXOF = false;
        this.blockLen = blockLen;
        this.suffix = suffix;
        this.outputLen = outputLen;
        this.enableXOF = enableXOF;
        this.rounds = rounds;
        // Can be passed from user as dkLen
        anumber(outputLen);
        // 1600 = 5x5 matrix of 64bit.  1600 bits === 200 bytes
        // 0 < blockLen < 200
        if (!(0 < blockLen && blockLen < 200))
            throw new Error('only keccak-f1600 function is supported');
        this.state = new Uint8Array(200);
        this.state32 = u32(this.state);
    }
    clone() {
        return this._cloneInto();
    }
    keccak() {
        swap32IfBE(this.state32);
        keccakP(this.state32, this.rounds);
        swap32IfBE(this.state32);
        this.posOut = 0;
        this.pos = 0;
    }
    update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { blockLen, state } = this;
        const len = data.length;
        for (let pos = 0; pos < len;) {
            const take = Math.min(blockLen - this.pos, len - pos);
            for (let i = 0; i < take; i++)
                state[this.pos++] ^= data[pos++];
            if (this.pos === blockLen)
                this.keccak();
        }
        return this;
    }
    finish() {
        if (this.finished)
            return;
        this.finished = true;
        const { state, suffix, pos, blockLen } = this;
        // Do the padding
        state[pos] ^= suffix;
        if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
            this.keccak();
        state[blockLen - 1] ^= 0x80;
        this.keccak();
    }
    writeInto(out) {
        aexists(this, false);
        abytes(out);
        this.finish();
        const bufferOut = this.state;
        const { blockLen } = this;
        for (let pos = 0, len = out.length; pos < len;) {
            if (this.posOut >= blockLen)
                this.keccak();
            const take = Math.min(blockLen - this.posOut, len - pos);
            out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
            this.posOut += take;
            pos += take;
        }
        return out;
    }
    xofInto(out) {
        // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
        if (!this.enableXOF)
            throw new Error('XOF is not possible for this instance');
        return this.writeInto(out);
    }
    xof(bytes) {
        anumber(bytes);
        return this.xofInto(new Uint8Array(bytes));
    }
    digestInto(out) {
        aoutput(out, this);
        if (this.finished)
            throw new Error('digest() was already called');
        this.writeInto(out);
        this.destroy();
        return out;
    }
    digest() {
        return this.digestInto(new Uint8Array(this.outputLen));
    }
    destroy() {
        this.destroyed = true;
        clean(this.state);
    }
    _cloneInto(to) {
        const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
        to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
        to.state32.set(this.state32);
        to.pos = this.pos;
        to.posOut = this.posOut;
        to.finished = this.finished;
        to.rounds = rounds;
        // Suffix can change in cSHAKE
        to.suffix = suffix;
        to.outputLen = outputLen;
        to.enableXOF = enableXOF;
        to.destroyed = this.destroyed;
        return to;
    }
}
const gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
/** SHA3-256 hash function. Different from keccak-256. */
const sha3_256 = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();
/** SHA3-512 hash function. */
const sha3_512 = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();
const genShake = (suffix, blockLen, outputLen) => createXOFer((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));
/** SHAKE256 XOF with 256-bit security. */
const shake256 = /* @__PURE__ */ (() => genShake(0x1f, 136, 256 / 8))();

/**
 * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
 * For design rationale of types / exports, see weierstrass module documentation.
 * Untwisted Edwards curves exist, but they aren't used in real-world protocols.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n$1 = BigInt(0), _1n$2 = BigInt(1), _2n$3 = BigInt(2), _8n = BigInt(8);
function isEdValidXY(Fp, CURVE, x, y) {
    const x2 = Fp.sqr(x);
    const y2 = Fp.sqr(y);
    const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
    const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
    return Fp.eql(left, right);
}
function edwards(params, extraOpts = {}) {
    const validated = _createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);
    const { Fp, Fn } = validated;
    let CURVE = validated.CURVE;
    const { h: cofactor } = CURVE;
    _validateObject(extraOpts, {}, { uvRatio: 'function' });
    // Important:
    // There are some places where Fp.BYTES is used instead of nByteLength.
    // So far, everything has been tested with curves of Fp.BYTES == nByteLength.
    // TODO: test and find curves which behave otherwise.
    const MASK = _2n$3 << (BigInt(Fn.BYTES * 8) - _1n$2);
    const modP = (n) => Fp.create(n); // Function overrides
    // sqrt(u/v)
    const uvRatio = extraOpts.uvRatio ||
        ((u, v) => {
            try {
                return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };
            }
            catch (e) {
                return { isValid: false, value: _0n$1 };
            }
        });
    // Validate whether the passed curve params are valid.
    // equation ax² + y² = 1 + dx²y² should work for generator point.
    if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))
        throw new Error('bad curve params: generator point');
    /**
     * Asserts coordinate is valid: 0 <= n < MASK.
     * Coordinates >= Fp.ORDER are allowed for zip215.
     */
    function acoord(title, n, banZero = false) {
        const min = banZero ? _1n$2 : _0n$1;
        aInRange('coordinate ' + title, n, min, MASK);
        return n;
    }
    function aextpoint(other) {
        if (!(other instanceof Point))
            throw new Error('ExtendedPoint expected');
    }
    // Converts Extended point to default (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    const toAffineMemo = memoized((p, iz) => {
        const { X, Y, Z } = p;
        const is0 = p.is0();
        if (iz == null)
            iz = is0 ? _8n : Fp.inv(Z); // 8 was chosen arbitrarily
        const x = modP(X * iz);
        const y = modP(Y * iz);
        const zz = Fp.mul(Z, iz);
        if (is0)
            return { x: _0n$1, y: _1n$2 };
        if (zz !== _1n$2)
            throw new Error('invZ was invalid');
        return { x, y };
    });
    const assertValidMemo = memoized((p) => {
        const { a, d } = CURVE;
        if (p.is0())
            throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?
        // Equation in affine coordinates: ax² + y² = 1 + dx²y²
        // Equation in projective coordinates (X/Z, Y/Z, Z):  (aX² + Y²)Z² = Z⁴ + dX²Y²
        const { X, Y, Z, T } = p;
        const X2 = modP(X * X); // X²
        const Y2 = modP(Y * Y); // Y²
        const Z2 = modP(Z * Z); // Z²
        const Z4 = modP(Z2 * Z2); // Z⁴
        const aX2 = modP(X2 * a); // aX²
        const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²
        const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²
        if (left !== right)
            throw new Error('bad point: equation left != right (1)');
        // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
        const XY = modP(X * Y);
        const ZT = modP(Z * T);
        if (XY !== ZT)
            throw new Error('bad point: equation left != right (2)');
        return true;
    });
    // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).
    // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
    class Point {
        constructor(X, Y, Z, T) {
            this.X = acoord('x', X);
            this.Y = acoord('y', Y);
            this.Z = acoord('z', Z, true);
            this.T = acoord('t', T);
            Object.freeze(this);
        }
        static CURVE() {
            return CURVE;
        }
        static fromAffine(p) {
            if (p instanceof Point)
                throw new Error('extended point not allowed');
            const { x, y } = p || {};
            acoord('x', x);
            acoord('y', y);
            return new Point(x, y, _1n$2, modP(x * y));
        }
        // Uses algo from RFC8032 5.1.3.
        static fromBytes(bytes, zip215 = false) {
            const len = Fp.BYTES;
            const { a, d } = CURVE;
            bytes = copyBytes(_abytes2(bytes, len, 'point'));
            _abool2(zip215, 'zip215');
            const normed = copyBytes(bytes); // copy again, we'll manipulate it
            const lastByte = bytes[len - 1]; // select last byte
            normed[len - 1] = lastByte & -129; // clear last bit
            const y = bytesToNumberLE(normed);
            // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
            // RFC8032 prohibits >= p, but ZIP215 doesn't
            // zip215=true:  0 <= y < MASK (2^256 for ed25519)
            // zip215=false: 0 <= y < P (2^255-19 for ed25519)
            const max = zip215 ? MASK : Fp.ORDER;
            aInRange('point.y', y, _0n$1, max);
            // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:
            // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)
            const y2 = modP(y * y); // denominator is always non-0 mod p.
            const u = modP(y2 - _1n$2); // u = y² - 1
            const v = modP(d * y2 - a); // v = d y² + 1.
            let { isValid, value: x } = uvRatio(u, v); // √(u/v)
            if (!isValid)
                throw new Error('bad point: invalid y coordinate');
            const isXOdd = (x & _1n$2) === _1n$2; // There are 2 square roots. Use x_0 bit to select proper
            const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit
            if (!zip215 && x === _0n$1 && isLastByteOdd)
                // if x=0 and x_0 = 1, fail
                throw new Error('bad point: x=0 and x_0=1');
            if (isLastByteOdd !== isXOdd)
                x = modP(-x); // if x_0 != x mod 2, set x = p-x
            return Point.fromAffine({ x, y });
        }
        static fromHex(bytes, zip215 = false) {
            return Point.fromBytes(ensureBytes('point', bytes), zip215);
        }
        get x() {
            return this.toAffine().x;
        }
        get y() {
            return this.toAffine().y;
        }
        precompute(windowSize = 8, isLazy = true) {
            wnaf.createCache(this, windowSize);
            if (!isLazy)
                this.multiply(_2n$3); // random number
            return this;
        }
        // Useful in fromAffine() - not for fromBytes(), which always created valid points.
        assertValidity() {
            assertValidMemo(this);
        }
        // Compare one point to another.
        equals(other) {
            aextpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            const X1Z2 = modP(X1 * Z2);
            const X2Z1 = modP(X2 * Z1);
            const Y1Z2 = modP(Y1 * Z2);
            const Y2Z1 = modP(Y2 * Z1);
            return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
        }
        is0() {
            return this.equals(Point.ZERO);
        }
        negate() {
            // Flips point sign to a negative one (-x, y in affine coords)
            return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
        }
        // Fast algo for doubling Extended Point.
        // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
        // Cost: 4M + 4S + 1*a + 6add + 1*2.
        double() {
            const { a } = CURVE;
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const A = modP(X1 * X1); // A = X12
            const B = modP(Y1 * Y1); // B = Y12
            const C = modP(_2n$3 * modP(Z1 * Z1)); // C = 2*Z12
            const D = modP(a * A); // D = a*A
            const x1y1 = X1 + Y1;
            const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B
            const G = D + B; // G = D+B
            const F = G - C; // F = G-C
            const H = D - B; // H = D-B
            const X3 = modP(E * F); // X3 = E*F
            const Y3 = modP(G * H); // Y3 = G*H
            const T3 = modP(E * H); // T3 = E*H
            const Z3 = modP(F * G); // Z3 = F*G
            return new Point(X3, Y3, Z3, T3);
        }
        // Fast algo for adding 2 Extended Points.
        // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
        // Cost: 9M + 1*a + 1*d + 7add.
        add(other) {
            aextpoint(other);
            const { a, d } = CURVE;
            const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
            const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
            const A = modP(X1 * X2); // A = X1*X2
            const B = modP(Y1 * Y2); // B = Y1*Y2
            const C = modP(T1 * d * T2); // C = T1*d*T2
            const D = modP(Z1 * Z2); // D = Z1*Z2
            const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B
            const F = D - C; // F = D-C
            const G = D + C; // G = D+C
            const H = modP(B - a * A); // H = B-a*A
            const X3 = modP(E * F); // X3 = E*F
            const Y3 = modP(G * H); // Y3 = G*H
            const T3 = modP(E * H); // T3 = E*H
            const Z3 = modP(F * G); // Z3 = F*G
            return new Point(X3, Y3, Z3, T3);
        }
        subtract(other) {
            return this.add(other.negate());
        }
        // Constant-time multiplication.
        multiply(scalar) {
            // 1 <= scalar < L
            if (!Fn.isValidNot0(scalar))
                throw new Error('invalid scalar: expected 1 <= sc < curve.n');
            const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));
            return normalizeZ(Point, [p, f])[0];
        }
        // Non-constant-time multiplication. Uses double-and-add algorithm.
        // It's faster, but should only be used when you don't care about
        // an exposed private key e.g. sig verification.
        // Does NOT allow scalars higher than CURVE.n.
        // Accepts optional accumulator to merge with multiply (important for sparse scalars)
        multiplyUnsafe(scalar, acc = Point.ZERO) {
            // 0 <= scalar < L
            if (!Fn.isValid(scalar))
                throw new Error('invalid scalar: expected 0 <= sc < curve.n');
            if (scalar === _0n$1)
                return Point.ZERO;
            if (this.is0() || scalar === _1n$2)
                return this;
            return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
        }
        // Checks if point is of small order.
        // If you add something to small order point, you will have "dirty"
        // point with torsion component.
        // Multiplies point by cofactor and checks if the result is 0.
        isSmallOrder() {
            return this.multiplyUnsafe(cofactor).is0();
        }
        // Multiplies point by curve order and checks if the result is 0.
        // Returns `false` is the point is dirty.
        isTorsionFree() {
            return wnaf.unsafe(this, CURVE.n).is0();
        }
        // Converts Extended point to default (x, y) coordinates.
        // Can accept precomputed Z^-1 - for example, from invertBatch.
        toAffine(invertedZ) {
            return toAffineMemo(this, invertedZ);
        }
        clearCofactor() {
            if (cofactor === _1n$2)
                return this;
            return this.multiplyUnsafe(cofactor);
        }
        toBytes() {
            const { x, y } = this.toAffine();
            // Fp.toBytes() allows non-canonical encoding of y (>= p).
            const bytes = Fp.toBytes(y);
            // Each y has 2 valid points: (x, y), (x,-y).
            // When compressing, it's enough to store y and use the last byte to encode sign of x
            bytes[bytes.length - 1] |= x & _1n$2 ? 0x80 : 0;
            return bytes;
        }
        toHex() {
            return bytesToHex(this.toBytes());
        }
        toString() {
            return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
        }
        // TODO: remove
        get ex() {
            return this.X;
        }
        get ey() {
            return this.Y;
        }
        get ez() {
            return this.Z;
        }
        get et() {
            return this.T;
        }
        static normalizeZ(points) {
            return normalizeZ(Point, points);
        }
        static msm(points, scalars) {
            return pippenger(Point, Fn, points, scalars);
        }
        _setWindowSize(windowSize) {
            this.precompute(windowSize);
        }
        toRawBytes() {
            return this.toBytes();
        }
    }
    // base / generator point
    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n$2, modP(CURVE.Gx * CURVE.Gy));
    // zero / infinity / identity point
    Point.ZERO = new Point(_0n$1, _1n$2, _1n$2, _0n$1); // 0, 1, 1, 0
    // math field
    Point.Fp = Fp;
    // scalar field
    Point.Fn = Fn;
    const wnaf = new wNAF(Point, Fn.BITS);
    Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
    return Point;
}
/**
 * Initializes EdDSA signatures over given Edwards curve.
 */
function eddsa(Point, cHash, eddsaOpts = {}) {
    if (typeof cHash !== 'function')
        throw new Error('"hash" function param is required');
    _validateObject(eddsaOpts, {}, {
        adjustScalarBytes: 'function',
        randomBytes: 'function',
        domain: 'function',
        prehash: 'function',
        mapToCurve: 'function',
    });
    const { prehash } = eddsaOpts;
    const { BASE, Fp, Fn } = Point;
    const randomBytes$1 = eddsaOpts.randomBytes || randomBytes;
    const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
    const domain = eddsaOpts.domain ||
        ((data, ctx, phflag) => {
            _abool2(phflag, 'phflag');
            if (ctx.length || phflag)
                throw new Error('Contexts/pre-hash are not supported');
            return data;
        }); // NOOP
    // Little-endian SHA512 with modulo n
    function modN_LE(hash) {
        return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit
    }
    // Get the hashed private scalar per RFC8032 5.1.5
    function getPrivateScalar(key) {
        const len = lengths.secretKey;
        key = ensureBytes('private key', key, len);
        // Hash private key with curve's hash function to produce uniformingly random input
        // Check byte lengths: ensure(64, h(ensure(32, key)))
        const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);
        const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE
        const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)
        const scalar = modN_LE(head); // The actual private scalar
        return { head, prefix, scalar };
    }
    /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */
    function getExtendedPublicKey(secretKey) {
        const { head, prefix, scalar } = getPrivateScalar(secretKey);
        const point = BASE.multiply(scalar); // Point on Edwards curve aka public key
        const pointBytes = point.toBytes();
        return { head, prefix, scalar, point, pointBytes };
    }
    /** Calculates EdDSA pub key. RFC8032 5.1.5. */
    function getPublicKey(secretKey) {
        return getExtendedPublicKey(secretKey).pointBytes;
    }
    // int('LE', SHA512(dom2(F, C) || msgs)) mod N
    function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
        const msg = concatBytes(...msgs);
        return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));
    }
    /** Signs message with privateKey. RFC8032 5.1.6 */
    function sign(msg, secretKey, options = {}) {
        msg = ensureBytes('message', msg);
        if (prehash)
            msg = prehash(msg); // for ed25519ph etc.
        const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
        const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)
        const R = BASE.multiply(r).toBytes(); // R = rG
        const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)
        const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L
        if (!Fn.isValid(s))
            throw new Error('sign failed: invalid s'); // 0 <= s < L
        const rs = concatBytes(R, Fn.toBytes(s));
        return _abytes2(rs, lengths.signature, 'result');
    }
    // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:
    const verifyOpts = { zip215: true };
    /**
     * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
     * An extended group equation is checked.
     */
    function verify(sig, msg, publicKey, options = verifyOpts) {
        const { context, zip215 } = options;
        const len = lengths.signature;
        sig = ensureBytes('signature', sig, len);
        msg = ensureBytes('message', msg);
        publicKey = ensureBytes('publicKey', publicKey, lengths.publicKey);
        if (zip215 !== undefined)
            _abool2(zip215, 'zip215');
        if (prehash)
            msg = prehash(msg); // for ed25519ph, etc
        const mid = len / 2;
        const r = sig.subarray(0, mid);
        const s = bytesToNumberLE(sig.subarray(mid, len));
        let A, R, SB;
        try {
            // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
            // zip215=true:  0 <= y < MASK (2^256 for ed25519)
            // zip215=false: 0 <= y < P (2^255-19 for ed25519)
            A = Point.fromBytes(publicKey, zip215);
            R = Point.fromBytes(r, zip215);
            SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside
        }
        catch (error) {
            return false;
        }
        if (!zip215 && A.isSmallOrder())
            return false; // zip215 allows public keys of small order
        const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
        const RkA = R.add(A.multiplyUnsafe(k));
        // Extended group equation
        // [8][S]B = [8]R + [8][k]A'
        return RkA.subtract(SB).clearCofactor().is0();
    }
    const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448
    const lengths = {
        secretKey: _size,
        publicKey: _size,
        signature: 2 * _size,
        seed: _size,
    };
    function randomSecretKey(seed = randomBytes$1(lengths.seed)) {
        return _abytes2(seed, lengths.seed, 'seed');
    }
    function keygen(seed) {
        const secretKey = utils.randomSecretKey(seed);
        return { secretKey, publicKey: getPublicKey(secretKey) };
    }
    function isValidSecretKey(key) {
        return isBytes(key) && key.length === Fn.BYTES;
    }
    function isValidPublicKey(key, zip215) {
        try {
            return !!Point.fromBytes(key, zip215);
        }
        catch (error) {
            return false;
        }
    }
    const utils = {
        getExtendedPublicKey,
        randomSecretKey,
        isValidSecretKey,
        isValidPublicKey,
        /**
         * Converts ed public key to x public key. Uses formula:
         * - ed25519:
         *   - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
         *   - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
         * - ed448:
         *   - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
         *   - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
         */
        toMontgomery(publicKey) {
            const { y } = Point.fromBytes(publicKey);
            const size = lengths.publicKey;
            const is25519 = size === 32;
            if (!is25519 && size !== 57)
                throw new Error('only defined for 25519 and 448');
            const u = is25519 ? Fp.div(_1n$2 + y, _1n$2 - y) : Fp.div(y - _1n$2, y + _1n$2);
            return Fp.toBytes(u);
        },
        toMontgomerySecret(secretKey) {
            const size = lengths.secretKey;
            _abytes2(secretKey, size);
            const hashed = cHash(secretKey.subarray(0, size));
            return adjustScalarBytes(hashed).subarray(0, size);
        },
        /** @deprecated */
        randomPrivateKey: randomSecretKey,
        /** @deprecated */
        precompute(windowSize = 8, point = Point.BASE) {
            return point.precompute(windowSize, false);
        },
    };
    return Object.freeze({
        keygen,
        getPublicKey,
        sign,
        verify,
        utils,
        Point,
        lengths,
    });
}
function _eddsa_legacy_opts_to_new(c) {
    const CURVE = {
        a: c.a,
        d: c.d,
        p: c.Fp.ORDER,
        n: c.n,
        h: c.h,
        Gx: c.Gx,
        Gy: c.Gy,
    };
    const Fp = c.Fp;
    const Fn = Field(CURVE.n, c.nBitLength, true);
    const curveOpts = { Fp, Fn, uvRatio: c.uvRatio };
    const eddsaOpts = {
        randomBytes: c.randomBytes,
        adjustScalarBytes: c.adjustScalarBytes,
        domain: c.domain,
        prehash: c.prehash,
        mapToCurve: c.mapToCurve,
    };
    return { CURVE, curveOpts, hash: c.hash, eddsaOpts };
}
function _eddsa_new_output_to_legacy(c, eddsa) {
    const Point = eddsa.Point;
    const legacy = Object.assign({}, eddsa, {
        ExtendedPoint: Point,
        CURVE: c,
        nBitLength: Point.Fn.BITS,
        nByteLength: Point.Fn.BYTES,
    });
    return legacy;
}
// TODO: remove. Use eddsa
function twistedEdwards(c) {
    const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);
    const Point = edwards(CURVE, curveOpts);
    const EDDSA = eddsa(Point, hash, eddsaOpts);
    return _eddsa_new_output_to_legacy(c, EDDSA);
}

/**
 * Montgomery curve methods. It's not really whole montgomery curve,
 * just bunch of very specific methods for X25519 / X448 from
 * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n = BigInt(0);
const _1n$1 = BigInt(1);
const _2n$2 = BigInt(2);
function validateOpts(curve) {
    _validateObject(curve, {
        adjustScalarBytes: 'function',
        powPminus2: 'function',
    });
    return Object.freeze({ ...curve });
}
function montgomery(curveDef) {
    const CURVE = validateOpts(curveDef);
    const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE;
    const is25519 = type === 'x25519';
    if (!is25519 && type !== 'x448')
        throw new Error('invalid type');
    const randomBytes_ = rand || randomBytes;
    const montgomeryBits = is25519 ? 255 : 448;
    const fieldLen = is25519 ? 32 : 56;
    const Gu = is25519 ? BigInt(9) : BigInt(5);
    // RFC 7748 #5:
    // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and
    // (156326 - 2) / 4 = 39081 for curve448/X448
    // const a = is25519 ? 156326n : 486662n;
    const a24 = is25519 ? BigInt(121665) : BigInt(39081);
    // RFC: x25519 "the resulting integer is of the form 2^254 plus
    // eight times a value between 0 and 2^251 - 1 (inclusive)"
    // x448: "2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)"
    const minScalar = is25519 ? _2n$2 ** BigInt(254) : _2n$2 ** BigInt(447);
    const maxAdded = is25519
        ? BigInt(8) * _2n$2 ** BigInt(251) - _1n$1
        : BigInt(4) * _2n$2 ** BigInt(445) - _1n$1;
    const maxScalar = minScalar + maxAdded + _1n$1; // (inclusive)
    const modP = (n) => mod(n, P);
    const GuBytes = encodeU(Gu);
    function encodeU(u) {
        return numberToBytesLE(modP(u), fieldLen);
    }
    function decodeU(u) {
        const _u = ensureBytes('u coordinate', u, fieldLen);
        // RFC: When receiving such an array, implementations of X25519
        // (but not X448) MUST mask the most significant bit in the final byte.
        if (is25519)
            _u[31] &= 127; // 0b0111_1111
        // RFC: Implementations MUST accept non-canonical values and process them as
        // if they had been reduced modulo the field prime.  The non-canonical
        // values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224
        // - 1 through 2^448 - 1 for X448.
        return modP(bytesToNumberLE(_u));
    }
    function decodeScalar(scalar) {
        return bytesToNumberLE(adjustScalarBytes(ensureBytes('scalar', scalar, fieldLen)));
    }
    function scalarMult(scalar, u) {
        const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
        // Some public keys are useless, of low-order. Curve author doesn't think
        // it needs to be validated, but we do it nonetheless.
        // https://cr.yp.to/ecdh.html#validate
        if (pu === _0n)
            throw new Error('invalid private or public key received');
        return encodeU(pu);
    }
    // Computes public key from private. By doing scalar multiplication of base point.
    function scalarMultBase(scalar) {
        return scalarMult(scalar, GuBytes);
    }
    // cswap from RFC7748 "example code"
    function cswap(swap, x_2, x_3) {
        // dummy = mask(swap) AND (x_2 XOR x_3)
        // Where mask(swap) is the all-1 or all-0 word of the same length as x_2
        // and x_3, computed, e.g., as mask(swap) = 0 - swap.
        const dummy = modP(swap * (x_2 - x_3));
        x_2 = modP(x_2 - dummy); // x_2 = x_2 XOR dummy
        x_3 = modP(x_3 + dummy); // x_3 = x_3 XOR dummy
        return { x_2, x_3 };
    }
    /**
     * Montgomery x-only multiplication ladder.
     * @param pointU u coordinate (x) on Montgomery Curve 25519
     * @param scalar by which the point would be multiplied
     * @returns new Point on Montgomery curve
     */
    function montgomeryLadder(u, scalar) {
        aInRange('u', u, _0n, P);
        aInRange('scalar', scalar, minScalar, maxScalar);
        const k = scalar;
        const x_1 = u;
        let x_2 = _1n$1;
        let z_2 = _0n;
        let x_3 = u;
        let z_3 = _1n$1;
        let swap = _0n;
        for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {
            const k_t = (k >> t) & _1n$1;
            swap ^= k_t;
            ({ x_2, x_3 } = cswap(swap, x_2, x_3));
            ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
            swap = k_t;
            const A = x_2 + z_2;
            const AA = modP(A * A);
            const B = x_2 - z_2;
            const BB = modP(B * B);
            const E = AA - BB;
            const C = x_3 + z_3;
            const D = x_3 - z_3;
            const DA = modP(D * A);
            const CB = modP(C * B);
            const dacb = DA + CB;
            const da_cb = DA - CB;
            x_3 = modP(dacb * dacb);
            z_3 = modP(x_1 * modP(da_cb * da_cb));
            x_2 = modP(AA * BB);
            z_2 = modP(E * (AA + modP(a24 * E)));
        }
        ({ x_2, x_3 } = cswap(swap, x_2, x_3));
        ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
        const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent
        return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2))
    }
    const lengths = {
        secretKey: fieldLen,
        publicKey: fieldLen,
        seed: fieldLen,
    };
    const randomSecretKey = (seed = randomBytes_(fieldLen)) => {
        abytes(seed, lengths.seed);
        return seed;
    };
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: scalarMultBase(secretKey) };
    }
    const utils = {
        randomSecretKey,
        randomPrivateKey: randomSecretKey,
    };
    return {
        keygen,
        getSharedSecret: (secretKey, publicKey) => scalarMult(secretKey, publicKey),
        getPublicKey: (secretKey) => scalarMultBase(secretKey),
        scalarMult,
        scalarMultBase,
        utils,
        GuBytes: GuBytes.slice(),
        lengths,
    };
}

/**
 * Edwards448 (not Ed448-Goldilocks) curve with following addons:
 * - X448 ECDH
 * - Decaf cofactor elimination
 * - Elligator hash-to-group / point indistinguishability
 * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// edwards448 curve
// a = 1n
// d = Fp.neg(39081n)
// Finite field 2n**448n - 2n**224n - 1n
// Subgroup order
// 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n
const ed448_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffff'),
    n: BigInt('0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f3'),
    h: BigInt(4),
    a: BigInt(1),
    d: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffff6756'),
    Gx: BigInt('0x4f1970c66bed0ded221d15a622bf36da9e146570470f1767ea6de324a3d3a46412ae1af72ab66511433b80e18b00938e2626a82bc70cc05e'),
    Gy: BigInt('0x693f46716eb6bc248876203756c9c7624bea73736ca3984087789c1e05a0c2d73ad3ff1ce67c39c4fdbd132c4ed7c8ad9808795bf230fa14'),
};
// E448 NIST curve is identical to edwards448, except for:
// d = 39082/39081
// Gx = 3/2
const E448_CURVE = Object.assign({}, ed448_CURVE, {
    d: BigInt('0xd78b4bdc7f0daf19f24f38c29373a2ccad46157242a50f37809b1da3412a12e79ccc9c81264cfe9ad080997058fb61c4243cc32dbaa156b9'),
    Gx: BigInt('0x79a70b2b70400553ae7c9df416c792c61128751ac92969240c25a07d728bdc93e21f7787ed6972249de732f38496cd11698713093e9c04fc'),
    Gy: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff80000000000000000000000000000000000000000000000000000001'),
});
const shake256_114 = /* @__PURE__ */ createHasher(() => shake256.create({ dkLen: 114 }));
// prettier-ignore
const _1n = BigInt(1), _2n$1 = BigInt(2), _3n = BigInt(3); BigInt(4); const _11n = BigInt(11);
// prettier-ignore
const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223);
// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4.
// Used for efficient square root calculation.
// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1]
function ed448_pow_Pminus3div4(x) {
    const P = ed448_CURVE.p;
    const b2 = (x * x * x) % P;
    const b3 = (b2 * b2 * x) % P;
    const b6 = (pow2(b3, _3n, P) * b3) % P;
    const b9 = (pow2(b6, _3n, P) * b3) % P;
    const b11 = (pow2(b9, _2n$1, P) * b2) % P;
    const b22 = (pow2(b11, _11n, P) * b11) % P;
    const b44 = (pow2(b22, _22n, P) * b22) % P;
    const b88 = (pow2(b44, _44n, P) * b44) % P;
    const b176 = (pow2(b88, _88n, P) * b88) % P;
    const b220 = (pow2(b176, _44n, P) * b44) % P;
    const b222 = (pow2(b220, _2n$1, P) * b2) % P;
    const b223 = (pow2(b222, _1n, P) * x) % P;
    return (pow2(b223, _223n, P) * b222) % P;
}
function adjustScalarBytes(bytes) {
    // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0,
    bytes[0] &= 252; // 0b11111100
    // and the most significant bit of the last byte to 1.
    bytes[55] |= 128; // 0b10000000
    // NOTE: is NOOP for 56 bytes scalars (X25519/X448)
    bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits)
    return bytes;
}
// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v.
// Uses algo from RFC8032 5.1.3.
function uvRatio(u, v) {
    const P = ed448_CURVE.p;
    // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3
    // To compute the square root of (u/v), the first step is to compute the
    //   candidate root x = (u/v)^((p+1)/4).  This can be done using the
    // following trick, to use a single modular powering for both the
    // inversion of v and the square root:
    // x = (u/v)^((p+1)/4)   = u³v(u⁵v³)^((p-3)/4)   (mod p)
    const u2v = mod(u * u * v, P); // u²v
    const u3v = mod(u2v * u, P); // u³v
    const u5v3 = mod(u3v * u2v * v, P); // u⁵v³
    const root = ed448_pow_Pminus3div4(u5v3);
    const x = mod(u3v * root, P);
    // Verify that root is exists
    const x2 = mod(x * x, P); // x²
    // If vx² = u, the recovered x-coordinate is x.  Otherwise, no
    // square root exists, and the decoding fails.
    return { isValid: mod(x2 * v, P) === u, value: x };
}
// Finite field 2n**448n - 2n**224n - 1n
// The value fits in 448 bits, but we use 456-bit (57-byte) elements because of bitflags.
// - ed25519 fits in 255 bits, allowing using last 1 byte for specifying bit flag of point negation.
// - ed448 fits in 448 bits. We can't use last 1 byte: we can only use a bit 224 in the middle.
const Fp$3 = /* @__PURE__ */ (() => Field(ed448_CURVE.p, { BITS: 456, isLE: true }))();
const Fn = /* @__PURE__ */ (() => Field(ed448_CURVE.n, { BITS: 456, isLE: true }))();
// SHAKE256(dom4(phflag,context)||x, 114)
function dom4(data, ctx, phflag) {
    if (ctx.length > 255)
        throw new Error('context must be smaller than 255, got: ' + ctx.length);
    return concatBytes(asciiToBytes('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
}
// const ed448_eddsa_opts = { adjustScalarBytes, domain: dom4 };
// const ed448_Point = edwards(ed448_CURVE, { Fp, Fn, uvRatio });
const ED448_DEF = /* @__PURE__ */ (() => ({
    ...ed448_CURVE,
    Fp: Fp$3,
    Fn,
    nBitLength: Fn.BITS,
    hash: shake256_114,
    adjustScalarBytes,
    domain: dom4,
    uvRatio,
}))();
/**
 * ed448 EdDSA curve and methods.
 * @example
 * import { ed448 } from '@noble/curves/ed448';
 * const { secretKey, publicKey } = ed448.keygen();
 * const msg = new TextEncoder().encode('hello');
 * const sig = ed448.sign(msg, secretKey);
 * const isValid = ed448.verify(sig, msg, publicKey);
 */
const ed448 = twistedEdwards(ED448_DEF);
/**
 * E448 curve, defined by NIST.
 * E448 != edwards448 used in ed448.
 * E448 is birationally equivalent to edwards448.
 */
edwards(E448_CURVE);
/**
 * ECDH using curve448 aka x448.
 * x448 has 56-byte keys as per RFC 7748, while
 * ed448 has 57-byte keys as per RFC 8032.
 */
const x448 = /* @__PURE__ */ (() => {
    const P = ed448_CURVE.p;
    return montgomery({
        P,
        type: 'x448',
        powPminus2: (x) => {
            const Pminus3div4 = ed448_pow_Pminus3div4(x);
            const Pminus3 = pow2(Pminus3div4, _2n$1, P);
            return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2
        },
        adjustScalarBytes,
    });
})();

/**
 * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
 *
 * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
 * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// Seems like generator was produced from some seed:
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
const secp256k1_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
    n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
    h: BigInt(1),
    a: BigInt(0),
    b: BigInt(7),
    Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
    Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
};
const secp256k1_ENDO = {
    beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
    basises: [
        [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
        [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
    ],
};
const _2n = /* @__PURE__ */ BigInt(2);
/**
 * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
 * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
 */
function sqrtMod(y) {
    const P = secp256k1_CURVE.p;
    // prettier-ignore
    const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
    // prettier-ignore
    const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
    const b2 = (y * y * y) % P; // x^3, 11
    const b3 = (b2 * b2 * y) % P; // x^7
    const b6 = (pow2(b3, _3n, P) * b3) % P;
    const b9 = (pow2(b6, _3n, P) * b3) % P;
    const b11 = (pow2(b9, _2n, P) * b2) % P;
    const b22 = (pow2(b11, _11n, P) * b11) % P;
    const b44 = (pow2(b22, _22n, P) * b22) % P;
    const b88 = (pow2(b44, _44n, P) * b44) % P;
    const b176 = (pow2(b88, _88n, P) * b88) % P;
    const b220 = (pow2(b176, _44n, P) * b44) % P;
    const b223 = (pow2(b220, _3n, P) * b3) % P;
    const t1 = (pow2(b223, _23n, P) * b22) % P;
    const t2 = (pow2(t1, _6n, P) * b2) % P;
    const root = pow2(t2, _2n, P);
    if (!Fpk1.eql(Fpk1.sqr(root), y))
        throw new Error('Cannot find square root');
    return root;
}
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
 * secp256k1 curve, ECDSA and ECDH methods.
 *
 * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
 *
 * @example
 * ```js
 * import { secp256k1 } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = secp256k1.keygen();
 * const msg = new TextEncoder().encode('hello');
 * const sig = secp256k1.sign(msg, secretKey);
 * const isValid = secp256k1.verify(sig, msg, publicKey) === true;
 * ```
 */
const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256$1);

/**
 * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
 *
 * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
 * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
 *
 * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
 * @module
 * @deprecated
 */
/** @deprecated Use import from `noble/hashes/sha2` module */
const sha256 = sha256$1;
/** @deprecated Use import from `noble/hashes/sha2` module */
const sha224 = sha224$1;

/** @access private */
// brainpoolP256r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.4
const Fp$2 = Field(BigInt('0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377'));
const CURVE_A$2 = Fp$2.create(BigInt('0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9'));
const CURVE_B$2 = BigInt('0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6');
// prettier-ignore
const brainpoolP256r1 = createCurve({
    a: CURVE_A$2, // Equation params: a, b
    b: CURVE_B$2,
    Fp: Fp$2,
    // Curve order (q), total count of valid points in the field
    n: BigInt('0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7'),
    // Base (generator) point (x, y)
    Gx: BigInt('0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262'),
    Gy: BigInt('0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997'),
    h: BigInt(1),
    lowS: false
}, sha256);

/**
 * SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.
 *
 * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
 * [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).
 * @module
 * @deprecated
 */
/** @deprecated Use import from `noble/hashes/sha2` module */
const sha512 = sha512$1;
/** @deprecated Use import from `noble/hashes/sha2` module */
const sha384 = sha384$1;

/** @access private */
// brainpoolP384 r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.6
const Fp$1 = Field(BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53'));
const CURVE_A$1 = Fp$1.create(BigInt('0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826'));
const CURVE_B$1 = BigInt('0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11');
// prettier-ignore
const brainpoolP384r1 = createCurve({
    a: CURVE_A$1, // Equation params: a, b
    b: CURVE_B$1,
    Fp: Fp$1,
    // Curve order (q), total count of valid points in the field
    n: BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565'),
    // Base (generator) point (x, y)
    Gx: BigInt('0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e'),
    Gy: BigInt('0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315'),
    h: BigInt(1),
    lowS: false
}, sha384);

/** @access private */
// brainpoolP512r1: https://datatracker.ietf.org/doc/html/rfc5639#section-3.7
const Fp = Field(BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3'));
const CURVE_A = Fp.create(BigInt('0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca'));
const CURVE_B = BigInt('0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723');
// prettier-ignore
const brainpoolP512r1 = createCurve({
    a: CURVE_A, // Equation params: a, b
    b: CURVE_B,
    Fp,
    // Curve order (q), total count of valid points in the field
    n: BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069'),
    // Base (generator) point (x, y)
    Gx: BigInt('0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822'),
    Gy: BigInt('0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892'),
    h: BigInt(1),
    lowS: false
}, sha512);

/**
 * @access private
 * This file is needed to dynamic import the noble-curves.
 * Separate dynamic imports are not convenient as they result in too many chunks,
 * which share a lot of code anyway.
 */
const nobleCurves = new Map(Object.entries({
    nistP256: p256,
    nistP384: p384,
    nistP521: p521,
    brainpoolP256r1,
    brainpoolP384r1,
    brainpoolP512r1,
    secp256k1,
    x448,
    ed448
}));

var noble_curves = /*#__PURE__*/Object.freeze({
  __proto__: null,
  nobleCurves: nobleCurves
});

/**

SHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.
Don't use them in a new protocol. What "weak" means:

- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.
- No practical pre-image attacks (only theoretical, 2^123.4)
- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151
 * @module
 */
/** Initial SHA1 state */
const SHA1_IV = /* @__PURE__ */ Uint32Array.from([
    0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,
]);
// Reusable temporary buffer
const SHA1_W = /* @__PURE__ */ new Uint32Array(80);
/** SHA1 legacy hash class. */
class SHA1 extends HashMD {
    constructor() {
        super(64, 20, 8, false);
        this.A = SHA1_IV[0] | 0;
        this.B = SHA1_IV[1] | 0;
        this.C = SHA1_IV[2] | 0;
        this.D = SHA1_IV[3] | 0;
        this.E = SHA1_IV[4] | 0;
    }
    get() {
        const { A, B, C, D, E } = this;
        return [A, B, C, D, E];
    }
    set(A, B, C, D, E) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
    }
    process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
            SHA1_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 80; i++)
            SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);
        // Compression function main loop, 80 rounds
        let { A, B, C, D, E } = this;
        for (let i = 0; i < 80; i++) {
            let F, K;
            if (i < 20) {
                F = Chi$1(B, C, D);
                K = 0x5a827999;
            }
            else if (i < 40) {
                F = B ^ C ^ D;
                K = 0x6ed9eba1;
            }
            else if (i < 60) {
                F = Maj(B, C, D);
                K = 0x8f1bbcdc;
            }
            else {
                F = B ^ C ^ D;
                K = 0xca62c1d6;
            }
            const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;
            E = D;
            D = C;
            C = rotl(B, 30);
            B = A;
            A = T;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        this.set(A, B, C, D, E);
    }
    roundClean() {
        clean(SHA1_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */
const sha1$1 = /* @__PURE__ */ createHasher(() => new SHA1());
// RIPEMD-160
const Rho160 = /* @__PURE__ */ Uint8Array.from([
    7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
]);
const Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();
const Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();
const idxLR = /* @__PURE__ */ (() => {
    const L = [Id160];
    const R = [Pi160];
    const res = [L, R];
    for (let i = 0; i < 4; i++)
        for (let j of res)
            j.push(j[i].map((k) => Rho160[k]));
    return res;
})();
const idxL = /* @__PURE__ */ (() => idxLR[0])();
const idxR = /* @__PURE__ */ (() => idxLR[1])();
// const [idxL, idxR] = idxLR;
const shifts160 = /* @__PURE__ */ [
    [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
    [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
    [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
    [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
    [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],
].map((i) => Uint8Array.from(i));
const shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));
const shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));
const Kl160 = /* @__PURE__ */ Uint32Array.from([
    0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,
]);
const Kr160 = /* @__PURE__ */ Uint32Array.from([
    0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,
]);
// It's called f() in spec.
function ripemd_f(group, x, y, z) {
    if (group === 0)
        return x ^ y ^ z;
    if (group === 1)
        return (x & y) | (~x & z);
    if (group === 2)
        return (x | ~y) ^ z;
    if (group === 3)
        return (x & z) | (y & ~z);
    return x ^ (y | ~z);
}
// Reusable temporary buffer
const BUF_160 = /* @__PURE__ */ new Uint32Array(16);
class RIPEMD160 extends HashMD {
    constructor() {
        super(64, 20, 8, true);
        this.h0 = 0x67452301 | 0;
        this.h1 = 0xefcdab89 | 0;
        this.h2 = 0x98badcfe | 0;
        this.h3 = 0x10325476 | 0;
        this.h4 = 0xc3d2e1f0 | 0;
    }
    get() {
        const { h0, h1, h2, h3, h4 } = this;
        return [h0, h1, h2, h3, h4];
    }
    set(h0, h1, h2, h3, h4) {
        this.h0 = h0 | 0;
        this.h1 = h1 | 0;
        this.h2 = h2 | 0;
        this.h3 = h3 | 0;
        this.h4 = h4 | 0;
    }
    process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
            BUF_160[i] = view.getUint32(offset, true);
        // prettier-ignore
        let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;
        // Instead of iterating 0 to 80, we split it into 5 groups
        // And use the groups in constants, functions, etc. Much simpler
        for (let group = 0; group < 5; group++) {
            const rGroup = 4 - group;
            const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore
            const rl = idxL[group], rr = idxR[group]; // prettier-ignore
            const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore
            for (let i = 0; i < 16; i++) {
                const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;
                al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore
            }
            // 2 loops are 10% faster
            for (let i = 0; i < 16; i++) {
                const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;
                ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore
            }
        }
        // Add the compressed chunk to the current hash value
        this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);
    }
    roundClean() {
        clean(BUF_160);
    }
    destroy() {
        this.destroyed = true;
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0);
    }
}
/**
 * RIPEMD-160 - a legacy hash function from 1990s.
 * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
 * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
 */
const ripemd160$1 = /* @__PURE__ */ createHasher(() => new RIPEMD160());

/**
 * SHA1 (RFC 3174) legacy hash function.
 * @module
 * @deprecated
 */
/** @deprecated Use import from `noble/hashes/legacy` module */
const sha1 = sha1$1;

/**
 * RIPEMD-160 legacy hash function.
 * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
 * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
 * @module
 * @deprecated
 */
/** @deprecated Use import from `noble/hashes/legacy` module */
const ripemd160 = ripemd160$1;

/** @access private */
// Copied from https://github.com/paulmillr/noble-hashes/blob/main/test/misc/md5.ts
// Per-round constants
const K$1 = Array.from({ length: 64 }, (_, i) => Math.floor(2 ** 32 * Math.abs(Math.sin(i + 1))));
// Choice: a ? b : c
const Chi = (a, b, c) => (a & b) ^ (~a & c);
// Initial state (same as sha1, but 4 u32 instead of 5)
const IV = /* @__PURE__ */ new Uint32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]);
// Temporary buffer, not used to store anything between runs
// Named this way for SHA1 compat
const MD5_W = /* @__PURE__ */ new Uint32Array(16);
class MD5 extends HashMD {
    constructor() {
        super(64, 16, 8, true);
        this.A = IV[0] | 0;
        this.B = IV[1] | 0;
        this.C = IV[2] | 0;
        this.D = IV[3] | 0;
    }
    get() {
        const { A, B, C, D } = this;
        return [A, B, C, D];
    }
    set(A, B, C, D) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
    }
    process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
            MD5_W[i] = view.getUint32(offset, true);
        // Compression function main loop, 64 rounds
        let { A, B, C, D } = this;
        for (let i = 0; i < 64; i++) {
            let F, g, s;
            if (i < 16) {
                F = Chi(B, C, D);
                g = i;
                s = [7, 12, 17, 22];
            }
            else if (i < 32) {
                F = Chi(D, B, C);
                g = (5 * i + 1) % 16;
                s = [5, 9, 14, 20];
            }
            else if (i < 48) {
                F = B ^ C ^ D;
                g = (3 * i + 5) % 16;
                s = [4, 11, 16, 23];
            }
            else {
                F = C ^ (B | ~D);
                g = (7 * i) % 16;
                s = [6, 10, 15, 21];
            }
            F = F + A + K$1[i] + MD5_W[g];
            A = D;
            D = C;
            C = B;
            B = B + rotl(F, s[i % 4]);
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        this.set(A, B, C, D);
    }
    roundClean() {
        MD5_W.fill(0);
    }
    destroy() {
        this.set(0, 0, 0, 0);
        this.buffer.fill(0);
    }
}
const md5 = /* @__PURE__ */ wrapConstructor(() => new MD5());

/**
 * @access private
 * This file is needed to dynamic import the noble-hashes.
 * Separate dynamic imports are not convenient as they result in too many chunks,
 * which share a lot of code anyway.
 */
const nobleHashes = new Map(Object.entries({
    md5,
    sha1,
    sha224,
    sha256,
    sha384,
    sha512,
    sha3_256,
    sha3_512,
    ripemd160
}));

var noble_hashes = /*#__PURE__*/Object.freeze({
  __proto__: null,
  nobleHashes: nobleHashes
});

// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// See utils.ts for details.
const crypto$1 =
  nc && typeof nc === 'object' && 'webcrypto' in nc ? nc.webcrypto : undefined;

const nacl = {};

// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
// Public domain.
//
// Implementation derived from TweetNaCl version 20140427.
// See for details: http://tweetnacl.cr.yp.to/

var gf = function(init) {
  var i, r = new Float64Array(16);
  if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
  return r;
};

//  Pluggable, initialized in high-level API below.
var randombytes = function(/* x, n */) { throw new Error('no PRNG'); };

var _9 = new Uint8Array(32); _9[0] = 9;

var gf0 = gf(),
    gf1 = gf([1]),
    _121665 = gf([0xdb41, 1]),
    D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
    D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
    X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
    Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
    I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);

function ts64(x, i, h, l) {
  x[i]   = (h >> 24) & 0xff;
  x[i+1] = (h >> 16) & 0xff;
  x[i+2] = (h >>  8) & 0xff;
  x[i+3] = h & 0xff;
  x[i+4] = (l >> 24)  & 0xff;
  x[i+5] = (l >> 16)  & 0xff;
  x[i+6] = (l >>  8)  & 0xff;
  x[i+7] = l & 0xff;
}

function vn(x, xi, y, yi, n) {
  var i,d = 0;
  for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];
  return (1 & ((d - 1) >>> 8)) - 1;
}

function crypto_verify_32(x, xi, y, yi) {
  return vn(x,xi,y,yi,32);
}

function set25519(r, a) {
  var i;
  for (i = 0; i < 16; i++) r[i] = a[i]|0;
}

function car25519(o) {
  var i, v, c = 1;
  for (i = 0; i < 16; i++) {
    v = o[i] + c + 65535;
    c = Math.floor(v / 65536);
    o[i] = v - c * 65536;
  }
  o[0] += c-1 + 37 * (c-1);
}

function sel25519(p, q, b) {
  var t, c = ~(b-1);
  for (var i = 0; i < 16; i++) {
    t = c & (p[i] ^ q[i]);
    p[i] ^= t;
    q[i] ^= t;
  }
}

function pack25519(o, n) {
  var i, j, b;
  var m = gf(), t = gf();
  for (i = 0; i < 16; i++) t[i] = n[i];
  car25519(t);
  car25519(t);
  car25519(t);
  for (j = 0; j < 2; j++) {
    m[0] = t[0] - 0xffed;
    for (i = 1; i < 15; i++) {
      m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
      m[i-1] &= 0xffff;
    }
    m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
    b = (m[15]>>16) & 1;
    m[14] &= 0xffff;
    sel25519(t, m, 1-b);
  }
  for (i = 0; i < 16; i++) {
    o[2*i] = t[i] & 0xff;
    o[2*i+1] = t[i]>>8;
  }
}

function neq25519(a, b) {
  var c = new Uint8Array(32), d = new Uint8Array(32);
  pack25519(c, a);
  pack25519(d, b);
  return crypto_verify_32(c, 0, d, 0);
}

function par25519(a) {
  var d = new Uint8Array(32);
  pack25519(d, a);
  return d[0] & 1;
}

function unpack25519(o, n) {
  var i;
  for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);
  o[15] &= 0x7fff;
}

function A(o, a, b) {
  for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
}

function Z(o, a, b) {
  for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
}

function M(o, a, b) {
  var v, c,
     t0 = 0,  t1 = 0,  t2 = 0,  t3 = 0,  t4 = 0,  t5 = 0,  t6 = 0,  t7 = 0,
     t8 = 0,  t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
    t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
    t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
    b0 = b[0],
    b1 = b[1],
    b2 = b[2],
    b3 = b[3],
    b4 = b[4],
    b5 = b[5],
    b6 = b[6],
    b7 = b[7],
    b8 = b[8],
    b9 = b[9],
    b10 = b[10],
    b11 = b[11],
    b12 = b[12],
    b13 = b[13],
    b14 = b[14],
    b15 = b[15];

  v = a[0];
  t0 += v * b0;
  t1 += v * b1;
  t2 += v * b2;
  t3 += v * b3;
  t4 += v * b4;
  t5 += v * b5;
  t6 += v * b6;
  t7 += v * b7;
  t8 += v * b8;
  t9 += v * b9;
  t10 += v * b10;
  t11 += v * b11;
  t12 += v * b12;
  t13 += v * b13;
  t14 += v * b14;
  t15 += v * b15;
  v = a[1];
  t1 += v * b0;
  t2 += v * b1;
  t3 += v * b2;
  t4 += v * b3;
  t5 += v * b4;
  t6 += v * b5;
  t7 += v * b6;
  t8 += v * b7;
  t9 += v * b8;
  t10 += v * b9;
  t11 += v * b10;
  t12 += v * b11;
  t13 += v * b12;
  t14 += v * b13;
  t15 += v * b14;
  t16 += v * b15;
  v = a[2];
  t2 += v * b0;
  t3 += v * b1;
  t4 += v * b2;
  t5 += v * b3;
  t6 += v * b4;
  t7 += v * b5;
  t8 += v * b6;
  t9 += v * b7;
  t10 += v * b8;
  t11 += v * b9;
  t12 += v * b10;
  t13 += v * b11;
  t14 += v * b12;
  t15 += v * b13;
  t16 += v * b14;
  t17 += v * b15;
  v = a[3];
  t3 += v * b0;
  t4 += v * b1;
  t5 += v * b2;
  t6 += v * b3;
  t7 += v * b4;
  t8 += v * b5;
  t9 += v * b6;
  t10 += v * b7;
  t11 += v * b8;
  t12 += v * b9;
  t13 += v * b10;
  t14 += v * b11;
  t15 += v * b12;
  t16 += v * b13;
  t17 += v * b14;
  t18 += v * b15;
  v = a[4];
  t4 += v * b0;
  t5 += v * b1;
  t6 += v * b2;
  t7 += v * b3;
  t8 += v * b4;
  t9 += v * b5;
  t10 += v * b6;
  t11 += v * b7;
  t12 += v * b8;
  t13 += v * b9;
  t14 += v * b10;
  t15 += v * b11;
  t16 += v * b12;
  t17 += v * b13;
  t18 += v * b14;
  t19 += v * b15;
  v = a[5];
  t5 += v * b0;
  t6 += v * b1;
  t7 += v * b2;
  t8 += v * b3;
  t9 += v * b4;
  t10 += v * b5;
  t11 += v * b6;
  t12 += v * b7;
  t13 += v * b8;
  t14 += v * b9;
  t15 += v * b10;
  t16 += v * b11;
  t17 += v * b12;
  t18 += v * b13;
  t19 += v * b14;
  t20 += v * b15;
  v = a[6];
  t6 += v * b0;
  t7 += v * b1;
  t8 += v * b2;
  t9 += v * b3;
  t10 += v * b4;
  t11 += v * b5;
  t12 += v * b6;
  t13 += v * b7;
  t14 += v * b8;
  t15 += v * b9;
  t16 += v * b10;
  t17 += v * b11;
  t18 += v * b12;
  t19 += v * b13;
  t20 += v * b14;
  t21 += v * b15;
  v = a[7];
  t7 += v * b0;
  t8 += v * b1;
  t9 += v * b2;
  t10 += v * b3;
  t11 += v * b4;
  t12 += v * b5;
  t13 += v * b6;
  t14 += v * b7;
  t15 += v * b8;
  t16 += v * b9;
  t17 += v * b10;
  t18 += v * b11;
  t19 += v * b12;
  t20 += v * b13;
  t21 += v * b14;
  t22 += v * b15;
  v = a[8];
  t8 += v * b0;
  t9 += v * b1;
  t10 += v * b2;
  t11 += v * b3;
  t12 += v * b4;
  t13 += v * b5;
  t14 += v * b6;
  t15 += v * b7;
  t16 += v * b8;
  t17 += v * b9;
  t18 += v * b10;
  t19 += v * b11;
  t20 += v * b12;
  t21 += v * b13;
  t22 += v * b14;
  t23 += v * b15;
  v = a[9];
  t9 += v * b0;
  t10 += v * b1;
  t11 += v * b2;
  t12 += v * b3;
  t13 += v * b4;
  t14 += v * b5;
  t15 += v * b6;
  t16 += v * b7;
  t17 += v * b8;
  t18 += v * b9;
  t19 += v * b10;
  t20 += v * b11;
  t21 += v * b12;
  t22 += v * b13;
  t23 += v * b14;
  t24 += v * b15;
  v = a[10];
  t10 += v * b0;
  t11 += v * b1;
  t12 += v * b2;
  t13 += v * b3;
  t14 += v * b4;
  t15 += v * b5;
  t16 += v * b6;
  t17 += v * b7;
  t18 += v * b8;
  t19 += v * b9;
  t20 += v * b10;
  t21 += v * b11;
  t22 += v * b12;
  t23 += v * b13;
  t24 += v * b14;
  t25 += v * b15;
  v = a[11];
  t11 += v * b0;
  t12 += v * b1;
  t13 += v * b2;
  t14 += v * b3;
  t15 += v * b4;
  t16 += v * b5;
  t17 += v * b6;
  t18 += v * b7;
  t19 += v * b8;
  t20 += v * b9;
  t21 += v * b10;
  t22 += v * b11;
  t23 += v * b12;
  t24 += v * b13;
  t25 += v * b14;
  t26 += v * b15;
  v = a[12];
  t12 += v * b0;
  t13 += v * b1;
  t14 += v * b2;
  t15 += v * b3;
  t16 += v * b4;
  t17 += v * b5;
  t18 += v * b6;
  t19 += v * b7;
  t20 += v * b8;
  t21 += v * b9;
  t22 += v * b10;
  t23 += v * b11;
  t24 += v * b12;
  t25 += v * b13;
  t26 += v * b14;
  t27 += v * b15;
  v = a[13];
  t13 += v * b0;
  t14 += v * b1;
  t15 += v * b2;
  t16 += v * b3;
  t17 += v * b4;
  t18 += v * b5;
  t19 += v * b6;
  t20 += v * b7;
  t21 += v * b8;
  t22 += v * b9;
  t23 += v * b10;
  t24 += v * b11;
  t25 += v * b12;
  t26 += v * b13;
  t27 += v * b14;
  t28 += v * b15;
  v = a[14];
  t14 += v * b0;
  t15 += v * b1;
  t16 += v * b2;
  t17 += v * b3;
  t18 += v * b4;
  t19 += v * b5;
  t20 += v * b6;
  t21 += v * b7;
  t22 += v * b8;
  t23 += v * b9;
  t24 += v * b10;
  t25 += v * b11;
  t26 += v * b12;
  t27 += v * b13;
  t28 += v * b14;
  t29 += v * b15;
  v = a[15];
  t15 += v * b0;
  t16 += v * b1;
  t17 += v * b2;
  t18 += v * b3;
  t19 += v * b4;
  t20 += v * b5;
  t21 += v * b6;
  t22 += v * b7;
  t23 += v * b8;
  t24 += v * b9;
  t25 += v * b10;
  t26 += v * b11;
  t27 += v * b12;
  t28 += v * b13;
  t29 += v * b14;
  t30 += v * b15;

  t0  += 38 * t16;
  t1  += 38 * t17;
  t2  += 38 * t18;
  t3  += 38 * t19;
  t4  += 38 * t20;
  t5  += 38 * t21;
  t6  += 38 * t22;
  t7  += 38 * t23;
  t8  += 38 * t24;
  t9  += 38 * t25;
  t10 += 38 * t26;
  t11 += 38 * t27;
  t12 += 38 * t28;
  t13 += 38 * t29;
  t14 += 38 * t30;
  // t15 left as is

  // first car
  c = 1;
  v =  t0 + c + 65535; c = Math.floor(v / 65536);  t0 = v - c * 65536;
  v =  t1 + c + 65535; c = Math.floor(v / 65536);  t1 = v - c * 65536;
  v =  t2 + c + 65535; c = Math.floor(v / 65536);  t2 = v - c * 65536;
  v =  t3 + c + 65535; c = Math.floor(v / 65536);  t3 = v - c * 65536;
  v =  t4 + c + 65535; c = Math.floor(v / 65536);  t4 = v - c * 65536;
  v =  t5 + c + 65535; c = Math.floor(v / 65536);  t5 = v - c * 65536;
  v =  t6 + c + 65535; c = Math.floor(v / 65536);  t6 = v - c * 65536;
  v =  t7 + c + 65535; c = Math.floor(v / 65536);  t7 = v - c * 65536;
  v =  t8 + c + 65535; c = Math.floor(v / 65536);  t8 = v - c * 65536;
  v =  t9 + c + 65535; c = Math.floor(v / 65536);  t9 = v - c * 65536;
  v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
  v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
  v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
  v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
  v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
  v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
  t0 += c-1 + 37 * (c-1);

  // second car
  c = 1;
  v =  t0 + c + 65535; c = Math.floor(v / 65536);  t0 = v - c * 65536;
  v =  t1 + c + 65535; c = Math.floor(v / 65536);  t1 = v - c * 65536;
  v =  t2 + c + 65535; c = Math.floor(v / 65536);  t2 = v - c * 65536;
  v =  t3 + c + 65535; c = Math.floor(v / 65536);  t3 = v - c * 65536;
  v =  t4 + c + 65535; c = Math.floor(v / 65536);  t4 = v - c * 65536;
  v =  t5 + c + 65535; c = Math.floor(v / 65536);  t5 = v - c * 65536;
  v =  t6 + c + 65535; c = Math.floor(v / 65536);  t6 = v - c * 65536;
  v =  t7 + c + 65535; c = Math.floor(v / 65536);  t7 = v - c * 65536;
  v =  t8 + c + 65535; c = Math.floor(v / 65536);  t8 = v - c * 65536;
  v =  t9 + c + 65535; c = Math.floor(v / 65536);  t9 = v - c * 65536;
  v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
  v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
  v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
  v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
  v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
  v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
  t0 += c-1 + 37 * (c-1);

  o[ 0] = t0;
  o[ 1] = t1;
  o[ 2] = t2;
  o[ 3] = t3;
  o[ 4] = t4;
  o[ 5] = t5;
  o[ 6] = t6;
  o[ 7] = t7;
  o[ 8] = t8;
  o[ 9] = t9;
  o[10] = t10;
  o[11] = t11;
  o[12] = t12;
  o[13] = t13;
  o[14] = t14;
  o[15] = t15;
}

function S(o, a) {
  M(o, a, a);
}

function inv25519(o, i) {
  var c = gf();
  var a;
  for (a = 0; a < 16; a++) c[a] = i[a];
  for (a = 253; a >= 0; a--) {
    S(c, c);
    if(a !== 2 && a !== 4) M(c, c, i);
  }
  for (a = 0; a < 16; a++) o[a] = c[a];
}

function pow2523(o, i) {
  var c = gf();
  var a;
  for (a = 0; a < 16; a++) c[a] = i[a];
  for (a = 250; a >= 0; a--) {
      S(c, c);
      if(a !== 1) M(c, c, i);
  }
  for (a = 0; a < 16; a++) o[a] = c[a];
}

function crypto_scalarmult(q, n, p) {
  var z = new Uint8Array(32);
  var x = new Float64Array(80), r, i;
  var a = gf(), b = gf(), c = gf(),
      d = gf(), e = gf(), f = gf();
  for (i = 0; i < 31; i++) z[i] = n[i];
  z[31]=(n[31]&127)|64;
  z[0]&=248;
  unpack25519(x,p);
  for (i = 0; i < 16; i++) {
    b[i]=x[i];
    d[i]=a[i]=c[i]=0;
  }
  a[0]=d[0]=1;
  for (i=254; i>=0; --i) {
    r=(z[i>>>3]>>>(i&7))&1;
    sel25519(a,b,r);
    sel25519(c,d,r);
    A(e,a,c);
    Z(a,a,c);
    A(c,b,d);
    Z(b,b,d);
    S(d,e);
    S(f,a);
    M(a,c,a);
    M(c,b,e);
    A(e,a,c);
    Z(a,a,c);
    S(b,a);
    Z(c,d,f);
    M(a,c,_121665);
    A(a,a,d);
    M(c,c,a);
    M(a,d,f);
    M(d,b,x);
    S(b,e);
    sel25519(a,b,r);
    sel25519(c,d,r);
  }
  for (i = 0; i < 16; i++) {
    x[i+16]=a[i];
    x[i+32]=c[i];
    x[i+48]=b[i];
    x[i+64]=d[i];
  }
  var x32 = x.subarray(32);
  var x16 = x.subarray(16);
  inv25519(x32,x32);
  M(x16,x16,x32);
  pack25519(q,x16);
  return 0;
}

function crypto_scalarmult_base(q, n) {
  return crypto_scalarmult(q, n, _9);
}

function crypto_box_keypair(y, x) {
  randombytes(x, 32);
  return crypto_scalarmult_base(y, x);
}

var K = [
  0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
  0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
  0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
  0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
  0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
  0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
  0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
  0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
  0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
  0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
  0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
  0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
  0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
  0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
  0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
  0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
  0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
  0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
  0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
  0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
  0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
  0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
  0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
  0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
  0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
  0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
  0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
  0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
  0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
  0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
  0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
  0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
  0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
  0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
  0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
  0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
  0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
  0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
  0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
  0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
];

function crypto_hashblocks_hl(hh, hl, m, n) {
  var wh = new Int32Array(16), wl = new Int32Array(16),
      bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,
      bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,
      th, tl, i, j, h, l, a, b, c, d;

  var ah0 = hh[0],
      ah1 = hh[1],
      ah2 = hh[2],
      ah3 = hh[3],
      ah4 = hh[4],
      ah5 = hh[5],
      ah6 = hh[6],
      ah7 = hh[7],

      al0 = hl[0],
      al1 = hl[1],
      al2 = hl[2],
      al3 = hl[3],
      al4 = hl[4],
      al5 = hl[5],
      al6 = hl[6],
      al7 = hl[7];

  var pos = 0;
  while (n >= 128) {
    for (i = 0; i < 16; i++) {
      j = 8 * i + pos;
      wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];
      wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];
    }
    for (i = 0; i < 80; i++) {
      bh0 = ah0;
      bh1 = ah1;
      bh2 = ah2;
      bh3 = ah3;
      bh4 = ah4;
      bh5 = ah5;
      bh6 = ah6;
      bh7 = ah7;

      bl0 = al0;
      bl1 = al1;
      bl2 = al2;
      bl3 = al3;
      bl4 = al4;
      bl5 = al5;
      bl6 = al6;
      bl7 = al7;

      // add
      h = ah7;
      l = al7;

      a = l & 0xffff; b = l >>> 16;
      c = h & 0xffff; d = h >>> 16;

      // Sigma1
      h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));
      l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));

      a += l & 0xffff; b += l >>> 16;
      c += h & 0xffff; d += h >>> 16;

      // Ch
      h = (ah4 & ah5) ^ (~ah4 & ah6);
      l = (al4 & al5) ^ (~al4 & al6);

      a += l & 0xffff; b += l >>> 16;
      c += h & 0xffff; d += h >>> 16;

      // K
      h = K[i*2];
      l = K[i*2+1];

      a += l & 0xffff; b += l >>> 16;
      c += h & 0xffff; d += h >>> 16;

      // w
      h = wh[i%16];
      l = wl[i%16];

      a += l & 0xffff; b += l >>> 16;
      c += h & 0xffff; d += h >>> 16;

      b += a >>> 16;
      c += b >>> 16;
      d += c >>> 16;

      th = c & 0xffff | d << 16;
      tl = a & 0xffff | b << 16;

      // add
      h = th;
      l = tl;

      a = l & 0xffff; b = l >>> 16;
      c = h & 0xffff; d = h >>> 16;

      // Sigma0
      h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));
      l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));

      a += l & 0xffff; b += l >>> 16;
      c += h & 0xffff; d += h >>> 16;

      // Maj
      h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);
      l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);

      a += l & 0xffff; b += l >>> 16;
      c += h & 0xffff; d += h >>> 16;

      b += a >>> 16;
      c += b >>> 16;
      d += c >>> 16;

      bh7 = (c & 0xffff) | (d << 16);
      bl7 = (a & 0xffff) | (b << 16);

      // add
      h = bh3;
      l = bl3;

      a = l & 0xffff; b = l >>> 16;
      c = h & 0xffff; d = h >>> 16;

      h = th;
      l = tl;

      a += l & 0xffff; b += l >>> 16;
      c += h & 0xffff; d += h >>> 16;

      b += a >>> 16;
      c += b >>> 16;
      d += c >>> 16;

      bh3 = (c & 0xffff) | (d << 16);
      bl3 = (a & 0xffff) | (b << 16);

      ah1 = bh0;
      ah2 = bh1;
      ah3 = bh2;
      ah4 = bh3;
      ah5 = bh4;
      ah6 = bh5;
      ah7 = bh6;
      ah0 = bh7;

      al1 = bl0;
      al2 = bl1;
      al3 = bl2;
      al4 = bl3;
      al5 = bl4;
      al6 = bl5;
      al7 = bl6;
      al0 = bl7;

      if (i%16 === 15) {
        for (j = 0; j < 16; j++) {
          // add
          h = wh[j];
          l = wl[j];

          a = l & 0xffff; b = l >>> 16;
          c = h & 0xffff; d = h >>> 16;

          h = wh[(j+9)%16];
          l = wl[(j+9)%16];

          a += l & 0xffff; b += l >>> 16;
          c += h & 0xffff; d += h >>> 16;

          // sigma0
          th = wh[(j+1)%16];
          tl = wl[(j+1)%16];
          h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);
          l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));

          a += l & 0xffff; b += l >>> 16;
          c += h & 0xffff; d += h >>> 16;

          // sigma1
          th = wh[(j+14)%16];
          tl = wl[(j+14)%16];
          h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);
          l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));

          a += l & 0xffff; b += l >>> 16;
          c += h & 0xffff; d += h >>> 16;

          b += a >>> 16;
          c += b >>> 16;
          d += c >>> 16;

          wh[j] = (c & 0xffff) | (d << 16);
          wl[j] = (a & 0xffff) | (b << 16);
        }
      }
    }

    // add
    h = ah0;
    l = al0;

    a = l & 0xffff; b = l >>> 16;
    c = h & 0xffff; d = h >>> 16;

    h = hh[0];
    l = hl[0];

    a += l & 0xffff; b += l >>> 16;
    c += h & 0xffff; d += h >>> 16;

    b += a >>> 16;
    c += b >>> 16;
    d += c >>> 16;

    hh[0] = ah0 = (c & 0xffff) | (d << 16);
    hl[0] = al0 = (a & 0xffff) | (b << 16);

    h = ah1;
    l = al1;

    a = l & 0xffff; b = l >>> 16;
    c = h & 0xffff; d = h >>> 16;

    h = hh[1];
    l = hl[1];

    a += l & 0xffff; b += l >>> 16;
    c += h & 0xffff; d += h >>> 16;

    b += a >>> 16;
    c += b >>> 16;
    d += c >>> 16;

    hh[1] = ah1 = (c & 0xffff) | (d << 16);
    hl[1] = al1 = (a & 0xffff) | (b << 16);

    h = ah2;
    l = al2;

    a = l & 0xffff; b = l >>> 16;
    c = h & 0xffff; d = h >>> 16;

    h = hh[2];
    l = hl[2];

    a += l & 0xffff; b += l >>> 16;
    c += h & 0xffff; d += h >>> 16;

    b += a >>> 16;
    c += b >>> 16;
    d += c >>> 16;

    hh[2] = ah2 = (c & 0xffff) | (d << 16);
    hl[2] = al2 = (a & 0xffff) | (b << 16);

    h = ah3;
    l = al3;

    a = l & 0xffff; b = l >>> 16;
    c = h & 0xffff; d = h >>> 16;

    h = hh[3];
    l = hl[3];

    a += l & 0xffff; b += l >>> 16;
    c += h & 0xffff; d += h >>> 16;

    b += a >>> 16;
    c += b >>> 16;
    d += c >>> 16;

    hh[3] = ah3 = (c & 0xffff) | (d << 16);
    hl[3] = al3 = (a & 0xffff) | (b << 16);

    h = ah4;
    l = al4;

    a = l & 0xffff; b = l >>> 16;
    c = h & 0xffff; d = h >>> 16;

    h = hh[4];
    l = hl[4];

    a += l & 0xffff; b += l >>> 16;
    c += h & 0xffff; d += h >>> 16;

    b += a >>> 16;
    c += b >>> 16;
    d += c >>> 16;

    hh[4] = ah4 = (c & 0xffff) | (d << 16);
    hl[4] = al4 = (a & 0xffff) | (b << 16);

    h = ah5;
    l = al5;

    a = l & 0xffff; b = l >>> 16;
    c = h & 0xffff; d = h >>> 16;

    h = hh[5];
    l = hl[5];

    a += l & 0xffff; b += l >>> 16;
    c += h & 0xffff; d += h >>> 16;

    b += a >>> 16;
    c += b >>> 16;
    d += c >>> 16;

    hh[5] = ah5 = (c & 0xffff) | (d << 16);
    hl[5] = al5 = (a & 0xffff) | (b << 16);

    h = ah6;
    l = al6;

    a = l & 0xffff; b = l >>> 16;
    c = h & 0xffff; d = h >>> 16;

    h = hh[6];
    l = hl[6];

    a += l & 0xffff; b += l >>> 16;
    c += h & 0xffff; d += h >>> 16;

    b += a >>> 16;
    c += b >>> 16;
    d += c >>> 16;

    hh[6] = ah6 = (c & 0xffff) | (d << 16);
    hl[6] = al6 = (a & 0xffff) | (b << 16);

    h = ah7;
    l = al7;

    a = l & 0xffff; b = l >>> 16;
    c = h & 0xffff; d = h >>> 16;

    h = hh[7];
    l = hl[7];

    a += l & 0xffff; b += l >>> 16;
    c += h & 0xffff; d += h >>> 16;

    b += a >>> 16;
    c += b >>> 16;
    d += c >>> 16;

    hh[7] = ah7 = (c & 0xffff) | (d << 16);
    hl[7] = al7 = (a & 0xffff) | (b << 16);

    pos += 128;
    n -= 128;
  }

  return n;
}

function crypto_hash(out, m, n) {
  var hh = new Int32Array(8),
      hl = new Int32Array(8),
      x = new Uint8Array(256),
      i, b = n;

  hh[0] = 0x6a09e667;
  hh[1] = 0xbb67ae85;
  hh[2] = 0x3c6ef372;
  hh[3] = 0xa54ff53a;
  hh[4] = 0x510e527f;
  hh[5] = 0x9b05688c;
  hh[6] = 0x1f83d9ab;
  hh[7] = 0x5be0cd19;

  hl[0] = 0xf3bcc908;
  hl[1] = 0x84caa73b;
  hl[2] = 0xfe94f82b;
  hl[3] = 0x5f1d36f1;
  hl[4] = 0xade682d1;
  hl[5] = 0x2b3e6c1f;
  hl[6] = 0xfb41bd6b;
  hl[7] = 0x137e2179;

  crypto_hashblocks_hl(hh, hl, m, n);
  n %= 128;

  for (i = 0; i < n; i++) x[i] = m[b-n+i];
  x[n] = 128;

  n = 256-128*(n<112?1:0);
  x[n-9] = 0;
  ts64(x, n-8,  (b / 0x20000000) | 0, b << 3);
  crypto_hashblocks_hl(hh, hl, x, n);

  for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);

  return 0;
}

function add(p, q) {
  var a = gf(), b = gf(), c = gf(),
      d = gf(), e = gf(), f = gf(),
      g = gf(), h = gf(), t = gf();

  Z(a, p[1], p[0]);
  Z(t, q[1], q[0]);
  M(a, a, t);
  A(b, p[0], p[1]);
  A(t, q[0], q[1]);
  M(b, b, t);
  M(c, p[3], q[3]);
  M(c, c, D2);
  M(d, p[2], q[2]);
  A(d, d, d);
  Z(e, b, a);
  Z(f, d, c);
  A(g, d, c);
  A(h, b, a);

  M(p[0], e, f);
  M(p[1], h, g);
  M(p[2], g, f);
  M(p[3], e, h);
}

function cswap(p, q, b) {
  var i;
  for (i = 0; i < 4; i++) {
    sel25519(p[i], q[i], b);
  }
}

function pack(r, p) {
  var tx = gf(), ty = gf(), zi = gf();
  inv25519(zi, p[2]);
  M(tx, p[0], zi);
  M(ty, p[1], zi);
  pack25519(r, ty);
  r[31] ^= par25519(tx) << 7;
}

function scalarmult(p, q, s) {
  var b, i;
  set25519(p[0], gf0);
  set25519(p[1], gf1);
  set25519(p[2], gf1);
  set25519(p[3], gf0);
  for (i = 255; i >= 0; --i) {
    b = (s[(i/8)|0] >> (i&7)) & 1;
    cswap(p, q, b);
    add(q, p);
    add(p, p);
    cswap(p, q, b);
  }
}

function scalarbase(p, s) {
  var q = [gf(), gf(), gf(), gf()];
  set25519(q[0], X);
  set25519(q[1], Y);
  set25519(q[2], gf1);
  M(q[3], X, Y);
  scalarmult(p, q, s);
}

function crypto_sign_keypair(pk, sk, seeded) {
  var d = new Uint8Array(64);
  var p = [gf(), gf(), gf(), gf()];
  var i;

  if (!seeded) randombytes(sk, 32);
  crypto_hash(d, sk, 32);
  d[0] &= 248;
  d[31] &= 127;
  d[31] |= 64;

  scalarbase(p, d);
  pack(pk, p);

  for (i = 0; i < 32; i++) sk[i+32] = pk[i];
  return 0;
}

var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);

function modL(r, x) {
  var carry, i, j, k;
  for (i = 63; i >= 32; --i) {
    carry = 0;
    for (j = i - 32, k = i - 12; j < k; ++j) {
      x[j] += carry - 16 * x[i] * L[j - (i - 32)];
      carry = Math.floor((x[j] + 128) / 256);
      x[j] -= carry * 256;
    }
    x[j] += carry;
    x[i] = 0;
  }
  carry = 0;
  for (j = 0; j < 32; j++) {
    x[j] += carry - (x[31] >> 4) * L[j];
    carry = x[j] >> 8;
    x[j] &= 255;
  }
  for (j = 0; j < 32; j++) x[j] -= carry * L[j];
  for (i = 0; i < 32; i++) {
    x[i+1] += x[i] >> 8;
    r[i] = x[i] & 255;
  }
}

function reduce(r) {
  var x = new Float64Array(64), i;
  for (i = 0; i < 64; i++) x[i] = r[i];
  for (i = 0; i < 64; i++) r[i] = 0;
  modL(r, x);
}

// Note: difference from C - smlen returned, not passed as argument.
function crypto_sign(sm, m, n, sk) {
  var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);
  var i, j, x = new Float64Array(64);
  var p = [gf(), gf(), gf(), gf()];

  crypto_hash(d, sk, 32);
  d[0] &= 248;
  d[31] &= 127;
  d[31] |= 64;

  var smlen = n + 64;
  for (i = 0; i < n; i++) sm[64 + i] = m[i];
  for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];

  crypto_hash(r, sm.subarray(32), n+32);
  reduce(r);
  scalarbase(p, r);
  pack(sm, p);

  for (i = 32; i < 64; i++) sm[i] = sk[i];
  crypto_hash(h, sm, n + 64);
  reduce(h);

  for (i = 0; i < 64; i++) x[i] = 0;
  for (i = 0; i < 32; i++) x[i] = r[i];
  for (i = 0; i < 32; i++) {
    for (j = 0; j < 32; j++) {
      x[i+j] += h[i] * d[j];
    }
  }

  modL(sm.subarray(32), x);
  return smlen;
}

function unpackneg(r, p) {
  var t = gf(), chk = gf(), num = gf(),
      den = gf(), den2 = gf(), den4 = gf(),
      den6 = gf();

  set25519(r[2], gf1);
  unpack25519(r[1], p);
  S(num, r[1]);
  M(den, num, D);
  Z(num, num, r[2]);
  A(den, r[2], den);

  S(den2, den);
  S(den4, den2);
  M(den6, den4, den2);
  M(t, den6, num);
  M(t, t, den);

  pow2523(t, t);
  M(t, t, num);
  M(t, t, den);
  M(t, t, den);
  M(r[0], t, den);

  S(chk, r[0]);
  M(chk, chk, den);
  if (neq25519(chk, num)) M(r[0], r[0], I);

  S(chk, r[0]);
  M(chk, chk, den);
  if (neq25519(chk, num)) return -1;

  if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);

  M(r[3], r[0], r[1]);
  return 0;
}

function crypto_sign_open(m, sm, n, pk) {
  var i;
  var t = new Uint8Array(32), h = new Uint8Array(64);
  var p = [gf(), gf(), gf(), gf()],
      q = [gf(), gf(), gf(), gf()];

  if (n < 64) return -1;

  if (unpackneg(q, pk)) return -1;

  for (i = 0; i < n; i++) m[i] = sm[i];
  for (i = 0; i < 32; i++) m[i+32] = pk[i];
  crypto_hash(h, m, n);
  reduce(h);
  scalarmult(p, q, h);

  scalarbase(q, sm.subarray(32));
  add(p, q);
  pack(t, p);

  n -= 64;
  if (crypto_verify_32(sm, 0, t, 0)) {
    for (i = 0; i < n; i++) m[i] = 0;
    return -1;
  }

  for (i = 0; i < n; i++) m[i] = sm[i + 64];
  return n;
}

var crypto_scalarmult_BYTES = 32,
    crypto_scalarmult_SCALARBYTES = 32,
    crypto_box_PUBLICKEYBYTES = 32,
    crypto_box_SECRETKEYBYTES = 32,
    crypto_sign_BYTES = 64,
    crypto_sign_PUBLICKEYBYTES = 32,
    crypto_sign_SECRETKEYBYTES = 64,
    crypto_sign_SEEDBYTES = 32;

function checkArrayTypes() {
  for (var i = 0; i < arguments.length; i++) {
    if (!(arguments[i] instanceof Uint8Array))
      throw new TypeError('unexpected type, use Uint8Array');
  }
}

function cleanup(arr) {
  for (var i = 0; i < arr.length; i++) arr[i] = 0;
}

nacl.scalarMult = function(n, p) {
  checkArrayTypes(n, p);
  if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
  if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
  var q = new Uint8Array(crypto_scalarmult_BYTES);
  crypto_scalarmult(q, n, p);
  return q;
};

nacl.box = {};

nacl.box.keyPair = function() {
  var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
  var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
  crypto_box_keypair(pk, sk);
  return {publicKey: pk, secretKey: sk};
};

nacl.box.keyPair.fromSecretKey = function(secretKey) {
  checkArrayTypes(secretKey);
  if (secretKey.length !== crypto_box_SECRETKEYBYTES)
    throw new Error('bad secret key size');
  var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
  crypto_scalarmult_base(pk, secretKey);
  return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
};

nacl.sign = function(msg, secretKey) {
  checkArrayTypes(msg, secretKey);
  if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
    throw new Error('bad secret key size');
  var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
  crypto_sign(signedMsg, msg, msg.length, secretKey);
  return signedMsg;
};

nacl.sign.detached = function(msg, secretKey) {
  var signedMsg = nacl.sign(msg, secretKey);
  var sig = new Uint8Array(crypto_sign_BYTES);
  for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
  return sig;
};

nacl.sign.detached.verify = function(msg, sig, publicKey) {
  checkArrayTypes(msg, sig, publicKey);
  if (sig.length !== crypto_sign_BYTES)
    throw new Error('bad signature size');
  if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
    throw new Error('bad public key size');
  var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
  var m = new Uint8Array(crypto_sign_BYTES + msg.length);
  var i;
  for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
  for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
  return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
};

nacl.sign.keyPair = function() {
  var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
  var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
  crypto_sign_keypair(pk, sk);
  return {publicKey: pk, secretKey: sk};
};

nacl.sign.keyPair.fromSecretKey = function(secretKey) {
  checkArrayTypes(secretKey);
  if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
    throw new Error('bad secret key size');
  var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
  for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
  return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
};

nacl.sign.keyPair.fromSeed = function(seed) {
  checkArrayTypes(seed);
  if (seed.length !== crypto_sign_SEEDBYTES)
    throw new Error('bad seed size');
  var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
  var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
  for (var i = 0; i < 32; i++) sk[i] = seed[i];
  crypto_sign_keypair(pk, sk, true);
  return {publicKey: pk, secretKey: sk};
};

nacl.setPRNG = function(fn) {
  randombytes = fn;
};

(function() {
  // Initialize PRNG if environment provides CSPRNG.
  // If not, methods calling randombytes will throw.
  if (crypto$1 && crypto$1.getRandomValues) {
    // Browsers and Node v16+
    var QUOTA = 65536;
    nacl.setPRNG(function(x, n) {
      var i, v = new Uint8Array(n);
      for (i = 0; i < n; i += QUOTA) {
        crypto$1.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
      }
      for (i = 0; i < n; i++) x[i] = v[i];
      cleanup(v);
    });
  }
})();

var naclFast = /*#__PURE__*/Object.freeze({
  __proto__: null,
  default: nacl
});

/** @access private */
//Paul Tero, July 2001
//http://www.tero.co.uk/des/
//
//Optimised for performance with large blocks by Michael Hayworth, November 2001
//http://www.netdealing.com
//
// Modified by Recurity Labs GmbH
//THIS SOFTWARE IS PROVIDED "AS IS" AND
//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
//ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
//SUCH DAMAGE.
//des
//this takes the key, the message, and whether to encrypt or decrypt
function des(keys, message, encrypt, mode, iv, padding) {
    //declaring this locally speeds things up a bit
    const spfunction1 = [
        0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,
        0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,
        0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,
        0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,
        0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,
        0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004
    ];
    const spfunction2 = [
        -2146402272, -2147450880, 0x8000, 0x108020, 0x100000, 0x20, -2146435040, -2147450848,
        -2147483616, -2146402272, -2146402304, -2147483648, -2147450880, 0x100000, 0x20, -2146435040, 0x108000, 0x100020,
        -2147450848, 0, -2147483648, 0x8000, 0x108020, -2146435072, 0x100020, -2147483616, 0, 0x108000, 0x8020, -2146402304,
        -2146435072, 0x8020, 0, 0x108020, -2146435040, 0x100000, -2147450848, -2146435072, -2146402304, 0x8000, -2146435072,
        -2147450880, 0x20, -2146402272, 0x108020, 0x20, 0x8000, -2147483648, 0x8020, -2146402304, 0x100000, -2147483616,
        0x100020, -2147450848, -2147483616, 0x100020, 0x108000, 0, -2147450880, 0x8020, -2147483648, -2146435040,
        -2146402272, 0x108000
    ];
    const spfunction3 = [
        0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,
        0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,
        0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,
        0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,
        0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,
        0x8020000, 0x20208, 0x8, 0x8020008, 0x20200
    ];
    const spfunction4 = [
        0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,
        0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,
        0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,
        0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,
        0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080
    ];
    const spfunction5 = [
        0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,
        0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,
        0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,
        0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,
        0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,
        0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,
        0x40080000, 0x2080100, 0x40000100
    ];
    const spfunction6 = [
        0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,
        0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,
        0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,
        0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,
        0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,
        0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010
    ];
    const spfunction7 = [
        0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,
        0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,
        0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,
        0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,
        0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,
        0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002
    ];
    const spfunction8 = [
        0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,
        0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,
        0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,
        0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,
        0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,
        0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000
    ];
    //create the 16 or 48 subkeys we will need
    let m = 0;
    let i;
    let j;
    let temp;
    let right1;
    let right2;
    let left;
    let right;
    let looping;
    let endloop;
    let loopinc;
    let len = message.length;
    //set up the loops for single and triple des
    const iterations = keys.length === 32 ? 3 : 9; //single or triple des
    if (iterations === 3) {
        looping = encrypt ? [0, 32, 2] : [30, -2, -2];
    }
    else {
        looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];
    }
    //pad the message depending on the padding parameter
    //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt
    if (encrypt) {
        message = desAddPadding(message);
        len = message.length;
    }
    //store the result here
    let result = new Uint8Array(len);
    let k = 0;
    //loop through each 64 bit chunk of the message
    while (m < len) {
        left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];
        right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];
        //first each 64 but chunk of the message must be permuted according to IP
        temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
        right ^= temp;
        left ^= (temp << 4);
        temp = ((left >>> 16) ^ right) & 0x0000ffff;
        right ^= temp;
        left ^= (temp << 16);
        temp = ((right >>> 2) ^ left) & 0x33333333;
        left ^= temp;
        right ^= (temp << 2);
        temp = ((right >>> 8) ^ left) & 0x00ff00ff;
        left ^= temp;
        right ^= (temp << 8);
        temp = ((left >>> 1) ^ right) & 0x55555555;
        right ^= temp;
        left ^= (temp << 1);
        left = ((left << 1) | (left >>> 31));
        right = ((right << 1) | (right >>> 31));
        //do this either 1 or 3 times for each chunk of the message
        for (j = 0; j < iterations; j += 3) {
            endloop = looping[j + 1];
            loopinc = looping[j + 2];
            //now go through and perform the encryption or decryption
            for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency
                right1 = right ^ keys[i];
                right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];
                //the result is attained by passing these bytes through the S selection functions
                temp = left;
                left = right;
                right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>
                    8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &
                    0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);
            }
            temp = left;
            left = right;
            right = temp; //unreverse left and right
        } //for either 1 or 3 iterations
        //move then each one bit to the right
        left = ((left >>> 1) | (left << 31));
        right = ((right >>> 1) | (right << 31));
        //now perform IP-1, which is IP in the opposite direction
        temp = ((left >>> 1) ^ right) & 0x55555555;
        right ^= temp;
        left ^= (temp << 1);
        temp = ((right >>> 8) ^ left) & 0x00ff00ff;
        left ^= temp;
        right ^= (temp << 8);
        temp = ((right >>> 2) ^ left) & 0x33333333;
        left ^= temp;
        right ^= (temp << 2);
        temp = ((left >>> 16) ^ right) & 0x0000ffff;
        right ^= temp;
        left ^= (temp << 16);
        temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
        right ^= temp;
        left ^= (temp << 4);
        result[k++] = (left >>> 24);
        result[k++] = ((left >>> 16) & 0xff);
        result[k++] = ((left >>> 8) & 0xff);
        result[k++] = (left & 0xff);
        result[k++] = (right >>> 24);
        result[k++] = ((right >>> 16) & 0xff);
        result[k++] = ((right >>> 8) & 0xff);
        result[k++] = (right & 0xff);
    } //for every 8 characters, or 64 bits in the message
    //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt
    if (!encrypt) {
        result = desRemovePadding(result);
    }
    return result;
} //end of des
//desCreateKeys
//this takes as input a 64 bit key (even though only 56 bits are used)
//as an array of 2 integers, and returns 16 48 bit keys
function desCreateKeys(key) {
    //declaring this locally speeds things up a bit
    const pc2bytes0 = [
        0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,
        0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204
    ];
    const pc2bytes1 = [
        0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,
        0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101
    ];
    const pc2bytes2 = [
        0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,
        0x1000000, 0x1000008, 0x1000800, 0x1000808
    ];
    const pc2bytes3 = [
        0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,
        0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000
    ];
    const pc2bytes4 = [
        0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,
        0x41000, 0x1010, 0x41010
    ];
    const pc2bytes5 = [
        0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,
        0x2000000, 0x2000400, 0x2000020, 0x2000420
    ];
    const pc2bytes6 = [
        0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,
        0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002
    ];
    const pc2bytes7 = [
        0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,
        0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800
    ];
    const pc2bytes8 = [
        0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,
        0x2000002, 0x2040002, 0x2000002, 0x2040002
    ];
    const pc2bytes9 = [
        0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,
        0x10000408, 0x400, 0x10000400, 0x408, 0x10000408
    ];
    const pc2bytes10 = [
        0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,
        0x102000, 0x102020, 0x102000, 0x102020
    ];
    const pc2bytes11 = [
        0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,
        0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200
    ];
    const pc2bytes12 = [
        0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,
        0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010
    ];
    const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];
    //how many iterations (1 for des, 3 for triple des)
    const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys
    //stores the return keys
    const keys = new Array(32 * iterations);
    //now define the left shifts which need to be done
    const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];
    //other variables
    let lefttemp;
    let righttemp;
    let m = 0;
    let n = 0;
    let temp;
    for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations
        let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];
        let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];
        temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
        right ^= temp;
        left ^= (temp << 4);
        temp = ((right >>> -16) ^ left) & 0x0000ffff;
        left ^= temp;
        right ^= (temp << -16);
        temp = ((left >>> 2) ^ right) & 0x33333333;
        right ^= temp;
        left ^= (temp << 2);
        temp = ((right >>> -16) ^ left) & 0x0000ffff;
        left ^= temp;
        right ^= (temp << -16);
        temp = ((left >>> 1) ^ right) & 0x55555555;
        right ^= temp;
        left ^= (temp << 1);
        temp = ((right >>> 8) ^ left) & 0x00ff00ff;
        left ^= temp;
        right ^= (temp << 8);
        temp = ((left >>> 1) ^ right) & 0x55555555;
        right ^= temp;
        left ^= (temp << 1);
        //the right side needs to be shifted and to get the last four bits of the left side
        temp = (left << 8) | ((right >>> 20) & 0x000000f0);
        //left needs to be put upside down
        left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);
        right = temp;
        //now go through and perform these shifts on the left and right keys
        for (let i = 0; i < shifts.length; i++) {
            //shift the keys either one or two bits to the left
            if (shifts[i]) {
                left = (left << 2) | (left >>> 26);
                right = (right << 2) | (right >>> 26);
            }
            else {
                left = (left << 1) | (left >>> 27);
                right = (right << 1) | (right >>> 27);
            }
            left &= -15;
            right &= -15;
            //now apply PC-2, in such a way that E is easier when encrypting or decrypting
            //this conversion will look like PC-2 except only the last 6 bits of each byte are used
            //rather than 48 consecutive bits and the order of lines will be according to
            //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7
            lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &
                0xf];
            righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |
                pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |
                pc2bytes13[(right >>> 4) & 0xf];
            temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;
            keys[n++] = lefttemp ^ temp;
            keys[n++] = righttemp ^ (temp << 16);
        }
    } //for each iterations
    //return the keys we've created
    return keys;
} //end of desCreateKeys
function desAddPadding(message, padding) {
    const padLength = 8 - (message.length % 8);
    let pad;
    if ((padLength < 8)) { //pad the message out with null bytes
        pad = 0;
    }
    else if (padLength === 8) {
        return message;
    }
    else {
        throw new Error('des: invalid padding');
    }
    const paddedMessage = new Uint8Array(message.length + padLength);
    for (let i = 0; i < message.length; i++) {
        paddedMessage[i] = message[i];
    }
    for (let j = 0; j < padLength; j++) {
        paddedMessage[message.length + j] = pad;
    }
    return paddedMessage;
}
function desRemovePadding(message, padding) {
    let padLength = null;
    let pad;
    { // null padding
        pad = 0;
    }
    if (!padLength) {
        padLength = 1;
        while (message[message.length - padLength] === pad) {
            padLength++;
        }
        padLength--;
    }
    return message.subarray(0, message.length - padLength);
}
// added by Recurity Labs
function TripleDES(key) {
    this.key = [];
    for (let i = 0; i < 3; i++) {
        this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));
    }
    this.encrypt = function (block) {
        return des(desCreateKeys(this.key[2]), des(desCreateKeys(this.key[1]), des(desCreateKeys(this.key[0]), block, true, 0, null, null), false, 0, null, null), true);
    };
}
TripleDES.keySize = TripleDES.prototype.keySize = 24;
TripleDES.blockSize = TripleDES.prototype.blockSize = 8;

/** @access private */
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright 2010 pjacobs@xeekr.com . All rights reserved.
// Modified by Recurity Labs GmbH
// fixed/modified by Herbert Hanewinkel, www.haneWIN.de
// check www.haneWIN.de for the latest version
// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.
// CAST-128 is a common OpenPGP cipher.
// CAST5 constructor
function OpenPGPSymEncCAST5() {
    this.BlockSize = 8;
    this.KeySize = 16;
    this.setKey = function (key) {
        this.masking = new Array(16);
        this.rotate = new Array(16);
        this.reset();
        if (key.length === this.KeySize) {
            this.keySchedule(key);
        }
        else {
            throw new Error('CAST-128: keys must be 16 bytes');
        }
        return true;
    };
    this.reset = function () {
        for (let i = 0; i < 16; i++) {
            this.masking[i] = 0;
            this.rotate[i] = 0;
        }
    };
    this.getBlockSize = function () {
        return this.BlockSize;
    };
    this.encrypt = function (src) {
        const dst = new Array(src.length);
        for (let i = 0; i < src.length; i += 8) {
            let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];
            let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];
            let t;
            t = r;
            r = l ^ f1(r, this.masking[0], this.rotate[0]);
            l = t;
            t = r;
            r = l ^ f2(r, this.masking[1], this.rotate[1]);
            l = t;
            t = r;
            r = l ^ f3(r, this.masking[2], this.rotate[2]);
            l = t;
            t = r;
            r = l ^ f1(r, this.masking[3], this.rotate[3]);
            l = t;
            t = r;
            r = l ^ f2(r, this.masking[4], this.rotate[4]);
            l = t;
            t = r;
            r = l ^ f3(r, this.masking[5], this.rotate[5]);
            l = t;
            t = r;
            r = l ^ f1(r, this.masking[6], this.rotate[6]);
            l = t;
            t = r;
            r = l ^ f2(r, this.masking[7], this.rotate[7]);
            l = t;
            t = r;
            r = l ^ f3(r, this.masking[8], this.rotate[8]);
            l = t;
            t = r;
            r = l ^ f1(r, this.masking[9], this.rotate[9]);
            l = t;
            t = r;
            r = l ^ f2(r, this.masking[10], this.rotate[10]);
            l = t;
            t = r;
            r = l ^ f3(r, this.masking[11], this.rotate[11]);
            l = t;
            t = r;
            r = l ^ f1(r, this.masking[12], this.rotate[12]);
            l = t;
            t = r;
            r = l ^ f2(r, this.masking[13], this.rotate[13]);
            l = t;
            t = r;
            r = l ^ f3(r, this.masking[14], this.rotate[14]);
            l = t;
            t = r;
            r = l ^ f1(r, this.masking[15], this.rotate[15]);
            l = t;
            dst[i] = (r >>> 24) & 255;
            dst[i + 1] = (r >>> 16) & 255;
            dst[i + 2] = (r >>> 8) & 255;
            dst[i + 3] = r & 255;
            dst[i + 4] = (l >>> 24) & 255;
            dst[i + 5] = (l >>> 16) & 255;
            dst[i + 6] = (l >>> 8) & 255;
            dst[i + 7] = l & 255;
        }
        return dst;
    };
    this.decrypt = function (src) {
        const dst = new Array(src.length);
        for (let i = 0; i < src.length; i += 8) {
            let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];
            let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];
            let t;
            t = r;
            r = l ^ f1(r, this.masking[15], this.rotate[15]);
            l = t;
            t = r;
            r = l ^ f3(r, this.masking[14], this.rotate[14]);
            l = t;
            t = r;
            r = l ^ f2(r, this.masking[13], this.rotate[13]);
            l = t;
            t = r;
            r = l ^ f1(r, this.masking[12], this.rotate[12]);
            l = t;
            t = r;
            r = l ^ f3(r, this.masking[11], this.rotate[11]);
            l = t;
            t = r;
            r = l ^ f2(r, this.masking[10], this.rotate[10]);
            l = t;
            t = r;
            r = l ^ f1(r, this.masking[9], this.rotate[9]);
            l = t;
            t = r;
            r = l ^ f3(r, this.masking[8], this.rotate[8]);
            l = t;
            t = r;
            r = l ^ f2(r, this.masking[7], this.rotate[7]);
            l = t;
            t = r;
            r = l ^ f1(r, this.masking[6], this.rotate[6]);
            l = t;
            t = r;
            r = l ^ f3(r, this.masking[5], this.rotate[5]);
            l = t;
            t = r;
            r = l ^ f2(r, this.masking[4], this.rotate[4]);
            l = t;
            t = r;
            r = l ^ f1(r, this.masking[3], this.rotate[3]);
            l = t;
            t = r;
            r = l ^ f3(r, this.masking[2], this.rotate[2]);
            l = t;
            t = r;
            r = l ^ f2(r, this.masking[1], this.rotate[1]);
            l = t;
            t = r;
            r = l ^ f1(r, this.masking[0], this.rotate[0]);
            l = t;
            dst[i] = (r >>> 24) & 255;
            dst[i + 1] = (r >>> 16) & 255;
            dst[i + 2] = (r >>> 8) & 255;
            dst[i + 3] = r & 255;
            dst[i + 4] = (l >>> 24) & 255;
            dst[i + 5] = (l >> 16) & 255;
            dst[i + 6] = (l >> 8) & 255;
            dst[i + 7] = l & 255;
        }
        return dst;
    };
    const scheduleA = new Array(4);
    scheduleA[0] = new Array(4);
    scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];
    scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
    scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
    scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
    scheduleA[1] = new Array(4);
    scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
    scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
    scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
    scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
    scheduleA[2] = new Array(4);
    scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];
    scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
    scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
    scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
    scheduleA[3] = new Array(4);
    scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
    scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
    scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
    scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
    const scheduleB = new Array(4);
    scheduleB[0] = new Array(4);
    scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];
    scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];
    scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];
    scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];
    scheduleB[1] = new Array(4);
    scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];
    scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];
    scheduleB[1][2] = [7, 6, 8, 9, 3];
    scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];
    scheduleB[2] = new Array(4);
    scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];
    scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];
    scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];
    scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];
    scheduleB[3] = new Array(4);
    scheduleB[3][0] = [8, 9, 7, 6, 3];
    scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];
    scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];
    scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];
    // changed 'in' to 'inn' (in javascript 'in' is a reserved word)
    this.keySchedule = function (inn) {
        const t = new Array(8);
        const k = new Array(32);
        let j;
        for (let i = 0; i < 4; i++) {
            j = i * 4;
            t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];
        }
        const x = [6, 7, 4, 5];
        let ki = 0;
        let w;
        for (let half = 0; half < 2; half++) {
            for (let round = 0; round < 4; round++) {
                for (j = 0; j < 4; j++) {
                    const a = scheduleA[round][j];
                    w = t[a[1]];
                    w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];
                    w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];
                    w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];
                    w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];
                    w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];
                    t[a[0]] = w;
                }
                for (j = 0; j < 4; j++) {
                    const b = scheduleB[round][j];
                    w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];
                    w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];
                    w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];
                    w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];
                    w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];
                    k[ki] = w;
                    ki++;
                }
            }
        }
        for (let i = 0; i < 16; i++) {
            this.masking[i] = k[i];
            this.rotate[i] = k[16 + i] & 0x1f;
        }
    };
    // These are the three 'f' functions. See RFC 2144, section 2.2.
    function f1(d, m, r) {
        const t = m + d;
        const I = (t << r) | (t >>> (32 - r));
        return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];
    }
    function f2(d, m, r) {
        const t = m ^ d;
        const I = (t << r) | (t >>> (32 - r));
        return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];
    }
    function f3(d, m, r) {
        const t = m - d;
        const I = (t << r) | (t >>> (32 - r));
        return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];
    }
    const sBox = new Array(8);
    sBox[0] = [
        0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,
        0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,
        0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,
        0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,
        0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,
        0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,
        0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,
        0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,
        0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,
        0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,
        0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,
        0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,
        0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,
        0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,
        0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,
        0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,
        0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,
        0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,
        0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,
        0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,
        0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,
        0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,
        0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,
        0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,
        0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,
        0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,
        0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,
        0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,
        0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,
        0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,
        0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,
        0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf
    ];
    sBox[1] = [
        0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,
        0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,
        0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,
        0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,
        0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,
        0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,
        0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,
        0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,
        0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,
        0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,
        0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,
        0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,
        0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,
        0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,
        0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,
        0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,
        0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,
        0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,
        0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,
        0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,
        0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,
        0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,
        0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,
        0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,
        0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,
        0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,
        0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,
        0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,
        0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,
        0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,
        0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,
        0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1
    ];
    sBox[2] = [
        0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,
        0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,
        0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,
        0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,
        0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,
        0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,
        0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,
        0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,
        0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,
        0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,
        0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,
        0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,
        0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,
        0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,
        0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,
        0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,
        0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,
        0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,
        0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,
        0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,
        0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,
        0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,
        0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,
        0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,
        0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,
        0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,
        0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,
        0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,
        0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,
        0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,
        0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,
        0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783
    ];
    sBox[3] = [
        0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,
        0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,
        0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,
        0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,
        0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,
        0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,
        0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,
        0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,
        0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,
        0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,
        0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,
        0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,
        0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,
        0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,
        0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,
        0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,
        0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,
        0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,
        0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,
        0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,
        0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,
        0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,
        0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,
        0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,
        0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,
        0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,
        0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,
        0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,
        0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,
        0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,
        0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,
        0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2
    ];
    sBox[4] = [
        0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,
        0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,
        0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,
        0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,
        0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,
        0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,
        0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,
        0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,
        0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,
        0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,
        0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,
        0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,
        0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,
        0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,
        0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,
        0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,
        0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,
        0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,
        0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,
        0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,
        0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,
        0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,
        0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,
        0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,
        0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,
        0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,
        0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,
        0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,
        0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,
        0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,
        0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,
        0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4
    ];
    sBox[5] = [
        0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,
        0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,
        0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,
        0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,
        0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,
        0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,
        0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,
        0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,
        0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,
        0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,
        0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,
        0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,
        0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,
        0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,
        0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,
        0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,
        0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,
        0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,
        0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,
        0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,
        0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,
        0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,
        0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,
        0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,
        0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,
        0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,
        0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,
        0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,
        0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,
        0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,
        0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,
        0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f
    ];
    sBox[6] = [
        0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,
        0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,
        0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,
        0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,
        0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,
        0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,
        0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,
        0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,
        0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,
        0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,
        0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,
        0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,
        0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,
        0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,
        0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,
        0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,
        0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,
        0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,
        0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,
        0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,
        0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,
        0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,
        0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,
        0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,
        0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,
        0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,
        0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,
        0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,
        0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,
        0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,
        0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,
        0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3
    ];
    sBox[7] = [
        0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,
        0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,
        0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,
        0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,
        0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,
        0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,
        0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,
        0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,
        0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,
        0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,
        0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,
        0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,
        0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,
        0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,
        0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,
        0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,
        0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,
        0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,
        0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,
        0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,
        0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,
        0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,
        0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,
        0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,
        0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,
        0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,
        0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,
        0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,
        0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,
        0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,
        0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,
        0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e
    ];
}
function CAST5(key) {
    this.cast5 = new OpenPGPSymEncCAST5();
    this.cast5.setKey(key);
    this.encrypt = function (block) {
        return this.cast5.encrypt(block);
    };
}
CAST5.blockSize = CAST5.prototype.blockSize = 8;
CAST5.keySize = CAST5.prototype.keySize = 16;

/**
 * @access private
 * Modified by Recurity Labs GmbH
 *
 * Cipher.js
 * A block-cipher algorithm implementation on JavaScript
 * See Cipher.readme.txt for further information.
 *
 * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]
 * This script file is distributed under the LGPL
 *
 * ACKNOWLEDGMENT
 *
 *     The main subroutines are written by Michiel van Everdingen.
 *
 *     Michiel van Everdingen
 *     http://home.versatel.nl/MAvanEverdingen/index.html
 *
 *     All rights for these routines are reserved to Michiel van Everdingen.
 *
 */
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Math
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const MAXINT = 0xFFFFFFFF;
function rotw(w, n) {
    return (w << n | w >>> (32 - n)) & MAXINT;
}
function getW(a, i) {
    return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;
}
function setW(a, i, w) {
    a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);
}
function getB(x, n) {
    return (x >>> (n * 8)) & 0xFF;
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Twofish
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function createTwofish() {
    //
    let keyBytes = null;
    let dataBytes = null;
    let dataOffset = -1;
    // var dataLength = -1;
    // var idx2 = -1;
    //
    let tfsKey = [];
    let tfsM = [
        [],
        [],
        [],
        []
    ];
    function tfsInit(key) {
        keyBytes = key;
        let i;
        let a;
        let b;
        let c;
        let d;
        const meKey = [];
        const moKey = [];
        const inKey = [];
        let kLen;
        const sKey = [];
        let f01;
        let f5b;
        let fef;
        const q0 = [
            [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],
            [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]
        ];
        const q1 = [
            [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],
            [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]
        ];
        const q2 = [
            [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],
            [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]
        ];
        const q3 = [
            [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],
            [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]
        ];
        const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];
        const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];
        /** @type {number[][]} */
        const q = [
            [],
            []
        ];
        const m = [
            [],
            [],
            [],
            []
        ];
        function ffm5b(x) {
            return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];
        }
        function ffmEf(x) {
            return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];
        }
        function mdsRem(p, q) {
            let i;
            let t;
            let u;
            for (i = 0; i < 8; i++) {
                t = q >>> 24;
                q = ((q << 8) & MAXINT) | p >>> 24;
                p = (p << 8) & MAXINT;
                u = t << 1;
                if (t & 128) {
                    u ^= 333;
                }
                q ^= t ^ (u << 16);
                u ^= t >>> 1;
                if (t & 1) {
                    u ^= 166;
                }
                q ^= u << 24 | u << 8;
            }
            return q;
        }
        function qp(n, x) {
            const a = x >> 4;
            const b = x & 15;
            const c = q0[n][a ^ b];
            const d = q1[n][ror4[b] ^ ashx[a]];
            return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];
        }
        function hFun(x, key) {
            let a = getB(x, 0);
            let b = getB(x, 1);
            let c = getB(x, 2);
            let d = getB(x, 3);
            switch (kLen) {
                case 4:
                    a = q[1][a] ^ getB(key[3], 0);
                    b = q[0][b] ^ getB(key[3], 1);
                    c = q[0][c] ^ getB(key[3], 2);
                    d = q[1][d] ^ getB(key[3], 3);
                // eslint-disable-next-line no-fallthrough
                case 3:
                    a = q[1][a] ^ getB(key[2], 0);
                    b = q[1][b] ^ getB(key[2], 1);
                    c = q[0][c] ^ getB(key[2], 2);
                    d = q[0][d] ^ getB(key[2], 3);
                // eslint-disable-next-line no-fallthrough
                case 2:
                    a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);
                    b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);
                    c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);
                    d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);
            }
            return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];
        }
        keyBytes = keyBytes.slice(0, 32);
        i = keyBytes.length;
        while (i !== 16 && i !== 24 && i !== 32) {
            keyBytes[i++] = 0;
        }
        for (i = 0; i < keyBytes.length; i += 4) {
            inKey[i >> 2] = getW(keyBytes, i);
        }
        for (i = 0; i < 256; i++) {
            q[0][i] = qp(0, i);
            q[1][i] = qp(1, i);
        }
        for (i = 0; i < 256; i++) {
            f01 = q[1][i];
            f5b = ffm5b(f01);
            fef = ffmEf(f01);
            m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);
            m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);
            f01 = q[0][i];
            f5b = ffm5b(f01);
            fef = ffmEf(f01);
            m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);
            m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);
        }
        kLen = inKey.length / 2;
        for (i = 0; i < kLen; i++) {
            a = inKey[i + i];
            meKey[i] = a;
            b = inKey[i + i + 1];
            moKey[i] = b;
            sKey[kLen - i - 1] = mdsRem(a, b);
        }
        for (i = 0; i < 40; i += 2) {
            a = 0x1010101 * i;
            b = a + 0x1010101;
            a = hFun(a, meKey);
            b = rotw(hFun(b, moKey), 8);
            tfsKey[i] = (a + b) & MAXINT;
            tfsKey[i + 1] = rotw(a + 2 * b, 9);
        }
        for (i = 0; i < 256; i++) {
            a = b = c = d = i;
            switch (kLen) {
                case 4:
                    a = q[1][a] ^ getB(sKey[3], 0);
                    b = q[0][b] ^ getB(sKey[3], 1);
                    c = q[0][c] ^ getB(sKey[3], 2);
                    d = q[1][d] ^ getB(sKey[3], 3);
                // eslint-disable-next-line no-fallthrough
                case 3:
                    a = q[1][a] ^ getB(sKey[2], 0);
                    b = q[1][b] ^ getB(sKey[2], 1);
                    c = q[0][c] ^ getB(sKey[2], 2);
                    d = q[0][d] ^ getB(sKey[2], 3);
                // eslint-disable-next-line no-fallthrough
                case 2:
                    tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];
                    tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];
                    tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];
                    tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];
            }
        }
    }
    function tfsG0(x) {
        return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];
    }
    function tfsG1(x) {
        return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];
    }
    function tfsFrnd(r, blk) {
        let a = tfsG0(blk[0]);
        let b = tfsG1(blk[1]);
        blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);
        blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;
        a = tfsG0(blk[2]);
        b = tfsG1(blk[3]);
        blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);
        blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;
    }
    function tfsIrnd(i, blk) {
        let a = tfsG0(blk[0]);
        let b = tfsG1(blk[1]);
        blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;
        blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);
        a = tfsG0(blk[2]);
        b = tfsG1(blk[3]);
        blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;
        blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);
    }
    function tfsClose() {
        tfsKey = [];
        tfsM = [
            [],
            [],
            [],
            []
        ];
    }
    function tfsEncrypt(data, offset) {
        dataBytes = data;
        dataOffset = offset;
        const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],
            getW(dataBytes, dataOffset + 4) ^ tfsKey[1],
            getW(dataBytes, dataOffset + 8) ^ tfsKey[2],
            getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];
        for (let j = 0; j < 8; j++) {
            tfsFrnd(j, blk);
        }
        setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);
        setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);
        setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);
        setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);
        dataOffset += 16;
        return dataBytes;
    }
    function tfsDecrypt(data, offset) {
        dataBytes = data;
        dataOffset = offset;
        const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],
            getW(dataBytes, dataOffset + 4) ^ tfsKey[5],
            getW(dataBytes, dataOffset + 8) ^ tfsKey[6],
            getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];
        for (let j = 7; j >= 0; j--) {
            tfsIrnd(j, blk);
        }
        setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);
        setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);
        setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);
        setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);
        dataOffset += 16;
    }
    // added by Recurity Labs
    function tfsFinal() {
        return dataBytes;
    }
    return {
        name: 'twofish',
        blocksize: 128 / 8,
        open: tfsInit,
        close: tfsClose,
        encrypt: tfsEncrypt,
        decrypt: tfsDecrypt,
        // added by Recurity Labs
        finalize: tfsFinal
    };
}
// added by Recurity Labs
function TF(key) {
    this.tf = createTwofish();
    this.tf.open(Array.from(key), 0);
    this.encrypt = function (block) {
        return this.tf.encrypt(Array.from(block), 0);
    };
}
TF.keySize = TF.prototype.keySize = 32;
TF.blockSize = TF.prototype.blockSize = 16;

/**
 * @access private
 * Modified by Recurity Labs GmbH
 *
 * Originally written by nklein software (nklein.com)
 */
/*
 * Javascript implementation based on Bruce Schneier's reference implementation.
 *
 *
 * The constructor doesn't do much of anything.  It's just here
 * so we can start defining properties and methods and such.
 */
function Blowfish() { }
/*
 * Declare the block size so that protocols know what size
 * Initialization Vector (IV) they will need.
 */
Blowfish.prototype.BLOCKSIZE = 8;
/*
 * These are the default SBOXES.
 */
Blowfish.prototype.SBOXES = [
    [
        0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
        0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
        0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,
        0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
        0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
        0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
        0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,
        0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
        0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,
        0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
        0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,
        0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
        0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
        0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
        0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
        0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
        0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,
        0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
        0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,
        0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
        0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,
        0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
        0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,
        0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
        0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
        0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
        0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,
        0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
        0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,
        0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
        0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,
        0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
        0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,
        0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
        0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
        0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
        0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,
        0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
        0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,
        0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
        0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,
        0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
        0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a
    ],
    [
        0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,
        0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
        0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,
        0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
        0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
        0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
        0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
        0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
        0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
        0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
        0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,
        0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
        0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,
        0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
        0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,
        0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
        0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,
        0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
        0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
        0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
        0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,
        0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
        0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,
        0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
        0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,
        0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
        0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
        0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
        0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
        0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
        0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,
        0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
        0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,
        0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
        0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,
        0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
        0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,
        0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
        0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
        0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
        0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,
        0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
        0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7
    ],
    [
        0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,
        0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
        0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,
        0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
        0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,
        0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
        0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,
        0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
        0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,
        0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
        0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,
        0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
        0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,
        0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
        0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,
        0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
        0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,
        0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
        0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,
        0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
        0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,
        0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
        0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,
        0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
        0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,
        0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
        0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,
        0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
        0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,
        0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
        0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,
        0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
        0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,
        0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
        0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,
        0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
        0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,
        0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
        0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,
        0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
        0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,
        0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
        0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0
    ],
    [
        0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,
        0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
        0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,
        0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
        0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
        0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
        0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
        0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
        0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,
        0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
        0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,
        0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
        0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,
        0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
        0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
        0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
        0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
        0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
        0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,
        0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
        0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,
        0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
        0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,
        0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
        0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,
        0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
        0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
        0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
        0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,
        0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
        0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,
        0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
        0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,
        0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
        0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,
        0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
        0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
        0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
        0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,
        0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
        0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
        0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
        0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
    ]
];
//*
//* This is the default PARRAY
//*
Blowfish.prototype.PARRAY = [
    0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
    0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
    0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b
];
//*
//* This is the number of rounds the cipher will go
//*
Blowfish.prototype.NN = 16;
//*
//* This function is needed to get rid of problems
//* with the high-bit getting set.  If we don't do
//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not
//* equal to ( bb & 0x00FFFFFFFF ) even when they
//* agree bit-for-bit for the first 32 bits.
//*
Blowfish.prototype._clean = function (xx) {
    if (xx < 0) {
        const yy = xx & 0x7FFFFFFF;
        xx = yy + 0x80000000;
    }
    return xx;
};
//*
//* This is the mixing function that uses the sboxes
//*
Blowfish.prototype._F = function (xx) {
    let yy;
    const dd = xx & 0x00FF;
    xx >>>= 8;
    const cc = xx & 0x00FF;
    xx >>>= 8;
    const bb = xx & 0x00FF;
    xx >>>= 8;
    const aa = xx & 0x00FF;
    yy = this.sboxes[0][aa] + this.sboxes[1][bb];
    yy ^= this.sboxes[2][cc];
    yy += this.sboxes[3][dd];
    return yy;
};
//*
//* This method takes an array with two values, left and right
//* and does NN rounds of Blowfish on them.
//*
Blowfish.prototype._encryptBlock = function (vals) {
    let dataL = vals[0];
    let dataR = vals[1];
    let ii;
    for (ii = 0; ii < this.NN; ++ii) {
        dataL ^= this.parray[ii];
        dataR = this._F(dataL) ^ dataR;
        const tmp = dataL;
        dataL = dataR;
        dataR = tmp;
    }
    dataL ^= this.parray[this.NN + 0];
    dataR ^= this.parray[this.NN + 1];
    vals[0] = this._clean(dataR);
    vals[1] = this._clean(dataL);
};
//*
//* This method takes a vector of numbers and turns them
//* into long words so that they can be processed by the
//* real algorithm.
//*
//* Maybe I should make the real algorithm above take a vector
//* instead.  That will involve more looping, but it won't require
//* the F() method to deconstruct the vector.
//*
Blowfish.prototype.encryptBlock = function (vector) {
    let ii;
    const vals = [0, 0];
    const off = this.BLOCKSIZE / 2;
    for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
        vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);
        vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);
    }
    this._encryptBlock(vals);
    const ret = [];
    for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
        ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);
        ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);
        // vals[ 0 ] = ( vals[ 0 ] >>> 8 );
        // vals[ 1 ] = ( vals[ 1 ] >>> 8 );
    }
    return ret;
};
//*
//* This method takes an array with two values, left and right
//* and undoes NN rounds of Blowfish on them.
//*
Blowfish.prototype._decryptBlock = function (vals) {
    let dataL = vals[0];
    let dataR = vals[1];
    let ii;
    for (ii = this.NN + 1; ii > 1; --ii) {
        dataL ^= this.parray[ii];
        dataR = this._F(dataL) ^ dataR;
        const tmp = dataL;
        dataL = dataR;
        dataR = tmp;
    }
    dataL ^= this.parray[1];
    dataR ^= this.parray[0];
    vals[0] = this._clean(dataR);
    vals[1] = this._clean(dataL);
};
//*
//* This method takes a key array and initializes the
//* sboxes and parray for this encryption.
//*
Blowfish.prototype.init = function (key) {
    let ii;
    let jj = 0;
    this.parray = [];
    for (ii = 0; ii < this.NN + 2; ++ii) {
        let data = 0x00000000;
        for (let kk = 0; kk < 4; ++kk) {
            data = (data << 8) | (key[jj] & 0x00FF);
            if (++jj >= key.length) {
                jj = 0;
            }
        }
        this.parray[ii] = this.PARRAY[ii] ^ data;
    }
    this.sboxes = [];
    for (ii = 0; ii < 4; ++ii) {
        this.sboxes[ii] = [];
        for (jj = 0; jj < 256; ++jj) {
            this.sboxes[ii][jj] = this.SBOXES[ii][jj];
        }
    }
    const vals = [0x00000000, 0x00000000];
    for (ii = 0; ii < this.NN + 2; ii += 2) {
        this._encryptBlock(vals);
        this.parray[ii + 0] = vals[0];
        this.parray[ii + 1] = vals[1];
    }
    for (ii = 0; ii < 4; ++ii) {
        for (jj = 0; jj < 256; jj += 2) {
            this._encryptBlock(vals);
            this.sboxes[ii][jj + 0] = vals[0];
            this.sboxes[ii][jj + 1] = vals[1];
        }
    }
};
// added by Recurity Labs
function BF(key) {
    this.bf = new Blowfish();
    this.bf.init(key);
    this.encrypt = function (block) {
        return this.bf.encryptBlock(block);
    };
}
BF.keySize = BF.prototype.keySize = 16;
BF.blockSize = BF.prototype.blockSize = 8;

/**
 * @access private
 * This file is needed to dynamic import the legacy ciphers.
 * Separate dynamic imports are not convenient as they result in multiple chunks.
 */
// We avoid importing 'enums' as this module is lazy loaded, and doing so could mess up
// chunking for the lightweight build
const legacyCiphers = new Map(Object.entries({
    tripledes: TripleDES,
    cast5: CAST5,
    twofish: TF,
    blowfish: BF
}));

var legacy_ciphers = /*#__PURE__*/Object.freeze({
  __proto__: null,
  legacyCiphers: legacyCiphers
});

// Adapted from the reference implementation in RFC7693
// Initial port to Javascript by https://github.com/dcposch and https://github.com/emilbayes

// Uint64 values are represented using two Uint32s, stored as little endian
// NB: Uint32Arrays endianness depends on the underlying system, so for interoperability, conversions between Uint8Array and Uint32Arrays
// need to be manually handled

// 64-bit unsigned addition (little endian, in place)
// Sets a[i,i+1] += b[j,j+1]
// `a` and `b` must be Uint32Array(2)
function ADD64 (a, i, b, j) {
  a[i] += b[j];
  a[i+1] += b[j+1] + (a[i] < b[j]); // add carry
}

// Increment 64-bit little-endian unsigned value by `c` (in place)
// `a` must be Uint32Array(2)
function INC64 (a, c) {
  a[0] += c;
  a[1] += (a[0] < c);
}

// G Mixing function
// The ROTRs are inlined for speed
function G$1 (v, m, a, b, c, d, ix, iy) {
  ADD64(v, a, v, b); // v[a,a+1] += v[b,b+1]
  ADD64(v, a, m, ix); // v[a, a+1] += x ... x0

  // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits
  let xor0 = v[d] ^ v[a];
  let xor1 = v[d + 1] ^ v[a + 1];
  v[d] = xor1;
  v[d + 1] = xor0;

  ADD64(v, c, v, d);

  // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits
  xor0 = v[b] ^ v[c];
  xor1 = v[b + 1] ^ v[c + 1];
  v[b] = (xor0 >>> 24) ^ (xor1 << 8);
  v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8);

  ADD64(v, a, v, b);
  ADD64(v, a, m, iy);

  // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits
  xor0 = v[d] ^ v[a];
  xor1 = v[d + 1] ^ v[a + 1];
  v[d] = (xor0 >>> 16) ^ (xor1 << 16);
  v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16);

  ADD64(v, c, v, d);

  // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits
  xor0 = v[b] ^ v[c];
  xor1 = v[b + 1] ^ v[c + 1];
  v[b] = (xor1 >>> 31) ^ (xor0 << 1);
  v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1);
}

// Initialization Vector
const BLAKE2B_IV32 = new Uint32Array([
  0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85,
  0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A,
  0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C,
  0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19
]);

// These are offsets into a Uint64 buffer.
// Multiply them all by 2 to make them offsets into a Uint32 buffer
const SIGMA = new Uint8Array([
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
  11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
  7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
  9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
  2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
  12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,
  13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,
  6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,
  10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3
].map(x => x * 2));

// Compression function. 'last' flag indicates last block.
// Note: we're representing 16 uint64s as 32 uint32s
function compress(S, last) {
  const v = new Uint32Array(32);
  const m = new Uint32Array(S.b.buffer, S.b.byteOffset, 32);

  // init work variables
  for (let i = 0; i < 16; i++) {
    v[i] = S.h[i];
    v[i + 16] = BLAKE2B_IV32[i];
  }

  // low 64 bits of offset
  v[24] ^= S.t0[0];
  v[25] ^= S.t0[1];
  // high 64 bits not supported (`t1`), offset may not be higher than 2**53-1

  // if last block
  const f0 = last ? 0xFFFFFFFF : 0;
  v[28] ^= f0;
  v[29] ^= f0;

  // twelve rounds of mixing
  for (let i = 0; i < 12; i++) {
    // ROUND(r)
    const i16 = i << 4;
    G$1(v, m, 0, 8, 16, 24,  SIGMA[i16 + 0], SIGMA[i16 + 1]);
    G$1(v, m, 2, 10, 18, 26, SIGMA[i16 + 2], SIGMA[i16 + 3]);
    G$1(v, m, 4, 12, 20, 28, SIGMA[i16 + 4], SIGMA[i16 + 5]);
    G$1(v, m, 6, 14, 22, 30, SIGMA[i16 + 6], SIGMA[i16 + 7]);
    G$1(v, m, 0, 10, 20, 30, SIGMA[i16 + 8], SIGMA[i16 + 9]);
    G$1(v, m, 2, 12, 22, 24, SIGMA[i16 + 10], SIGMA[i16 + 11]);
    G$1(v, m, 4, 14, 16, 26, SIGMA[i16 + 12], SIGMA[i16 + 13]);
    G$1(v, m, 6, 8, 18, 28,  SIGMA[i16 + 14], SIGMA[i16 + 15]);
  }

  for (let i = 0; i < 16; i++) {
    S.h[i] ^= v[i] ^ v[i + 16];
  }
}

// Creates a BLAKE2b hashing context
// Requires an output length between 1 and 64 bytes
// Takes an optional Uint8Array key
class Blake2b {
  constructor(outlen, key, salt, personal) {
    const params = new Uint8Array(64);
    //  0: outlen, keylen, fanout, depth
    //  4: leaf length, sequential mode
    //  8: node offset
    // 12: node offset
    // 16: node depth, inner length, rfu
    // 20: rfu
    // 24: rfu
    // 28: rfu
    // 32: salt
    // 36: salt
    // 40: salt
    // 44: salt
    // 48: personal
    // 52: personal
    // 56: personal
    // 60: personal

    // init internal state
    this.S = {
      b: new Uint8Array(BLOCKBYTES),
      h: new Uint32Array(OUTBYTES_MAX / 4),
      t0: new Uint32Array(2), // input counter `t`, lower 64-bits only
      c: 0, // `fill`, pointer within buffer, up to `BLOCKBYTES`
      outlen // output length in bytes
    };

    // init parameter block
    params[0] = outlen;
    if (key) params[1] = key.length;
    params[2] = 1; // fanout
    params[3] = 1; // depth
    if (salt) params.set(salt, 32);
    if (personal) params.set(personal, 48);
    const params32 = new Uint32Array(params.buffer, params.byteOffset, params.length / Uint32Array.BYTES_PER_ELEMENT);

    // initialize hash state
    for (let i = 0; i < 16; i++) {
      this.S.h[i] = BLAKE2B_IV32[i] ^ params32[i];
    }

    // key the hash, if applicable
    if (key) {
      const block = new Uint8Array(BLOCKBYTES);
      block.set(key);
      this.update(block);
    }
  }

  // Updates a BLAKE2b streaming hash
  // Requires Uint8Array (byte array)
  update(input) {
    if (!(input instanceof Uint8Array)) throw new Error('Input must be Uint8Array or Buffer')
    // for (let i = 0; i < input.length; i++) {
    //   if (this.S.c === BLOCKBYTES) { // buffer full
    //     INC64(this.S.t0, this.S.c) // add counters
    //     compress(this.S, false)
    //     this.S.c = 0 // empty buffer
    //   }
    //   this.S.b[this.S.c++] = input[i]
    // }
    let i = 0;
    while(i < input.length) {
      if (this.S.c === BLOCKBYTES) { // buffer full
        INC64(this.S.t0, this.S.c); // add counters
        compress(this.S, false);
        this.S.c = 0; // empty buffer
      }
      let left = BLOCKBYTES - this.S.c;
      this.S.b.set(input.subarray(i, i + left), this.S.c); // end index can be out of bounds
      const fill = Math.min(left, input.length - i);
      this.S.c += fill;
      i += fill;
    }
    return this
  }

  /**
   * Return a BLAKE2b hash, either filling the given Uint8Array or allocating a new one
   * @param {Uint8Array} [prealloc] - optional preallocated buffer
   * @returns {ArrayBuffer} message digest
   */
  digest(prealloc) {
    INC64(this.S.t0, this.S.c); // mark last block offset

    // final block, padded
    this.S.b.fill(0, this.S.c);
    this.S.c = BLOCKBYTES;
    compress(this.S, true);

    const out = prealloc || new Uint8Array(this.S.outlen);
    for (let i = 0; i < this.S.outlen; i++) {
      // must be loaded individually since default Uint32 endianness is platform dependant
      out[i] = this.S.h[i >> 2] >> (8 * (i & 3));
    }
    this.S.h = null; // prevent calling `update` after `digest`
    return out.buffer;
  }
}


function createHash(outlen, key, salt, personal) {
  if (outlen > OUTBYTES_MAX) throw new Error(`outlen must be at most ${OUTBYTES_MAX} (given: ${outlen})`)

  return new Blake2b(outlen, key, salt, personal)
}

const OUTBYTES_MAX = 64;
const BLOCKBYTES = 128;

const TYPE = 2;  // Argon2id
const VERSION = 0x13;
const TAGBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1;
const TAGBYTES_MIN = 4; // Math.pow(2, 32) - 1;
const SALTBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1;
const SALTBYTES_MIN = 8;
const passwordBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1;
const passwordBYTES_MIN = 8;
const MEMBYTES_MAX = 0xFFFFFFFF;// Math.pow(2, 32) - 1;
const ADBYTES_MAX = 0xFFFFFFFF; // Math.pow(2, 32) - 1; // associated data (optional)
const SECRETBYTES_MAX = 32; // key (optional)

const ARGON2_BLOCK_SIZE = 1024;
const ARGON2_PREHASH_DIGEST_LENGTH = 64;

const isLittleEndian = new Uint8Array(new Uint16Array([0xabcd]).buffer)[0] === 0xcd;

// store n as a little-endian 32-bit Uint8Array inside buf (at buf[i:i+3])
function LE32(buf, n, i) {
  buf[i+0] = n;
  buf[i+1] = n >>  8;
  buf[i+2] = n >> 16;
  buf[i+3] = n >> 24;
  return buf;
}

/**
 * Store n as a 64-bit LE number in the given buffer (from buf[i] to buf[i+7])
 * @param {Uint8Array} buf
 * @param {Number} n
 * @param {Number} i
 */
function LE64(buf, n, i) {
  if (n > Number.MAX_SAFE_INTEGER) throw new Error("LE64: large numbers unsupported");
  // ECMAScript standard has engines convert numbers to 32-bit integers for bitwise operations
  // shifting by 32 or more bits is not supported (https://stackoverflow.com/questions/6729122/javascript-bit-shift-number-wraps)
  // so we manually extract each byte
  let remainder = n;
  for (let offset = i; offset < i+7; offset++) { // last byte can be ignored as it would overflow MAX_SAFE_INTEGER
    buf[offset] = remainder; // implicit & 0xff
    remainder = (remainder - buf[offset]) / 256;
  }
  return buf;
}

/**
 * Variable-Length Hash Function H'
 * @param {Number} outlen - T
 * @param {Uint8Array} X - value to hash
 * @param {Uint8Array} res - output buffer, of length `outlength` or larger
 */
function H_(outlen, X, res) {
  const V = new Uint8Array(64); // no need to keep around all V_i

  const V1_in = new Uint8Array(4 + X.length);
  LE32(V1_in, outlen, 0);
  V1_in.set(X, 4);
  if (outlen <= 64) {
    // H'^T(A) = H^T(LE32(T)||A)
    createHash(outlen).update(V1_in).digest(res);
    return res
  }

  const r = Math.ceil(outlen / 32) - 2;

  // Let V_i be a 64-byte block and W_i be its first 32 bytes.
  // V_1 = H^(64)(LE32(T)||A)
  // V_2 = H^(64)(V_1)
  // ...
  // V_r = H^(64)(V_{r-1})
  // V_{r+1} = H^(T-32*r)(V_{r})
  // H'^T(X) = W_1 || W_2 || ... || W_r || V_{r+1}
  for (let i = 0; i < r; i++) {
    createHash(64).update(i === 0 ? V1_in : V).digest(V);
    // store W_i in result buffer already
    res.set(V.subarray(0, 32), i*32);
  }
  // V_{r+1}
  const V_r1 = new Uint8Array(createHash(outlen - 32*r).update(V).digest());
  res.set(V_r1, r*32);

  return res;
}

// compute buf = xs ^ ys
function XOR(wasmContext, buf, xs, ys) {
  wasmContext.fn.XOR(
    buf.byteOffset,
    xs.byteOffset,
    ys.byteOffset,
  );
  return buf
}

/**
 * @param {Uint8Array} X (read-only)
 * @param {Uint8Array} Y (read-only)
 * @param {Uint8Array} R - output buffer
 * @returns
 */
function G(wasmContext, X, Y, R) {
  wasmContext.fn.G(
    X.byteOffset,
    Y.byteOffset,
    R.byteOffset,
    wasmContext.refs.gZ.byteOffset
  );
  return R;
}

function G2(wasmContext, X, Y, R) {
  wasmContext.fn.G2(
    X.byteOffset,
    Y.byteOffset,
    R.byteOffset,
    wasmContext.refs.gZ.byteOffset
  );
  return R;
}

// Generator for data-independent J1, J2. Each `next()` invocation returns a new pair of values.
function* makePRNG(wasmContext, pass, lane, slice, m_, totalPasses, segmentLength, segmentOffset) {
  // For each segment, we do the following. First, we compute the value Z as:
  // Z= ( LE64(r) || LE64(l) || LE64(sl) || LE64(m') || LE64(t) || LE64(y) )
  wasmContext.refs.prngTmp.fill(0);
  const Z = wasmContext.refs.prngTmp.subarray(0, 6 * 8);
  LE64(Z, pass, 0);
  LE64(Z, lane, 8);
  LE64(Z, slice, 16);
  LE64(Z, m_, 24);
  LE64(Z, totalPasses, 32);
  LE64(Z, TYPE, 40);

  // Then we compute q/(128*SL) 1024-byte values
  // G( ZERO(1024),
  //    G( ZERO(1024), Z || LE64(1) || ZERO(968) ) ),
  // ...,
  // G( ZERO(1024),
  //    G( ZERO(1024), Z || LE64(q/(128*SL)) || ZERO(968) )),
  for(let i = 1; i <= segmentLength; i++) {
    // tmp.set(Z); // no need to re-copy
    LE64(wasmContext.refs.prngTmp, i, Z.length); // tmp.set(ZER0968) not necessary, memory already zeroed
    const g2 = G2(wasmContext, wasmContext.refs.ZERO1024, wasmContext.refs.prngTmp, wasmContext.refs.prngR );

    // each invocation of G^2 outputs 1024 bytes that are to be partitioned into 8-bytes values, take as X1 || X2
    // NB: the first generated pair must be used for the first block of the segment, and so on.
    // Hence, if some blocks are skipped (e.g. during the first pass), the corresponding J1J2 are discarded based on the given segmentOffset.
    for(let k = i === 1 ? segmentOffset*8 : 0; k < g2.length; k += 8) {
       yield g2.subarray(k, k+8);
    }
  }
  return [];
}

function validateParams({ type, version, tagLength, password, salt, ad, secret, parallelism, memorySize, passes }) {
  const assertLength = (name, value, min, max) => {
    if (value < min || value > max) { throw new Error(`${name} size should be between ${min} and ${max} bytes`); }
  };

  if (type !== TYPE || version !== VERSION) throw new Error('Unsupported type or version');
  assertLength('password', password, passwordBYTES_MIN, passwordBYTES_MAX);
  assertLength('salt', salt, SALTBYTES_MIN, SALTBYTES_MAX);
  assertLength('tag', tagLength, TAGBYTES_MIN, TAGBYTES_MAX);
  assertLength('memory', memorySize, 8*parallelism, MEMBYTES_MAX);
  // optional fields
  ad && assertLength('associated data', ad, 0, ADBYTES_MAX);
  secret && assertLength('secret', secret, 0, SECRETBYTES_MAX);

  return { type, version, tagLength, password, salt, ad, secret, lanes: parallelism, memorySize, passes };
}

const KB = 1024;
const WASM_PAGE_SIZE = 64 * KB;

function argon2id(params, { memory, instance: wasmInstance }) {
  if (!isLittleEndian) throw new Error('BigEndian system not supported'); // optmisations assume LE system

  const ctx = validateParams({ type: TYPE, version: VERSION, ...params });

  const { G:wasmG, G2:wasmG2, xor:wasmXOR, getLZ:wasmLZ } = wasmInstance.exports;
  const wasmRefs = {};
  const wasmFn = {};
  wasmFn.G = wasmG;
  wasmFn.G2 = wasmG2;
  wasmFn.XOR = wasmXOR;

  // The actual number of blocks is m', which is m rounded down to the nearest multiple of 4*p.
  const m_ = 4 * ctx.lanes * Math.floor(ctx.memorySize / (4 * ctx.lanes));
  const requiredMemory = m_ * ARGON2_BLOCK_SIZE + 10 * KB; // Additional KBs for utility references
  if (memory.buffer.byteLength < requiredMemory) {
    const missing = Math.ceil((requiredMemory - memory.buffer.byteLength) / WASM_PAGE_SIZE);
    // If enough memory is available, the `memory.buffer` is internally detached and the reference updated.
    // Otherwise, the operation fails, and the original memory can still be used.
    memory.grow(missing);
  }

  let offset = 0;
  // Init wasm memory needed in other functions
  wasmRefs.gZ = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+= wasmRefs.gZ.length;
  wasmRefs.prngR = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngR.length;
  wasmRefs.prngTmp = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=wasmRefs.prngTmp.length;
  wasmRefs.ZERO1024 = new Uint8Array(memory.buffer, offset, 1024); offset+=wasmRefs.ZERO1024.length;
  // Init wasm memory needed locally
  const lz = new Uint32Array(memory.buffer, offset, 2); offset+=lz.length * Uint32Array.BYTES_PER_ELEMENT;
  const wasmContext = { fn: wasmFn, refs: wasmRefs };
  const newBlock = new Uint8Array(memory.buffer, offset, ARGON2_BLOCK_SIZE); offset+=newBlock.length;
  const blockMemory = new Uint8Array(memory.buffer, offset, ctx.memorySize * ARGON2_BLOCK_SIZE);
  const allocatedMemory = new Uint8Array(memory.buffer, 0, offset);

  // 1. Establish H_0
  const H0 = getH0(ctx);

  // 2. Allocate the memory as m' 1024-byte blocks
  // For p lanes, the memory is organized in a matrix B[i][j] of blocks with p rows (lanes) and q = m' / p columns.
  const q = m_ / ctx.lanes;
  const B = new Array(ctx.lanes).fill(null).map(() => new Array(q));
  const initBlock = (i, j) => {
    B[i][j] = blockMemory.subarray(i*q*1024 + j*1024, (i*q*1024 + j*1024) + ARGON2_BLOCK_SIZE);
    return B[i][j];
  };

  for (let i = 0; i < ctx.lanes; i++) {
    // const LEi = LE0; //  since p = 1 for us
    const tmp = new Uint8Array(H0.length + 8);
    // 3. Compute B[i][0] for all i ranging from (and including) 0 to (not including) p
    // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i))
    tmp.set(H0); LE32(tmp, 0, H0.length); LE32(tmp, i, H0.length + 4);
    H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 0));
    // 4. Compute B[i][1] for all i ranging from (and including) 0 to (not including) p
    // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i))
    LE32(tmp, 1, H0.length);
    H_(ARGON2_BLOCK_SIZE, tmp, initBlock(i, 1));
  }

    // 5. Compute B[i][j] for all i ranging from (and including) 0 to (not including) p and for all j ranging from (and including) 2
    // to (not including) q. The computation MUST proceed slicewise (Section 3.4) : first, blocks from slice 0 are computed for all lanes
    // (in an arbitrary order of lanes), then blocks from slice 1 are computed, etc.
  const SL = 4; // vertical slices
  const segmentLength = q / SL;
  for (let pass = 0; pass < ctx.passes; pass++) {
      // The intersection of a slice and a lane is called a segment, which has a length of q/SL. Segments of the same slice can be computed in parallel
    for (let sl = 0; sl < SL; sl++) {
      const isDataIndependent = pass === 0 && sl <= 1;
      for (let i = 0; i < ctx.lanes; i++) { // lane
        // On the first slice of the first pass, blocks 0 and 1 are already filled
        let segmentOffset = sl === 0 && pass === 0 ? 2 : 0;
        // no need to generate all J1J2s, use iterator/generator that creates the value on the fly (to save memory)
        const PRNG = isDataIndependent ? makePRNG(wasmContext, pass, i, sl, m_, ctx.passes, segmentLength, segmentOffset) : null;
        for (segmentOffset; segmentOffset < segmentLength; segmentOffset++) {
          const j = sl * segmentLength + segmentOffset;
          const prevBlock = j > 0 ? B[i][j-1] : B[i][q-1]; // B[i][(j-1) mod q]

          // we can assume the PRNG is never done
          const J1J2 = isDataIndependent ? PRNG.next().value : prevBlock; // .subarray(0, 8) not required since we only pass the byteOffset to wasm
          // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id.
          wasmLZ(lz.byteOffset, J1J2.byteOffset, i, ctx.lanes, pass, sl, segmentOffset, SL, segmentLength);
          const l = lz[0]; const z = lz[1];
          // for (let i = 0; i < p; i++ )
          // B[i][j] = G(B[i][j-1], B[l][z])
          // The block indices l and z are determined for each i, j differently for Argon2d, Argon2i, and Argon2id.
          if (pass === 0) initBlock(i, j);
          G(wasmContext, prevBlock, B[l][z], pass > 0 ? newBlock : B[i][j]);

          // 6. If the number of passes t is larger than 1, we repeat step 5. However, blocks are computed differently as the old value is XORed with the new one
          if (pass > 0) XOR(wasmContext, B[i][j], newBlock, B[i][j]);
        }
      }
    }
  }

  // 7. After t steps have been iterated, the final block C is computed as the XOR of the last column:
  // C = B[0][q-1] XOR B[1][q-1] XOR ... XOR B[p-1][q-1]
  const C = B[0][q-1];
  for(let i = 1; i < ctx.lanes; i++) {
    XOR(wasmContext, C, C, B[i][q-1]);
  }

  const tag = H_(ctx.tagLength, C, new Uint8Array(ctx.tagLength));
  // clear memory since the module might be cached
  allocatedMemory.fill(0); // clear sensitive contents
  memory.grow(0); // allow deallocation
  // 8. The output tag is computed as H'^T(C).
  return tag;

}

function getH0(ctx) {
  const H = createHash(ARGON2_PREHASH_DIGEST_LENGTH);
  const ZERO32 = new Uint8Array(4);
  const params = new Uint8Array(24);
  LE32(params, ctx.lanes, 0);
  LE32(params, ctx.tagLength, 4);
  LE32(params, ctx.memorySize, 8);
  LE32(params, ctx.passes, 12);
  LE32(params, ctx.version, 16);
  LE32(params, ctx.type, 20);

  const toHash = [params];
  if (ctx.password) {
    toHash.push(LE32(new Uint8Array(4), ctx.password.length, 0));
    toHash.push(ctx.password);
  } else {
    toHash.push(ZERO32); // context.password.length
  }

  if (ctx.salt) {
    toHash.push(LE32(new Uint8Array(4), ctx.salt.length, 0));
    toHash.push(ctx.salt);
  } else {
    toHash.push(ZERO32); // context.salt.length
  }

  if (ctx.secret) {
    toHash.push(LE32(new Uint8Array(4), ctx.secret.length, 0));
    toHash.push(ctx.secret);
    // todo clear secret?
  } else {
    toHash.push(ZERO32); // context.secret.length
  }

  if (ctx.ad) {
    toHash.push(LE32(new Uint8Array(4), ctx.ad.length, 0));
    toHash.push(ctx.ad);
  } else {
    toHash.push(ZERO32); // context.ad.length
  }
  H.update(concatArrays(toHash));

  const outputBuffer = H.digest();
  return new Uint8Array(outputBuffer);
}

function concatArrays(arrays) {
  if (arrays.length === 1) return arrays[0];

  let totalLength = 0;
  for (let i = 0; i < arrays.length; i++) {
      if (!(arrays[i] instanceof Uint8Array)) {
          throw new Error('concatArrays: Data must be in the form of a Uint8Array');
      }

      totalLength += arrays[i].length;
  }

  const result = new Uint8Array(totalLength);
  let pos = 0;
  arrays.forEach((element) => {
      result.set(element, pos);
      pos += element.length;
  });

  return result;
}

let isSIMDSupported;
async function wasmLoader(memory, getSIMD, getNonSIMD) {
  const importObject = { env: { memory } };
  if (isSIMDSupported === undefined) {
    try {
      const loaded = await getSIMD(importObject);
      isSIMDSupported = true;
      return loaded;
    } catch(e) {
      isSIMDSupported = false;
    }
  }

  const loader = isSIMDSupported ? getSIMD : getNonSIMD;
  return loader(importObject);
}

async function setupWasm(getSIMD, getNonSIMD) {
  const memory = new WebAssembly.Memory({
    // in pages of 64KiB each
    // these values need to be compatible with those declared when building in `build-wasm`
    initial: 1040,  // 65MB
    maximum: 65536, // 4GB
  });
  const wasmModule = await wasmLoader(memory, getSIMD, getNonSIMD);

  /**
   * Argon2id hash function
   * @callback computeHash
   * @param {Object} params
   * @param {Uint8Array} params.password - password
   * @param {Uint8Array} params.salt - salt
   * @param {Integer} params.parallelism
   * @param {Integer} params.passes
   * @param {Integer} params.memorySize - in kibibytes
   * @param {Integer} params.tagLength - output tag length
   * @param {Uint8Array} [params.ad] - associated data (optional)
   * @param {Uint8Array} [params.secret] - secret data (optional)
   * @return {Uint8Array} argon2id hash
   */
  const computeHash = (params) => argon2id(params, { instance: wasmModule.instance, memory });

  return computeHash;
}

function _loadWasmModule (sync, filepath, src, imports) {
  function _instantiateOrCompile(source, imports, stream) {
    var instantiateFunc = stream ? WebAssembly.instantiateStreaming : WebAssembly.instantiate;
    var compileFunc = stream ? WebAssembly.compileStreaming : WebAssembly.compile;

    if (imports) {
      return instantiateFunc(source, imports)
    } else {
      return compileFunc(source)
    }
  }

  
var buf = null;


buf = Buffer.from(src, 'base64');



  {
    return _instantiateOrCompile(buf, imports, false)
  }
}

function wasmSIMD(imports){return _loadWasmModule(0, null, 'AGFzbQEAAAABKwdgBH9/f38AYAABf2AAAGADf39/AGAJf39/f39/f39/AX9gAX8AYAF/AX8CEwEDZW52Bm1lbW9yeQIBkAiAgAQDCgkCAwAABAEFBgEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwACAkcyAAMFZ2V0TFoABBlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAgJc3RhY2tTYXZlAAUMc3RhY2tSZXN0b3JlAAYKc3RhY2tBbGxvYwAHCQcBAEEBCwEACs0gCQMAAQtYAQJ/A0AgACAEQQR0IgNqIAIgA2r9AAQAIAEgA2r9AAQA/VH9CwQAIAAgA0EQciIDaiACIANq/QAEACABIANq/QAEAP1R/QsEACAEQQJqIgRBwABHDQALC7ceAgt7A38DQCADIBFBBHQiD2ogASAPav0ABAAgACAPav0ABAD9USIF/QsEACACIA9qIAX9CwQAIAMgD0EQciIPaiABIA9q/QAEACAAIA9q/QAEAP1RIgX9CwQAIAIgD2ogBf0LBAAgEUECaiIRQcAARw0ACwNAIAMgEEEHdGoiAEEQaiAA/QAEcCAA/QAEMCIFIAD9AAQQIgT9zgEgBSAF/Q0AAQIDCAkKCwABAgMICQoLIAQgBP0NAAECAwgJCgsAAQIDCAkKC/3eAUEB/csB/c4BIgT9USIJQSD9ywEgCUEg/c0B/VAiCSAA/QAEUCIG/c4BIAkgCf0NAAECAwgJCgsAAQIDCAkKCyAGIAb9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIGIAX9USIFQSj9ywEgBUEY/c0B/VAiCCAE/c4BIAggCP0NAAECAwgJCgsAAQIDCAkKCyAEIAT9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIKIAogCf1RIgVBMP3LASAFQRD9zQH9UCIFIAb9zgEgBSAF/Q0AAQIDCAkKCwABAgMICQoLIAYgBv0NAAECAwgJCgsAAQIDCAkKC/3eAUEB/csB/c4BIgkgCP1RIgRBAf3LASAEQT/9zQH9UCIMIAD9AARgIAD9AAQgIgQgAP0ABAAiBv3OASAEIAT9DQABAgMICQoLAAECAwgJCgsgBiAG/Q0AAQIDCAkKCwABAgMICQoL/d4BQQH9ywH9zgEiBv1RIghBIP3LASAIQSD9zQH9UCIIIABBQGsiAf0ABAAiB/3OASAIIAj9DQABAgMICQoLAAECAwgJCgsgByAH/Q0AAQIDCAkKCwABAgMICQoL/d4BQQH9ywH9zgEiByAE/VEiBEEo/csBIARBGP3NAf1QIgsgBv3OASALIAv9DQABAgMICQoLAAECAwgJCgsgBiAG/Q0AAQIDCAkKCwABAgMICQoL/d4BQQH9ywH9zgEiBiAI/VEiBEEw/csBIARBEP3NAf1QIgQgB/3OASAEIAT9DQABAgMICQoLAAECAwgJCgsgByAH/Q0AAQIDCAkKCwABAgMICQoL/d4BQQH9ywH9zgEiCCAL/VEiB0EB/csBIAdBP/3NAf1QIg0gDf0NAAECAwQFBgcQERITFBUWF/0NCAkKCwwNDg8YGRobHB0eHyIH/c4BIAcgB/0NAAECAwgJCgsAAQIDCAkKCyAKIAr9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIKIAQgBSAF/Q0AAQIDBAUGBxAREhMUFRYX/Q0ICQoLDA0ODxgZGhscHR4f/VEiC0Eg/csBIAtBIP3NAf1QIgsgCP3OASALIAv9DQABAgMICQoLAAECAwgJCgsgCCAI/Q0AAQIDCAkKCwABAgMICQoL/d4BQQH9ywH9zgEiCCAH/VEiB0Eo/csBIAdBGP3NAf1QIgcgCv3OASAHIAf9DQABAgMICQoLAAECAwgJCgsgCiAK/Q0AAQIDCAkKCwABAgMICQoL/d4BQQH9ywH9zgEiDv0LBAAgACAGIA0gDCAM/Q0AAQIDBAUGBxAREhMUFRYX/Q0ICQoLDA0ODxgZGhscHR4fIgr9zgEgCiAK/Q0AAQIDCAkKCwABAgMICQoLIAYgBv0NAAECAwgJCgsAAQIDCAkKC/3eAUEB/csB/c4BIgYgBSAEIAT9DQABAgMEBQYHEBESExQVFhf9DQgJCgsMDQ4PGBkaGxwdHh/9USIFQSD9ywEgBUEg/c0B/VAiBSAJ/c4BIAUgBf0NAAECAwgJCgsAAQIDCAkKCyAJIAn9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIJIAr9USIEQSj9ywEgBEEY/c0B/VAiCiAG/c4BIAogCv0NAAECAwgJCgsAAQIDCAkKCyAGIAb9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIE/QsEACAAIAQgBf1RIgVBMP3LASAFQRD9zQH9UCIFIA4gC/1RIgRBMP3LASAEQRD9zQH9UCIEIAT9DQABAgMEBQYHEBESExQVFhf9DQgJCgsMDQ4PGBkaGxwdHh/9CwRgIAAgBCAFIAX9DQABAgMEBQYHEBESExQVFhf9DQgJCgsMDQ4PGBkaGxwdHh/9CwRwIAEgBCAI/c4BIAQgBP0NAAECAwgJCgsAAQIDCAkKCyAIIAj9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIE/QsEACAAIAUgCf3OASAFIAX9DQABAgMICQoLAAECAwgJCgsgCSAJ/Q0AAQIDCAkKCwABAgMICQoL/d4BQQH9ywH9zgEiCf0LBFAgACAEIAf9USIFQQH9ywEgBUE//c0B/VAiBSAJIAr9USIEQQH9ywEgBEE//c0B/VAiBCAE/Q0AAQIDBAUGBxAREhMUFRYX/Q0ICQoLDA0ODxgZGhscHR4f/QsEICAAIAQgBSAF/Q0AAQIDBAUGBxAREhMUFRYX/Q0ICQoLDA0ODxgZGhscHR4f/QsEMCAQQQFqIhBBCEcNAAtBACEQA0AgAyAQQQR0aiIAQYABaiAA/QAEgAcgAP0ABIADIgUgAP0ABIABIgT9zgEgBSAF/Q0AAQIDCAkKCwABAgMICQoLIAQgBP0NAAECAwgJCgsAAQIDCAkKC/3eAUEB/csB/c4BIgT9USIJQSD9ywEgCUEg/c0B/VAiCSAA/QAEgAUiBv3OASAJIAn9DQABAgMICQoLAAECAwgJCgsgBiAG/Q0AAQIDCAkKCwABAgMICQoL/d4BQQH9ywH9zgEiBiAF/VEiBUEo/csBIAVBGP3NAf1QIgggBP3OASAIIAj9DQABAgMICQoLAAECAwgJCgsgBCAE/Q0AAQIDCAkKCwABAgMICQoL/d4BQQH9ywH9zgEiCiAKIAn9USIFQTD9ywEgBUEQ/c0B/VAiBSAG/c4BIAUgBf0NAAECAwgJCgsAAQIDCAkKCyAGIAb9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIJIAj9USIEQQH9ywEgBEE//c0B/VAiDCAA/QAEgAYgAP0ABIACIgQgAP0ABAAiBv3OASAEIAT9DQABAgMICQoLAAECAwgJCgsgBiAG/Q0AAQIDCAkKCwABAgMICQoL/d4BQQH9ywH9zgEiBv1RIghBIP3LASAIQSD9zQH9UCIIIAD9AASABCIH/c4BIAggCP0NAAECAwgJCgsAAQIDCAkKCyAHIAf9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIHIAT9USIEQSj9ywEgBEEY/c0B/VAiCyAG/c4BIAsgC/0NAAECAwgJCgsAAQIDCAkKCyAGIAb9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIGIAj9USIEQTD9ywEgBEEQ/c0B/VAiBCAH/c4BIAQgBP0NAAECAwgJCgsAAQIDCAkKCyAHIAf9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIIIAv9USIHQQH9ywEgB0E//c0B/VAiDSAN/Q0AAQIDBAUGBxAREhMUFRYX/Q0ICQoLDA0ODxgZGhscHR4fIgf9zgEgByAH/Q0AAQIDCAkKCwABAgMICQoLIAogCv0NAAECAwgJCgsAAQIDCAkKC/3eAUEB/csB/c4BIgogBCAFIAX9DQABAgMEBQYHEBESExQVFhf9DQgJCgsMDQ4PGBkaGxwdHh/9USILQSD9ywEgC0Eg/c0B/VAiCyAI/c4BIAsgC/0NAAECAwgJCgsAAQIDCAkKCyAIIAj9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIIIAf9USIHQSj9ywEgB0EY/c0B/VAiByAK/c4BIAcgB/0NAAECAwgJCgsAAQIDCAkKCyAKIAr9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIO/QsEACAAIAYgDSAMIAz9DQABAgMEBQYHEBESExQVFhf9DQgJCgsMDQ4PGBkaGxwdHh8iCv3OASAKIAr9DQABAgMICQoLAAECAwgJCgsgBiAG/Q0AAQIDCAkKCwABAgMICQoL/d4BQQH9ywH9zgEiBiAFIAQgBP0NAAECAwQFBgcQERITFBUWF/0NCAkKCwwNDg8YGRobHB0eH/1RIgVBIP3LASAFQSD9zQH9UCIFIAn9zgEgBSAF/Q0AAQIDCAkKCwABAgMICQoLIAkgCf0NAAECAwgJCgsAAQIDCAkKC/3eAUEB/csB/c4BIgkgCv1RIgRBKP3LASAEQRj9zQH9UCIKIAb9zgEgCiAK/Q0AAQIDCAkKCwABAgMICQoLIAYgBv0NAAECAwgJCgsAAQIDCAkKC/3eAUEB/csB/c4BIgT9CwQAIAAgBCAF/VEiBUEw/csBIAVBEP3NAf1QIgUgDiAL/VEiBEEw/csBIARBEP3NAf1QIgQgBP0NAAECAwQFBgcQERITFBUWF/0NCAkKCwwNDg8YGRobHB0eH/0LBIAGIAAgBCAFIAX9DQABAgMEBQYHEBESExQVFhf9DQgJCgsMDQ4PGBkaGxwdHh/9CwSAByAAIAQgCP3OASAEIAT9DQABAgMICQoLAAECAwgJCgsgCCAI/Q0AAQIDCAkKCwABAgMICQoL/d4BQQH9ywH9zgEiBP0LBIAEIAAgBSAJ/c4BIAUgBf0NAAECAwgJCgsAAQIDCAkKCyAJIAn9DQABAgMICQoLAAECAwgJCgv93gFBAf3LAf3OASIJ/QsEgAUgACAEIAf9USIFQQH9ywEgBUE//c0B/VAiBSAJIAr9USIEQQH9ywEgBEE//c0B/VAiBCAE/Q0AAQIDBAUGBxAREhMUFRYX/Q0ICQoLDA0ODxgZGhscHR4f/QsEgAIgACAEIAUgBf0NAAECAwQFBgcQERITFBUWF/0NCAkKCwwNDg8YGRobHB0eH/0LBIADIBBBAWoiEEEIRw0AC0EAIRADQCACIBBBBHQiAGoiASAAIANq/QAEACAB/QAEAP1R/QsEACACIABBEHIiAWoiDyABIANq/QAEACAP/QAEAP1R/QsEACACIABBIHIiAWoiDyABIANq/QAEACAP/QAEAP1R/QsEACACIABBMHIiAGoiASAAIANq/QAEACAB/QAEAP1R/QsEACAQQQRqIhBBwABHDQALCxYAIAAgASACIAMQAiAAIAIgAiADEAILewIBfwF+IAIhCSABNQIAIQogBCAFcgRAIAEoAgQgA3AhCQsgACAJNgIAIAAgB0EBayAFIAQbIAhsIAZBAWtBAEF/IAYbIAIgCUYbaiIBIAVBAWogCGxBACAEG2ogAa0gCiAKfkIgiH5CIIinQX9zaiAHIAhscDYCBCAACwQAIwALBgAgACQACxAAIwAgAGtBcHEiACQAIAALBQBBgAgL', imports)}

function wasmNonSIMD(imports){return _loadWasmModule(0, null, 'AGFzbQEAAAABPwhgBH9/f38AYAABf2AAAGADf39/AGARf39/f39/f39/f39/f39/f38AYAl/f39/f39/f38Bf2ABfwBgAX8BfwITAQNlbnYGbWVtb3J5AgGQCICABAMLCgIDBAAABQEGBwEEBQFwAQICBgkBfwFBkIjAAgsHfQoDeG9yAAEBRwADAkcyAAQFZ2V0TFoABRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALX2luaXRpYWxpemUAABBfX2Vycm5vX2xvY2F0aW9uAAkJc3RhY2tTYXZlAAYMc3RhY2tSZXN0b3JlAAcKc3RhY2tBbGxvYwAICQcBAEEBCwEACssaCgMAAQtQAQJ/A0AgACAEQQN0IgNqIAIgA2opAwAgASADaikDAIU3AwAgACADQQhyIgNqIAIgA2opAwAgASADaikDAIU3AwAgBEECaiIEQYABRw0ACwveDwICfgF/IAAgAUEDdGoiEyATKQMAIhEgACAFQQN0aiIBKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA1BA3RqIgUgESAFKQMAhUIgiSIRNwMAIAAgCUEDdGoiCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIoiSIRNwMAIBMgESATKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAFIBEgBSkDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgASARIAEpAwCFQgGJNwMAIAAgAkEDdGoiDSANKQMAIhEgACAGQQN0aiICKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA5BA3RqIgYgESAGKQMAhUIgiSIRNwMAIAAgCkEDdGoiCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIoiSIRNwMAIA0gESANKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAKIBEgCikDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAiARIAIpAwCFQgGJNwMAIAAgA0EDdGoiDiAOKQMAIhEgACAHQQN0aiIDKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIA9BA3RqIgcgESAHKQMAhUIgiSIRNwMAIAAgC0EDdGoiCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAMgESADKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAHIBEgBykDAIVCMIkiETcDACALIBEgCykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQgGJNwMAIAAgBEEDdGoiDyAPKQMAIhEgACAIQQN0aiIEKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAAIBBBA3RqIgggESAIKQMAhUIgiSIRNwMAIAAgDEEDdGoiACARIAApAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA8gESAPKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAIIBEgCCkDAIVCMIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIBMgEykDACIRIAIpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAggESAIKQMAhUIgiSIRNwMAIAsgESALKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACACIBEgAikDAIVCKIkiETcDACATIBEgEykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgCCARIAgpAwCFQjCJIhE3AwAgCyARIAspAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAIgESACKQMAhUIBiTcDACANIA0pAwAiESADKQMAIhJ8IBFCAYZC/v///x+DIBJC/////w+DfnwiETcDACAFIBEgBSkDAIVCIIkiETcDACAAIBEgACkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgAyARIAMpAwCFQiiJIhE3AwAgDSARIA0pAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAUgESAFKQMAhUIwiSIRNwMAIAAgESAAKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACADIBEgAykDAIVCAYk3AwAgDiAOKQMAIhEgBCkDACISfCARQgGGQv7///8fgyASQv////8Pg358IhE3AwAgBiARIAYpAwCFQiCJIhE3AwAgCSARIAkpAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAQgESAEKQMAhUIoiSIRNwMAIA4gESAOKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACAGIBEgBikDAIVCMIkiETcDACAJIBEgCSkDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgBCARIAQpAwCFQgGJNwMAIA8gDykDACIRIAEpAwAiEnwgEUIBhkL+////H4MgEkL/////D4N+fCIRNwMAIAcgESAHKQMAhUIgiSIRNwMAIAogESAKKQMAIhJ8IBFC/////w+DIBJCAYZC/v///x+DfnwiETcDACABIBEgASkDAIVCKIkiETcDACAPIBEgDykDACISfCARQv////8PgyASQgGGQv7///8fg358IhE3AwAgByARIAcpAwCFQjCJIhE3AwAgCiARIAopAwAiEnwgEUL/////D4MgEkIBhkL+////H4N+fCIRNwMAIAEgESABKQMAhUIBiTcDAAvdCAEPfwNAIAIgBUEDdCIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAIgBkEIciIGaiABIAZqKQMAIAAgBmopAwCFNwMAIAVBAmoiBUGAAUcNAAsDQCADIARBA3QiAGogACACaikDADcDACADIARBAXIiAEEDdCIBaiABIAJqKQMANwMAIAMgBEECciIBQQN0IgVqIAIgBWopAwA3AwAgAyAEQQNyIgVBA3QiBmogAiAGaikDADcDACADIARBBHIiBkEDdCIHaiACIAdqKQMANwMAIAMgBEEFciIHQQN0IghqIAIgCGopAwA3AwAgAyAEQQZyIghBA3QiCWogAiAJaikDADcDACADIARBB3IiCUEDdCIKaiACIApqKQMANwMAIAMgBEEIciIKQQN0IgtqIAIgC2opAwA3AwAgAyAEQQlyIgtBA3QiDGogAiAMaikDADcDACADIARBCnIiDEEDdCINaiACIA1qKQMANwMAIAMgBEELciINQQN0Ig5qIAIgDmopAwA3AwAgAyAEQQxyIg5BA3QiD2ogAiAPaikDADcDACADIARBDXIiD0EDdCIQaiACIBBqKQMANwMAIAMgBEEOciIQQQN0IhFqIAIgEWopAwA3AwAgAyAEQQ9yIhFBA3QiEmogAiASaikDADcDACADIARB//8DcSAAQf//A3EgAUH//wNxIAVB//8DcSAGQf//A3EgB0H//wNxIAhB//8DcSAJQf//A3EgCkH//wNxIAtB//8DcSAMQf//A3EgDUH//wNxIA5B//8DcSAPQf//A3EgEEH//wNxIBFB//8DcRACIARB8ABJIQAgBEEQaiEEIAANAAtBACEBIANBAEEBQRBBEUEgQSFBMEExQcAAQcEAQdAAQdEAQeAAQeEAQfAAQfEAEAIgA0ECQQNBEkETQSJBI0EyQTNBwgBBwwBB0gBB0wBB4gBB4wBB8gBB8wAQAiADQQRBBUEUQRVBJEElQTRBNUHEAEHFAEHUAEHVAEHkAEHlAEH0AEH1ABACIANBBkEHQRZBF0EmQSdBNkE3QcYAQccAQdYAQdcAQeYAQecAQfYAQfcAEAIgA0EIQQlBGEEZQShBKUE4QTlByABByQBB2ABB2QBB6ABB6QBB+ABB+QAQAiADQQpBC0EaQRtBKkErQTpBO0HKAEHLAEHaAEHbAEHqAEHrAEH6AEH7ABACIANBDEENQRxBHUEsQS1BPEE9QcwAQc0AQdwAQd0AQewAQe0AQfwAQf0AEAIgA0EOQQ9BHkEfQS5BL0E+QT9BzgBBzwBB3gBB3wBB7gBB7wBB/gBB/wAQAgNAIAIgAUEDdCIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAiAAQQhyIgRqIgUgAyAEaikDACAFKQMAhTcDACACIABBEHIiBGoiBSADIARqKQMAIAUpAwCFNwMAIAIgAEEYciIAaiIEIAAgA2opAwAgBCkDAIU3AwAgAUEEaiIBQYABRw0ACwsWACAAIAEgAiADEAMgACACIAIgAxADC3sCAX8BfiACIQkgATUCACEKIAQgBXIEQCABKAIEIANwIQkLIAAgCTYCACAAIAdBAWsgBSAEGyAIbCAGQQFrQQBBfyAGGyACIAlGG2oiASAFQQFqIAhsQQAgBBtqIAGtIAogCn5CIIh+QiCIp0F/c2ogByAIbHA2AgQgAAsEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwUAQYAICw==', imports)}

const loadWasm = async () => setupWasm(
  (instanceObject) => wasmSIMD(instanceObject),
  (instanceObject) => wasmNonSIMD(instanceObject),
);

var index$2 = /*#__PURE__*/Object.freeze({
  __proto__: null,
  default: loadWasm
});

function getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

/* 
  bzip2.js - a small bzip2 decompression implementation
  
  Copyright 2011 by antimatter15 (antimatter15@gmail.com)
  
  Based on micro-bunzip by Rob Landley (rob@landley.net).

  Copyright (c) 2011 by antimatter15 (antimatter15@gmail.com).

  Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the "Software"),
  to deal in the Software without restriction, including without limitation
  the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included
  in all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
  THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

var bzip2_1;
var hasRequiredBzip2;

function requireBzip2 () {
	if (hasRequiredBzip2) return bzip2_1;
	hasRequiredBzip2 = 1;
	function Bzip2Error(message) {
	    this.name = 'Bzip2Error';
	    this.message = message;
	    this.stack = (new Error()).stack;
	}
	Bzip2Error.prototype = new Error;
	 
	var message = {
	    Error: function(message) {throw new Bzip2Error(message);}
	};

	var bzip2 = {};
	bzip2.Bzip2Error = Bzip2Error;

	bzip2.crcTable =
	[
	   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
	];

	bzip2.array = function(bytes) {
	    var bit = 0, byte = 0;
	    var BITMASK = [0, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF ];
	    return function(n) {
	        var result = 0;
	        while(n > 0) {
	            var left = 8 - bit;
	            if (n >= left) {
	                result <<= left;
	                result |= (BITMASK[left] & bytes[byte++]);
	                bit = 0;
	                n -= left;
	            } else {
	                result <<= n;
	                result |= ((bytes[byte] & (BITMASK[n] << (8 - n - bit))) >> (8 - n - bit));
	                bit += n;
	                n = 0;
	            }
	        }
	        return result;
	    }
	};

	    
	bzip2.simple = function(srcbuffer, stream) {
	    var bits = bzip2.array(srcbuffer);
	    var size = bzip2.header(bits);
	    var ret = false;
	    var bufsize = 100000 * size;
	    var buf = new Int32Array(bufsize);
	    
	    do {
	        ret = bzip2.decompress(bits, stream, buf, bufsize);        
	    } while(!ret);
	};

	bzip2.header = function(bits) {
	    this.byteCount = new Int32Array(256);
	    this.symToByte = new Uint8Array(256);
	    this.mtfSymbol = new Int32Array(256);
	    this.selectors = new Uint8Array(0x8000);

	    if (bits(8*3) != 4348520) message.Error("No magic number found");

	    var i = bits(8) - 48;
	    if (i < 1 || i > 9) message.Error("Not a BZIP archive");
	    return i;
	};


	//takes a function for reading the block data (starting with 0x314159265359)
	//a block size (0-9) (optional, defaults to 9)
	//a length at which to stop decompressing and return the output
	bzip2.decompress = function(bits, stream, buf, bufsize, streamCRC) {
	    var MAX_HUFCODE_BITS = 20;
	    var MAX_SYMBOLS = 258;
	    var SYMBOL_RUNA = 0;
	    var SYMBOL_RUNB = 1;
	    var GROUP_SIZE = 50;
	    var crc = 0 ^ (-1);
	    
	    for(var h = '', i = 0; i < 6; i++) h += bits(8).toString(16);
	    if (h == "177245385090") {
	      var finalCRC = bits(32)|0;
	      if (finalCRC !== streamCRC) message.Error("Error in bzip2: crc32 do not match");
	      // align stream to byte
	      bits(null);
	      return null; // reset streamCRC for next call
	    }
	    if (h != "314159265359") message.Error("Invalid bzip data");
	    var crcblock = bits(32)|0; // CRC code
	    if (bits(1)) message.Error("unsupported obsolete version");
	    var origPtr = bits(24);
	    if (origPtr > bufsize) message.Error("Initial position larger than buffer size");
	    var t = bits(16);
	    var symTotal = 0;
	    for (i = 0; i < 16; i++) {
	        if (t & (1 << (15 - i))) {
	            var k = bits(16);
	            for(j = 0; j < 16; j++) {
	                if (k & (1 << (15 - j))) {
	                    this.symToByte[symTotal++] = (16 * i) + j;
	                }
	            }
	        }
	    }

	    var groupCount = bits(3);
	    if (groupCount < 2 || groupCount > 6) message.Error("Invalid bzip data");
	    var nSelectors = bits(15);
	    if (nSelectors == 0) message.Error("Invalid bzip data");
	    for(var i = 0; i < groupCount; i++) this.mtfSymbol[i] = i;

	    for(var i = 0; i < nSelectors; i++) {
	        for(var j = 0; bits(1); j++) if (j >= groupCount) message.Error("Invalid bzip data");
	        var uc = this.mtfSymbol[j];
	        for(var k = j-1; k>=0; k--) {
	            this.mtfSymbol[k+1] = this.mtfSymbol[k];
	        }
	        this.mtfSymbol[0] = uc;
	        this.selectors[i] = uc;
	    }

	    var symCount = symTotal + 2;
	    var groups = [];
	    var length = new Uint8Array(MAX_SYMBOLS),
	    temp = new Uint16Array(MAX_HUFCODE_BITS+1);

	    var hufGroup;

	    for(var j = 0; j < groupCount; j++) {
	        t = bits(5); //lengths
	        for(var i = 0; i < symCount; i++) {
	            while(true){
	                if (t < 1 || t > MAX_HUFCODE_BITS) message.Error("Invalid bzip data");
	                if (!bits(1)) break;
	                if (!bits(1)) t++;
	                else t--;
	            }
	            length[i] = t;
	        }
	        var  minLen,  maxLen;
	        minLen = maxLen = length[0];
	        for(var i = 1; i < symCount; i++) {
	            if (length[i] > maxLen) maxLen = length[i];
	            else if (length[i] < minLen) minLen = length[i];
	        }
	        hufGroup = groups[j] = {};
	        hufGroup.permute = new Int32Array(MAX_SYMBOLS);
	        hufGroup.limit = new Int32Array(MAX_HUFCODE_BITS + 1);
	        hufGroup.base = new Int32Array(MAX_HUFCODE_BITS + 1);

	        hufGroup.minLen = minLen;
	        hufGroup.maxLen = maxLen;
	        var base = hufGroup.base;
	        var limit = hufGroup.limit;
	        var pp = 0;
	        for(var i = minLen; i <= maxLen; i++)
	        for(var t = 0; t < symCount; t++)
	        if (length[t] == i) hufGroup.permute[pp++] = t;
	        for(i = minLen; i <= maxLen; i++) temp[i] = limit[i] = 0;
	        for(i = 0; i < symCount; i++) temp[length[i]]++;
	        pp = t = 0;
	        for(i = minLen; i < maxLen; i++) {
	            pp += temp[i];
	            limit[i] = pp - 1;
	            pp <<= 1;
	            base[i+1] = pp - (t += temp[i]);
	        }
	        limit[maxLen] = pp + temp[maxLen] - 1;
	        base[minLen] = 0;
	    }

	    for(var i = 0; i < 256; i++) { 
	        this.mtfSymbol[i] = i;
	        this.byteCount[i] = 0;
	    }
	    var runPos, count, symCount, selector;
	    runPos = count = symCount = selector = 0;    
	    while(true) {
	        if (!(symCount--)) {
	            symCount = GROUP_SIZE - 1;
	            if (selector >= nSelectors) message.Error("Invalid bzip data");
	            hufGroup = groups[this.selectors[selector++]];
	            base = hufGroup.base;
	            limit = hufGroup.limit;
	        }
	        i = hufGroup.minLen;
	        j = bits(i);
	        while(true) {
	            if (i > hufGroup.maxLen) message.Error("Invalid bzip data");
	            if (j <= limit[i]) break;
	            i++;
	            j = (j << 1) | bits(1);
	        }
	        j -= base[i];
	        if (j < 0 || j >= MAX_SYMBOLS) message.Error("Invalid bzip data");
	        var nextSym = hufGroup.permute[j];
	        if (nextSym == SYMBOL_RUNA || nextSym == SYMBOL_RUNB) {
	            if (!runPos){
	                runPos = 1;
	                t = 0;
	            }
	            if (nextSym == SYMBOL_RUNA) t += runPos;
	            else t += 2 * runPos;
	            runPos <<= 1;
	            continue;
	        }
	        if (runPos) {
	            runPos = 0;
	            if (count + t > bufsize) message.Error("Invalid bzip data");
	            uc = this.symToByte[this.mtfSymbol[0]];
	            this.byteCount[uc] += t;
	            while(t--) buf[count++] = uc;
	        }
	        if (nextSym > symTotal) break;
	        if (count >= bufsize) message.Error("Invalid bzip data");
	        i = nextSym - 1;
	        uc = this.mtfSymbol[i];
	        for(var k = i-1; k>=0; k--) {
	            this.mtfSymbol[k+1] = this.mtfSymbol[k];
	        }
	        this.mtfSymbol[0] = uc;
	        uc = this.symToByte[uc];
	        this.byteCount[uc]++;
	        buf[count++] = uc;
	    }
	    if (origPtr < 0 || origPtr >= count) message.Error("Invalid bzip data");
	    var j = 0;
	    for(var i = 0; i < 256; i++) {
	        k = j + this.byteCount[i];
	        this.byteCount[i] = j;
	        j = k;
	    }
	    for(var i = 0; i < count; i++) {
	        uc = buf[i] & 0xff;
	        buf[this.byteCount[uc]] |= (i << 8);
	        this.byteCount[uc]++;
	    }
	    var pos = 0, current = 0, run = 0;
	    if (count) {
	        pos = buf[origPtr];
	        current = (pos & 0xff);
	        pos >>= 8;
	        run = -1;
	    }
	    count = count;
	    var copies, previous, outbyte;
	    while(count) {
	        count--;
	        previous = current;
	        pos = buf[pos];
	        current = pos & 0xff;
	        pos >>= 8;
	        if (run++ == 3) {
	            copies = current;
	            outbyte = previous;
	            current = -1;
	        } else {
	            copies = 1;
	            outbyte = current;
	        }
	        while(copies--) {
	            crc = ((crc << 8) ^ this.crcTable[((crc>>24) ^ outbyte) & 0xFF])&0xFFFFFFFF; // crc32
	            stream(outbyte);
	        }
	        if (current != previous) run = 0;
	    }

	    crc = (crc ^ (-1)) >>> 0;
	    if ((crc|0) != (crcblock|0)) message.Error("Error in bzip2: crc32 do not match");
	    streamCRC = (crc ^ ((streamCRC << 1) | (streamCRC >>> 31))) & 0xFFFFFFFF;
	    return streamCRC;
	};

	bzip2_1 = bzip2;
	return bzip2_1;
}

var bit_iterator;
var hasRequiredBit_iterator;

function requireBit_iterator () {
	if (hasRequiredBit_iterator) return bit_iterator;
	hasRequiredBit_iterator = 1;
	var BITMASK = [0, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];

	// returns a function that reads bits.
	// takes a buffer iterator as input
	bit_iterator = function bitIterator(nextBuffer) {
	    var bit = 0, byte = 0;
	    var bytes = nextBuffer();
	    var f = function(n) {
	        if (n === null && bit != 0) {  // align to byte boundary
	            bit = 0;
	            byte++;
	            return;
	        }
	        var result = 0;
	        while(n > 0) {
	            if (byte >= bytes.length) {
	                byte = 0;
	                bytes = nextBuffer();
	            }
	            var left = 8 - bit;
	            if (bit === 0 && n > 0)
	                f.bytesRead++;
	            if (n >= left) {
	                result <<= left;
	                result |= (BITMASK[left] & bytes[byte++]);
	                bit = 0;
	                n -= left;
	            } else {
	                result <<= n;
	                result |= ((bytes[byte] & (BITMASK[n] << (8 - n - bit))) >> (8 - n - bit));
	                bit += n;
	                n = 0;
	            }
	        }
	        return result;
	    };
	    f.bytesRead = 0;
	    return f;
	};
	return bit_iterator;
}

var unbzip2Stream_1;
var hasRequiredUnbzip2Stream;

function requireUnbzip2Stream () {
	if (hasRequiredUnbzip2Stream) return unbzip2Stream_1;
	hasRequiredUnbzip2Stream = 1;
	const bz2 = requireBzip2();
	const bitIterator = requireBit_iterator();

	unbzip2Stream_1 = unbzip2Stream;

	function unbzip2Stream(input, maxDecompressedBytes = Infinity) {
	    const bufferQueue = [];
	    let hasBytes = 0;
	    let blockSize = 0;
	    let broken = false;
	    let hasAllData = false;
	    let bitReader = null;
	    let streamCRC = null;
	    let totalOut = 0; // cumulative decompressed bytes across all blocks

	    function decompressBlock(push){
	        if(!blockSize) {
	            blockSize = bz2.header(bitReader);
	            streamCRC = 0;
	            return false;
	        } else {
	            const bufsize = 100000 * blockSize;
	            const buf = new Int32Array(bufsize);

	            // Growable output buffer
	            let chunk = new Uint8Array(32768);
	            let chunkLen = 0;
	            const f = function(b) {
	                if (++totalOut > maxDecompressedBytes) {
	                    throw new Error('Maximum decompressed size exceeded');
	                }
	                if (chunkLen === chunk.length) {
	                    // Grow the chunk buffer
	                    const newLen = Math.min(chunk.length * 2, chunkLen + (maxDecompressedBytes - totalOut) + 1);
	                    const bigger = new Uint8Array(newLen);
	                    bigger.set(chunk);
	                    chunk = bigger;
	                }
	                chunk[chunkLen++] = b;
	            };

	            streamCRC = bz2.decompress(bitReader, f, buf, bufsize, streamCRC);
	            if (streamCRC === null) {
	                // reset for next bzip2 header
	                blockSize = 0;
	                return false;
	            } else {
	                push(chunk.subarray(0, chunkLen));
	                return true;
	            }
	        }
	    }

	    let outlength = 0;
	    function decompressAndQueue(controller) {
	        if (broken) return;
	        try {
	            return decompressBlock(function(d) {
	                controller.enqueue(d);
	                if (d !== null) {
	                    outlength += d.length;
	                }
	            });
	        } catch(e) {
	            controller.error(e);
	            broken = true;
	            return true;
	        }
	    }

	    let inputReader;
	    return new ReadableStream({
	        start() {
	            inputReader = input.getReader();
	        },
	        async pull(controller) {
	            try {
	                while (true) {
	                    while (!(
	                        hasAllData ||
	                            (
	                                bitReader &&
	                                hasBytes - bitReader.bytesRead + 1 >= 25000 + 100000 * (blockSize || 4)
	                            )
	                    )) {
	                        const { value, done } = await inputReader.read();
	                        if (!done) {
	                            bufferQueue.push(value);
	                            hasBytes += value.length;
	                            if (bitReader === null) {
	                                bitReader = bitIterator(function() {
	                                    return bufferQueue.shift();
	                                });
	                            }
	                        } else {
	                            hasAllData = true;
	                        }
	                    }
	                    while (
	                        hasAllData ?
	                            (bitReader && hasBytes > bitReader.bytesRead) :
	                            (
	                                bitReader &&
	                                hasBytes - bitReader.bytesRead + 1 >= 25000 + 100000 * (blockSize || 4)
	                            )
	                    ) {
	                        //console.error('decompressing with', hasBytes - bitReader.bytesRead + 1, 'bytes in buffer');
	                        if (decompressAndQueue(controller)) {
	                            return; // `pull` will get called again
	                        }
	                    }
	                    if (hasAllData && !broken && (!bitReader || hasBytes <= bitReader.bytesRead)) {
	                        if (streamCRC === null) {
	                            controller.close();
	                        } else {
	                            controller.error(new Error("input stream ended prematurely"));
	                        }
	                        return;
	                    }
	                }
	            } catch (e) {
	                controller.error(e);
	            }
	        },
	        async cancel(reason) {
	            await inputReader.abort(reason);
	        }
	    }, { highWaterMark: 0 });
	}
	return unbzip2Stream_1;
}

var unbzip2StreamExports = requireUnbzip2Stream();
var index = /*@__PURE__*/getDefaultExportFromCjs(unbzip2StreamExports);

var index$1 = /*#__PURE__*/_mergeNamespaces({
  __proto__: null,
  default: index
}, [unbzip2StreamExports]);

export { AEADEncryptedDataPacket, CleartextMessage, CompressedDataPacket, GrammarError, LiteralDataPacket, MarkerPacket, Message, OnePassSignaturePacket, PacketList, PaddingPacket, PrivateKey, PublicKey, PublicKeyEncryptedSessionKeyPacket, PublicKeyPacket, PublicSubkeyPacket, SecretKeyPacket, SecretSubkeyPacket, Signature, SignaturePacket, Subkey, SymEncryptedIntegrityProtectedDataPacket, SymEncryptedSessionKeyPacket, SymmetricallyEncryptedDataPacket, TrustPacket, UnparseablePacket, UserAttributePacket, UserIDPacket, armor, config, createCleartextMessage, createMessage, decrypt, decryptKey, decryptSessionKeys, encrypt, encryptKey, encryptSessionKey, enums, generateKey, generateSessionKey, readCleartextMessage, readKey, readKeys, readMessage, readPrivateKey, readPrivateKeys, readSignature, reformatKey, revokeKey, sign, unarmor, verify };