UNPKG

1.48 MBJavaScriptView Raw
1/*! OpenPGP.js v5.11.0 - 2023-10-25 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */
2const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
3
4const doneWritingPromise = Symbol('doneWritingPromise');
5const doneWritingResolve = Symbol('doneWritingResolve');
6const doneWritingReject = Symbol('doneWritingReject');
7
8const readingIndex = Symbol('readingIndex');
9
10class ArrayStream extends Array {
11 constructor() {
12 super();
13 this[doneWritingPromise] = new Promise((resolve, reject) => {
14 this[doneWritingResolve] = resolve;
15 this[doneWritingReject] = reject;
16 });
17 this[doneWritingPromise].catch(() => {});
18 }
19}
20
21ArrayStream.prototype.getReader = function() {
22 if (this[readingIndex] === undefined) {
23 this[readingIndex] = 0;
24 }
25 return {
26 read: async () => {
27 await this[doneWritingPromise];
28 if (this[readingIndex] === this.length) {
29 return { value: undefined, done: true };
30 }
31 return { value: this[this[readingIndex]++], done: false };
32 }
33 };
34};
35
36ArrayStream.prototype.readToEnd = async function(join) {
37 await this[doneWritingPromise];
38 const result = join(this.slice(this[readingIndex]));
39 this.length = 0;
40 return result;
41};
42
43ArrayStream.prototype.clone = function() {
44 const clone = new ArrayStream();
45 clone[doneWritingPromise] = this[doneWritingPromise].then(() => {
46 clone.push(...this);
47 });
48 return clone;
49};
50
51/**
52 * Check whether data is an ArrayStream
53 * @param {Any} input data to check
54 * @returns {boolean}
55 */
56function isArrayStream(input) {
57 return input && input.getReader && Array.isArray(input);
58}
59
60/**
61 * A wrapper class over the native WritableStreamDefaultWriter.
62 * It also lets you "write data to" array streams instead of streams.
63 * @class
64 */
65function Writer(input) {
66 if (!isArrayStream(input)) {
67 const writer = input.getWriter();
68 const releaseLock = writer.releaseLock;
69 writer.releaseLock = () => {
70 writer.closed.catch(function() {});
71 releaseLock.call(writer);
72 };
73 return writer;
74 }
75 this.stream = input;
76}
77
78/**
79 * Write a chunk of data.
80 * @returns {Promise<undefined>}
81 * @async
82 */
83Writer.prototype.write = async function(chunk) {
84 this.stream.push(chunk);
85};
86
87/**
88 * Close the stream.
89 * @returns {Promise<undefined>}
90 * @async
91 */
92Writer.prototype.close = async function() {
93 this.stream[doneWritingResolve]();
94};
95
96/**
97 * Error the stream.
98 * @returns {Promise<Object>}
99 * @async
100 */
101Writer.prototype.abort = async function(reason) {
102 this.stream[doneWritingReject](reason);
103 return reason;
104};
105
106/**
107 * Release the writer's lock.
108 * @returns {undefined}
109 * @async
110 */
111Writer.prototype.releaseLock = function() {};
112
113const isNode = typeof globalThis.process === 'object' &&
114 typeof globalThis.process.versions === 'object';
115
116const NodeReadableStream = isNode && void('stream').Readable;
117
118/**
119 * Check whether data is a Stream, and if so of which type
120 * @param {Any} input data to check
121 * @returns {'web'|'ponyfill'|'node'|'array'|'web-like'|false}
122 */
123function isStream(input) {
124 if (isArrayStream(input)) {
125 return 'array';
126 }
127 if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {
128 return 'web';
129 }
130 if (ReadableStream && ReadableStream.prototype.isPrototypeOf(input)) {
131 return 'ponyfill';
132 }
133 if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) {
134 return 'node';
135 }
136 if (input && input.getReader) {
137 return 'web-like';
138 }
139 return false;
140}
141
142/**
143 * Check whether data is a Uint8Array
144 * @param {Any} input data to check
145 * @returns {Boolean}
146 */
147function isUint8Array(input) {
148 return Uint8Array.prototype.isPrototypeOf(input);
149}
150
151/**
152 * Concat Uint8Arrays
153 * @param {Array<Uint8array>} Array of Uint8Arrays to concatenate
154 * @returns {Uint8array} Concatenated array
155 */
156function concatUint8Array(arrays) {
157 if (arrays.length === 1) return arrays[0];
158
159 let totalLength = 0;
160 for (let i = 0; i < arrays.length; i++) {
161 if (!isUint8Array(arrays[i])) {
162 throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');
163 }
164
165 totalLength += arrays[i].length;
166 }
167
168 const result = new Uint8Array(totalLength);
169 let pos = 0;
170 arrays.forEach(function (element) {
171 result.set(element, pos);
172 pos += element.length;
173 });
174
175 return result;
176}
177
178const NodeBuffer = isNode && void('buffer').Buffer;
179const NodeReadableStream$1 = isNode && void('stream').Readable;
180
181/**
182 * Web / node stream conversion functions
183 * From https://github.com/gwicke/node-web-streams
184 */
185
186let nodeToWeb;
187let webToNode;
188
189if (NodeReadableStream$1) {
190
191 /**
192 * Convert a Node Readable Stream to a Web ReadableStream
193 * @param {Readable} nodeStream
194 * @returns {ReadableStream}
195 */
196 nodeToWeb = function(nodeStream) {
197 let canceled = false;
198 return new ReadableStream({
199 start(controller) {
200 nodeStream.pause();
201 nodeStream.on('data', chunk => {
202 if (canceled) {
203 return;
204 }
205 if (NodeBuffer.isBuffer(chunk)) {
206 chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
207 }
208 controller.enqueue(chunk);
209 nodeStream.pause();
210 });
211 nodeStream.on('end', () => {
212 if (canceled) {
213 return;
214 }
215 controller.close();
216 });
217 nodeStream.on('error', e => controller.error(e));
218 },
219 pull() {
220 nodeStream.resume();
221 },
222 cancel(reason) {
223 canceled = true;
224 nodeStream.destroy(reason);
225 }
226 });
227 };
228
229
230 class NodeReadable extends NodeReadableStream$1 {
231 constructor(webStream, options) {
232 super(options);
233 this._reader = getReader(webStream);
234 }
235
236 async _read(size) {
237 try {
238 while (true) {
239 const { done, value } = await this._reader.read();
240 if (done) {
241 this.push(null);
242 break;
243 }
244 if (!this.push(value)) {
245 break;
246 }
247 }
248 } catch (e) {
249 this.destroy(e);
250 }
251 }
252
253 async _destroy(error, callback) {
254 this._reader.cancel(error).then(callback, callback);
255 }
256 }
257
258 /**
259 * Convert a Web ReadableStream to a Node Readable Stream
260 * @param {ReadableStream} webStream
261 * @param {Object} options
262 * @returns {Readable}
263 */
264 webToNode = function(webStream, options) {
265 return new NodeReadable(webStream, options);
266 };
267
268}
269
270const doneReadingSet = new WeakSet();
271const externalBuffer = Symbol('externalBuffer');
272
273/**
274 * A wrapper class over the native ReadableStreamDefaultReader.
275 * This additionally implements pushing back data on the stream, which
276 * lets us implement peeking and a host of convenience functions.
277 * It also lets you read data other than streams, such as a Uint8Array.
278 * @class
279 */
280function Reader(input) {
281 this.stream = input;
282 if (input[externalBuffer]) {
283 this[externalBuffer] = input[externalBuffer].slice();
284 }
285 if (isArrayStream(input)) {
286 const reader = input.getReader();
287 this._read = reader.read.bind(reader);
288 this._releaseLock = () => {};
289 this._cancel = async () => {};
290 return;
291 }
292 let streamType = isStream(input);
293 if (streamType === 'node') {
294 input = nodeToWeb(input);
295 }
296 if (streamType) {
297 const reader = input.getReader();
298 this._read = reader.read.bind(reader);
299 this._releaseLock = () => {
300 reader.closed.catch(function() {});
301 reader.releaseLock();
302 };
303 this._cancel = reader.cancel.bind(reader);
304 return;
305 }
306 let doneReading = false;
307 this._read = async () => {
308 if (doneReading || doneReadingSet.has(input)) {
309 return { value: undefined, done: true };
310 }
311 doneReading = true;
312 return { value: input, done: false };
313 };
314 this._releaseLock = () => {
315 if (doneReading) {
316 try {
317 doneReadingSet.add(input);
318 } catch(e) {}
319 }
320 };
321}
322
323/**
324 * Read a chunk of data.
325 * @returns {Promise<Object>} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }
326 * @async
327 */
328Reader.prototype.read = async function() {
329 if (this[externalBuffer] && this[externalBuffer].length) {
330 const value = this[externalBuffer].shift();
331 return { done: false, value };
332 }
333 return this._read();
334};
335
336/**
337 * Allow others to read the stream.
338 */
339Reader.prototype.releaseLock = function() {
340 if (this[externalBuffer]) {
341 this.stream[externalBuffer] = this[externalBuffer];
342 }
343 this._releaseLock();
344};
345
346/**
347 * Cancel the stream.
348 */
349Reader.prototype.cancel = function(reason) {
350 return this._cancel(reason);
351};
352
353/**
354 * Read up to and including the first \n character.
355 * @returns {Promise<String|Undefined>}
356 * @async
357 */
358Reader.prototype.readLine = async function() {
359 let buffer = [];
360 let returnVal;
361 while (!returnVal) {
362 let { done, value } = await this.read();
363 value += '';
364 if (done) {
365 if (buffer.length) return concat(buffer);
366 return;
367 }
368 const lineEndIndex = value.indexOf('\n') + 1;
369 if (lineEndIndex) {
370 returnVal = concat(buffer.concat(value.substr(0, lineEndIndex)));
371 buffer = [];
372 }
373 if (lineEndIndex !== value.length) {
374 buffer.push(value.substr(lineEndIndex));
375 }
376 }
377 this.unshift(...buffer);
378 return returnVal;
379};
380
381/**
382 * Read a single byte/character.
383 * @returns {Promise<Number|String|Undefined>}
384 * @async
385 */
386Reader.prototype.readByte = async function() {
387 const { done, value } = await this.read();
388 if (done) return;
389 const byte = value[0];
390 this.unshift(slice(value, 1));
391 return byte;
392};
393
394/**
395 * Read a specific amount of bytes/characters, unless the stream ends before that amount.
396 * @returns {Promise<Uint8Array|String|Undefined>}
397 * @async
398 */
399Reader.prototype.readBytes = async function(length) {
400 const buffer = [];
401 let bufferLength = 0;
402 while (true) {
403 const { done, value } = await this.read();
404 if (done) {
405 if (buffer.length) return concat(buffer);
406 return;
407 }
408 buffer.push(value);
409 bufferLength += value.length;
410 if (bufferLength >= length) {
411 const bufferConcat = concat(buffer);
412 this.unshift(slice(bufferConcat, length));
413 return slice(bufferConcat, 0, length);
414 }
415 }
416};
417
418/**
419 * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.
420 * @returns {Promise<Uint8Array|String|Undefined>}
421 * @async
422 */
423Reader.prototype.peekBytes = async function(length) {
424 const bytes = await this.readBytes(length);
425 this.unshift(bytes);
426 return bytes;
427};
428
429/**
430 * Push data to the front of the stream.
431 * Data must have been read in the last call to read*.
432 * @param {...(Uint8Array|String|Undefined)} values
433 */
434Reader.prototype.unshift = function(...values) {
435 if (!this[externalBuffer]) {
436 this[externalBuffer] = [];
437 }
438 if (
439 values.length === 1 && isUint8Array(values[0]) &&
440 this[externalBuffer].length && values[0].length &&
441 this[externalBuffer][0].byteOffset >= values[0].length
442 ) {
443 this[externalBuffer][0] = new Uint8Array(
444 this[externalBuffer][0].buffer,
445 this[externalBuffer][0].byteOffset - values[0].length,
446 this[externalBuffer][0].byteLength + values[0].length
447 );
448 return;
449 }
450 this[externalBuffer].unshift(...values.filter(value => value && value.length));
451};
452
453/**
454 * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).
455 * @param {Function} join
456 * @returns {Promise<Uint8array|String|Any>} the return value of join()
457 * @async
458 */
459Reader.prototype.readToEnd = async function(join=concat) {
460 const result = [];
461 while (true) {
462 const { done, value } = await this.read();
463 if (done) break;
464 result.push(value);
465 }
466 return join(result);
467};
468
469let { ReadableStream, WritableStream, TransformStream } = globalThis;
470
471let toPonyfillReadable, toNativeReadable;
472
473async function loadStreamsPonyfill() {
474 if (TransformStream) {
475 return;
476 }
477
478 const [ponyfill, adapter] = await Promise.all([
479 Promise.resolve().then(function () { return ponyfill_es6; }),
480 Promise.resolve().then(function () { return webStreamsAdapter; })
481 ]);
482
483 ({ ReadableStream, WritableStream, TransformStream } = ponyfill);
484
485 const { createReadableStreamWrapper } = adapter;
486
487 if (globalThis.ReadableStream && ReadableStream !== globalThis.ReadableStream) {
488 toPonyfillReadable = createReadableStreamWrapper(ReadableStream);
489 toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream);
490 }
491}
492
493const NodeBuffer$1 = isNode && void('buffer').Buffer;
494
495/**
496 * Convert data to Stream
497 * @param {ReadableStream|Uint8array|String} input data to convert
498 * @returns {ReadableStream} Converted data
499 */
500function toStream(input) {
501 let streamType = isStream(input);
502 if (streamType === 'node') {
503 return nodeToWeb(input);
504 }
505 if (streamType === 'web' && toPonyfillReadable) {
506 return toPonyfillReadable(input);
507 }
508 if (streamType) {
509 return input;
510 }
511 return new ReadableStream({
512 start(controller) {
513 controller.enqueue(input);
514 controller.close();
515 }
516 });
517}
518
519/**
520 * Convert data to ArrayStream
521 * @param {Object} input data to convert
522 * @returns {ArrayStream} Converted data
523 */
524function toArrayStream(input) {
525 if (isStream(input)) {
526 return input;
527 }
528 const stream = new ArrayStream();
529 (async () => {
530 const writer = getWriter(stream);
531 await writer.write(input);
532 await writer.close();
533 })();
534 return stream;
535}
536
537/**
538 * Concat a list of Uint8Arrays, Strings or Streams
539 * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
540 * @param {Array<Uint8array|String|ReadableStream>} Array of Uint8Arrays/Strings/Streams to concatenate
541 * @returns {Uint8array|String|ReadableStream} Concatenated array
542 */
543function concat(list) {
544 if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {
545 return concatStream(list);
546 }
547 if (list.some(stream => isArrayStream(stream))) {
548 return concatArrayStream(list);
549 }
550 if (typeof list[0] === 'string') {
551 return list.join('');
552 }
553 if (NodeBuffer$1 && NodeBuffer$1.isBuffer(list[0])) {
554 return NodeBuffer$1.concat(list);
555 }
556 return concatUint8Array(list);
557}
558
559/**
560 * Concat a list of Streams
561 * @param {Array<ReadableStream|Uint8array|String>} list Array of Uint8Arrays/Strings/Streams to concatenate
562 * @returns {ReadableStream} Concatenated list
563 */
564function concatStream(list) {
565 list = list.map(toStream);
566 const transform = transformWithCancel(async function(reason) {
567 await Promise.all(transforms.map(stream => cancel(stream, reason)));
568 });
569 let prev = Promise.resolve();
570 const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {
571 prev = prev.then(() => pipe(readable, transform.writable, {
572 preventClose: i !== list.length - 1
573 }));
574 return prev;
575 }));
576 return transform.readable;
577}
578
579/**
580 * Concat a list of ArrayStreams
581 * @param {Array<ArrayStream|Uint8array|String>} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate
582 * @returns {ArrayStream} Concatenated streams
583 */
584function concatArrayStream(list) {
585 const result = new ArrayStream();
586 let prev = Promise.resolve();
587 list.forEach((stream, i) => {
588 prev = prev.then(() => pipe(stream, result, {
589 preventClose: i !== list.length - 1
590 }));
591 return prev;
592 });
593 return result;
594}
595
596/**
597 * Get a Reader
598 * @param {ReadableStream|Uint8array|String} input
599 * @returns {Reader}
600 */
601function getReader(input) {
602 return new Reader(input);
603}
604
605/**
606 * Get a Writer
607 * @param {WritableStream} input
608 * @returns {Writer}
609 */
610function getWriter(input) {
611 return new Writer(input);
612}
613
614/**
615 * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.
616 * @param {ReadableStream|Uint8array|String} input
617 * @param {WritableStream} target
618 * @param {Object} (optional) options
619 * @returns {Promise<undefined>} Promise indicating when piping has finished (input stream closed or errored)
620 * @async
621 */
622async function pipe(input, target, {
623 preventClose = false,
624 preventAbort = false,
625 preventCancel = false
626} = {}) {
627 if (isStream(input) && !isArrayStream(input)) {
628 input = toStream(input);
629 try {
630 if (input[externalBuffer]) {
631 const writer = getWriter(target);
632 for (let i = 0; i < input[externalBuffer].length; i++) {
633 await writer.ready;
634 await writer.write(input[externalBuffer][i]);
635 }
636 writer.releaseLock();
637 }
638 await input.pipeTo(target, {
639 preventClose,
640 preventAbort,
641 preventCancel
642 });
643 } catch(e) {}
644 return;
645 }
646 input = toArrayStream(input);
647 const reader = getReader(input);
648 const writer = getWriter(target);
649 try {
650 while (true) {
651 await writer.ready;
652 const { done, value } = await reader.read();
653 if (done) {
654 if (!preventClose) await writer.close();
655 break;
656 }
657 await writer.write(value);
658 }
659 } catch (e) {
660 if (!preventAbort) await writer.abort(e);
661 } finally {
662 reader.releaseLock();
663 writer.releaseLock();
664 }
665}
666
667/**
668 * Pipe a readable stream through a transform stream.
669 * @param {ReadableStream|Uint8array|String} input
670 * @param {Object} (optional) options
671 * @returns {ReadableStream} transformed stream
672 */
673function transformRaw(input, options) {
674 const transformStream = new TransformStream(options);
675 pipe(input, transformStream.writable);
676 return transformStream.readable;
677}
678
679/**
680 * Create a cancelable TransformStream.
681 * @param {Function} cancel
682 * @returns {TransformStream}
683 */
684function transformWithCancel(cancel) {
685 let pulled = false;
686 let backpressureChangePromiseResolve;
687 let outputController;
688 return {
689 readable: new ReadableStream({
690 start(controller) {
691 outputController = controller;
692 },
693 pull() {
694 if (backpressureChangePromiseResolve) {
695 backpressureChangePromiseResolve();
696 } else {
697 pulled = true;
698 }
699 },
700 cancel
701 }, {highWaterMark: 0}),
702 writable: new WritableStream({
703 write: async function(chunk) {
704 outputController.enqueue(chunk);
705 if (!pulled) {
706 await new Promise(resolve => {
707 backpressureChangePromiseResolve = resolve;
708 });
709 backpressureChangePromiseResolve = null;
710 } else {
711 pulled = false;
712 }
713 },
714 close: outputController.close.bind(outputController),
715 abort: outputController.error.bind(outputController)
716 })
717 };
718}
719
720/**
721 * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.
722 * @param {ReadableStream|Uint8array|String} input
723 * @param {Function} process
724 * @param {Function} finish
725 * @returns {ReadableStream|Uint8array|String}
726 */
727function transform(input, process = () => undefined, finish = () => undefined) {
728 if (isArrayStream(input)) {
729 const output = new ArrayStream();
730 (async () => {
731 const writer = getWriter(output);
732 try {
733 const data = await readToEnd(input);
734 const result1 = process(data);
735 const result2 = finish();
736 let result;
737 if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);
738 else result = result1 !== undefined ? result1 : result2;
739 await writer.write(result);
740 await writer.close();
741 } catch (e) {
742 await writer.abort(e);
743 }
744 })();
745 return output;
746 }
747 if (isStream(input)) {
748 return transformRaw(input, {
749 async transform(value, controller) {
750 try {
751 const result = await process(value);
752 if (result !== undefined) controller.enqueue(result);
753 } catch(e) {
754 controller.error(e);
755 }
756 },
757 async flush(controller) {
758 try {
759 const result = await finish();
760 if (result !== undefined) controller.enqueue(result);
761 } catch(e) {
762 controller.error(e);
763 }
764 }
765 });
766 }
767 const result1 = process(input);
768 const result2 = finish();
769 if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);
770 return result1 !== undefined ? result1 : result2;
771}
772
773/**
774 * Transform a stream using a helper function which is passed a readable and a writable stream.
775 * This function also maintains the possibility to cancel the input stream,
776 * and does so on cancelation of the output stream, despite cancelation
777 * normally being impossible when the input stream is being read from.
778 * @param {ReadableStream|Uint8array|String} input
779 * @param {Function} fn
780 * @returns {ReadableStream}
781 */
782function transformPair(input, fn) {
783 if (isStream(input) && !isArrayStream(input)) {
784 let incomingTransformController;
785 const incoming = new TransformStream({
786 start(controller) {
787 incomingTransformController = controller;
788 }
789 });
790
791 const pipeDonePromise = pipe(input, incoming.writable);
792
793 const outgoing = transformWithCancel(async function(reason) {
794 incomingTransformController.error(reason);
795 await pipeDonePromise;
796 await new Promise(setTimeout);
797 });
798 fn(incoming.readable, outgoing.writable);
799 return outgoing.readable;
800 }
801 input = toArrayStream(input);
802 const output = new ArrayStream();
803 fn(input, output);
804 return output;
805}
806
807/**
808 * Parse a stream using a helper function which is passed a Reader.
809 * The reader additionally has a remainder() method which returns a
810 * stream pointing to the remainder of input, and is linked to input
811 * for cancelation.
812 * @param {ReadableStream|Uint8array|String} input
813 * @param {Function} fn
814 * @returns {Any} the return value of fn()
815 */
816function parse(input, fn) {
817 let returnValue;
818 const transformed = transformPair(input, (readable, writable) => {
819 const reader = getReader(readable);
820 reader.remainder = () => {
821 reader.releaseLock();
822 pipe(readable, writable);
823 return transformed;
824 };
825 returnValue = fn(reader);
826 });
827 return returnValue;
828}
829
830/**
831 * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.
832 * Reading either of the two returned streams will pull from the input stream.
833 * The input stream will only be canceled if both of the returned streams are canceled.
834 * @param {ReadableStream|Uint8array|String} input
835 * @returns {Array<ReadableStream|Uint8array|String>} array containing two copies of input
836 */
837function tee(input) {
838 if (isArrayStream(input)) {
839 throw new Error('ArrayStream cannot be tee()d, use clone() instead');
840 }
841 if (isStream(input)) {
842 const teed = toStream(input).tee();
843 teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];
844 return teed;
845 }
846 return [slice(input), slice(input)];
847}
848
849/**
850 * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.
851 * Reading from the clone will pull from the input stream.
852 * The input stream will only be canceled if both the clone and the input stream are canceled.
853 * @param {ReadableStream|Uint8array|String} input
854 * @returns {ReadableStream|Uint8array|String} cloned input
855 */
856function clone(input) {
857 if (isArrayStream(input)) {
858 return input.clone();
859 }
860 if (isStream(input)) {
861 const teed = tee(input);
862 overwrite(input, teed[0]);
863 return teed[1];
864 }
865 return slice(input);
866}
867
868/**
869 * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.
870 * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.
871 * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.
872 * If the input stream is canceled, the clone will be errored.
873 * @param {ReadableStream|Uint8array|String} input
874 * @returns {ReadableStream|Uint8array|String} cloned input
875 */
876function passiveClone(input) {
877 if (isArrayStream(input)) {
878 return clone(input);
879 }
880 if (isStream(input)) {
881 return new ReadableStream({
882 start(controller) {
883 const transformed = transformPair(input, async (readable, writable) => {
884 const reader = getReader(readable);
885 const writer = getWriter(writable);
886 try {
887 while (true) {
888 await writer.ready;
889 const { done, value } = await reader.read();
890 if (done) {
891 try { controller.close(); } catch(e) {}
892 await writer.close();
893 return;
894 }
895 try { controller.enqueue(value); } catch(e) {}
896 await writer.write(value);
897 }
898 } catch(e) {
899 controller.error(e);
900 await writer.abort(e);
901 }
902 });
903 overwrite(input, transformed);
904 }
905 });
906 }
907 return slice(input);
908}
909
910/**
911 * Modify a stream object to point to a different stream object.
912 * This is used internally by clone() and passiveClone() to provide an abstraction over tee().
913 * @param {ReadableStream} input
914 * @param {ReadableStream} clone
915 */
916function overwrite(input, clone) {
917 // Overwrite input.getReader, input.locked, etc to point to clone
918 Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {
919 if (name === 'constructor') {
920 return;
921 }
922 if (descriptor.value) {
923 descriptor.value = descriptor.value.bind(clone);
924 } else {
925 descriptor.get = descriptor.get.bind(clone);
926 }
927 Object.defineProperty(input, name, descriptor);
928 });
929}
930
931/**
932 * Return a stream pointing to a part of the input stream.
933 * @param {ReadableStream|Uint8array|String} input
934 * @returns {ReadableStream|Uint8array|String} clone
935 */
936function slice(input, begin=0, end=Infinity) {
937 if (isArrayStream(input)) {
938 throw new Error('Not implemented');
939 }
940 if (isStream(input)) {
941 if (begin >= 0 && end >= 0) {
942 let bytesRead = 0;
943 return transformRaw(input, {
944 transform(value, controller) {
945 if (bytesRead < end) {
946 if (bytesRead + value.length >= begin) {
947 controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));
948 }
949 bytesRead += value.length;
950 } else {
951 controller.terminate();
952 }
953 }
954 });
955 }
956 if (begin < 0 && (end < 0 || end === Infinity)) {
957 let lastBytes = [];
958 return transform(input, value => {
959 if (value.length >= -begin) lastBytes = [value];
960 else lastBytes.push(value);
961 }, () => slice(concat(lastBytes), begin, end));
962 }
963 if (begin === 0 && end < 0) {
964 let lastBytes;
965 return transform(input, value => {
966 const returnValue = lastBytes ? concat([lastBytes, value]) : value;
967 if (returnValue.length >= -end) {
968 lastBytes = slice(returnValue, end);
969 return slice(returnValue, begin, end);
970 } else {
971 lastBytes = returnValue;
972 }
973 });
974 }
975 console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);
976 return fromAsync(async () => slice(await readToEnd(input), begin, end));
977 }
978 if (input[externalBuffer]) {
979 input = concat(input[externalBuffer].concat([input]));
980 }
981 if (isUint8Array(input) && !(NodeBuffer$1 && NodeBuffer$1.isBuffer(input))) {
982 if (end === Infinity) end = input.length;
983 return input.subarray(begin, end);
984 }
985 return input.slice(begin, end);
986}
987
988/**
989 * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).
990 * @param {ReadableStream|Uint8array|String} input
991 * @param {Function} join
992 * @returns {Promise<Uint8array|String|Any>} the return value of join()
993 * @async
994 */
995async function readToEnd(input, join=concat) {
996 if (isArrayStream(input)) {
997 return input.readToEnd(join);
998 }
999 if (isStream(input)) {
1000 return getReader(input).readToEnd(join);
1001 }
1002 return input;
1003}
1004
1005/**
1006 * Cancel a stream.
1007 * @param {ReadableStream|Uint8array|String} input
1008 * @param {Any} reason
1009 * @returns {Promise<Any>} indicates when the stream has been canceled
1010 * @async
1011 */
1012async function cancel(input, reason) {
1013 if (isStream(input)) {
1014 if (input.cancel) {
1015 return input.cancel(reason);
1016 }
1017 if (input.destroy) {
1018 input.destroy(reason);
1019 await new Promise(setTimeout);
1020 return reason;
1021 }
1022 }
1023}
1024
1025/**
1026 * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.
1027 * @param {Function} fn
1028 * @returns {ArrayStream}
1029 */
1030function fromAsync(fn) {
1031 const arrayStream = new ArrayStream();
1032 (async () => {
1033 const writer = getWriter(arrayStream);
1034 try {
1035 await writer.write(await fn());
1036 await writer.close();
1037 } catch (e) {
1038 await writer.abort(e);
1039 }
1040 })();
1041 return arrayStream;
1042}
1043
1044/* eslint-disable new-cap */
1045
1046/**
1047 * @fileoverview
1048 * BigInteger implementation of basic operations
1049 * that wraps the native BigInt library.
1050 * Operations are not constant time,
1051 * but we try and limit timing leakage where we can
1052 * @module biginteger/native
1053 * @private
1054 */
1055
1056/**
1057 * @private
1058 */
1059class BigInteger {
1060 /**
1061 * Get a BigInteger (input must be big endian for strings and arrays)
1062 * @param {Number|String|Uint8Array} n - Value to convert
1063 * @throws {Error} on null or undefined input
1064 */
1065 constructor(n) {
1066 if (n === undefined) {
1067 throw new Error('Invalid BigInteger input');
1068 }
1069
1070 if (n instanceof Uint8Array) {
1071 const bytes = n;
1072 const hex = new Array(bytes.length);
1073 for (let i = 0; i < bytes.length; i++) {
1074 const hexByte = bytes[i].toString(16);
1075 hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte;
1076 }
1077 this.value = BigInt('0x0' + hex.join(''));
1078 } else {
1079 this.value = BigInt(n);
1080 }
1081 }
1082
1083 clone() {
1084 return new BigInteger(this.value);
1085 }
1086
1087 /**
1088 * BigInteger increment in place
1089 */
1090 iinc() {
1091 this.value++;
1092 return this;
1093 }
1094
1095 /**
1096 * BigInteger increment
1097 * @returns {BigInteger} this + 1.
1098 */
1099 inc() {
1100 return this.clone().iinc();
1101 }
1102
1103 /**
1104 * BigInteger decrement in place
1105 */
1106 idec() {
1107 this.value--;
1108 return this;
1109 }
1110
1111 /**
1112 * BigInteger decrement
1113 * @returns {BigInteger} this - 1.
1114 */
1115 dec() {
1116 return this.clone().idec();
1117 }
1118
1119 /**
1120 * BigInteger addition in place
1121 * @param {BigInteger} x - Value to add
1122 */
1123 iadd(x) {
1124 this.value += x.value;
1125 return this;
1126 }
1127
1128 /**
1129 * BigInteger addition
1130 * @param {BigInteger} x - Value to add
1131 * @returns {BigInteger} this + x.
1132 */
1133 add(x) {
1134 return this.clone().iadd(x);
1135 }
1136
1137 /**
1138 * BigInteger subtraction in place
1139 * @param {BigInteger} x - Value to subtract
1140 */
1141 isub(x) {
1142 this.value -= x.value;
1143 return this;
1144 }
1145
1146 /**
1147 * BigInteger subtraction
1148 * @param {BigInteger} x - Value to subtract
1149 * @returns {BigInteger} this - x.
1150 */
1151 sub(x) {
1152 return this.clone().isub(x);
1153 }
1154
1155 /**
1156 * BigInteger multiplication in place
1157 * @param {BigInteger} x - Value to multiply
1158 */
1159 imul(x) {
1160 this.value *= x.value;
1161 return this;
1162 }
1163
1164 /**
1165 * BigInteger multiplication
1166 * @param {BigInteger} x - Value to multiply
1167 * @returns {BigInteger} this * x.
1168 */
1169 mul(x) {
1170 return this.clone().imul(x);
1171 }
1172
1173 /**
1174 * Compute value modulo m, in place
1175 * @param {BigInteger} m - Modulo
1176 */
1177 imod(m) {
1178 this.value %= m.value;
1179 if (this.isNegative()) {
1180 this.iadd(m);
1181 }
1182 return this;
1183 }
1184
1185 /**
1186 * Compute value modulo m
1187 * @param {BigInteger} m - Modulo
1188 * @returns {BigInteger} this mod m.
1189 */
1190 mod(m) {
1191 return this.clone().imod(m);
1192 }
1193
1194 /**
1195 * Compute modular exponentiation using square and multiply
1196 * @param {BigInteger} e - Exponent
1197 * @param {BigInteger} n - Modulo
1198 * @returns {BigInteger} this ** e mod n.
1199 */
1200 modExp(e, n) {
1201 if (n.isZero()) throw Error('Modulo cannot be zero');
1202 if (n.isOne()) return new BigInteger(0);
1203 if (e.isNegative()) throw Error('Unsopported negative exponent');
1204
1205 let exp = e.value;
1206 let x = this.value;
1207
1208 x %= n.value;
1209 let r = BigInt(1);
1210 while (exp > BigInt(0)) {
1211 const lsb = exp & BigInt(1);
1212 exp >>= BigInt(1); // e / 2
1213 // Always compute multiplication step, to reduce timing leakage
1214 const rx = (r * x) % n.value;
1215 // Update r only if lsb is 1 (odd exponent)
1216 r = lsb ? rx : r;
1217 x = (x * x) % n.value; // Square
1218 }
1219 return new BigInteger(r);
1220 }
1221
1222
1223 /**
1224 * Compute the inverse of this value modulo n
1225 * Note: this and and n must be relatively prime
1226 * @param {BigInteger} n - Modulo
1227 * @returns {BigInteger} x such that this*x = 1 mod n
1228 * @throws {Error} if the inverse does not exist
1229 */
1230 modInv(n) {
1231 const { gcd, x } = this._egcd(n);
1232 if (!gcd.isOne()) {
1233 throw new Error('Inverse does not exist');
1234 }
1235 return x.add(n).mod(n);
1236 }
1237
1238 /**
1239 * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)
1240 * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b)
1241 * @param {BigInteger} b - Second operand
1242 * @returns {{ gcd, x, y: BigInteger }}
1243 */
1244 _egcd(b) {
1245 let x = BigInt(0);
1246 let y = BigInt(1);
1247 let xPrev = BigInt(1);
1248 let yPrev = BigInt(0);
1249
1250 let a = this.value;
1251 b = b.value;
1252
1253 while (b !== BigInt(0)) {
1254 const q = a / b;
1255 let tmp = x;
1256 x = xPrev - q * x;
1257 xPrev = tmp;
1258
1259 tmp = y;
1260 y = yPrev - q * y;
1261 yPrev = tmp;
1262
1263 tmp = b;
1264 b = a % b;
1265 a = tmp;
1266 }
1267
1268 return {
1269 x: new BigInteger(xPrev),
1270 y: new BigInteger(yPrev),
1271 gcd: new BigInteger(a)
1272 };
1273 }
1274
1275 /**
1276 * Compute greatest common divisor between this and n
1277 * @param {BigInteger} b - Operand
1278 * @returns {BigInteger} gcd
1279 */
1280 gcd(b) {
1281 let a = this.value;
1282 b = b.value;
1283 while (b !== BigInt(0)) {
1284 const tmp = b;
1285 b = a % b;
1286 a = tmp;
1287 }
1288 return new BigInteger(a);
1289 }
1290
1291 /**
1292 * Shift this to the left by x, in place
1293 * @param {BigInteger} x - Shift value
1294 */
1295 ileftShift(x) {
1296 this.value <<= x.value;
1297 return this;
1298 }
1299
1300 /**
1301 * Shift this to the left by x
1302 * @param {BigInteger} x - Shift value
1303 * @returns {BigInteger} this << x.
1304 */
1305 leftShift(x) {
1306 return this.clone().ileftShift(x);
1307 }
1308
1309 /**
1310 * Shift this to the right by x, in place
1311 * @param {BigInteger} x - Shift value
1312 */
1313 irightShift(x) {
1314 this.value >>= x.value;
1315 return this;
1316 }
1317
1318 /**
1319 * Shift this to the right by x
1320 * @param {BigInteger} x - Shift value
1321 * @returns {BigInteger} this >> x.
1322 */
1323 rightShift(x) {
1324 return this.clone().irightShift(x);
1325 }
1326
1327 /**
1328 * Whether this value is equal to x
1329 * @param {BigInteger} x
1330 * @returns {Boolean}
1331 */
1332 equal(x) {
1333 return this.value === x.value;
1334 }
1335
1336 /**
1337 * Whether this value is less than x
1338 * @param {BigInteger} x
1339 * @returns {Boolean}
1340 */
1341 lt(x) {
1342 return this.value < x.value;
1343 }
1344
1345 /**
1346 * Whether this value is less than or equal to x
1347 * @param {BigInteger} x
1348 * @returns {Boolean}
1349 */
1350 lte(x) {
1351 return this.value <= x.value;
1352 }
1353
1354 /**
1355 * Whether this value is greater than x
1356 * @param {BigInteger} x
1357 * @returns {Boolean}
1358 */
1359 gt(x) {
1360 return this.value > x.value;
1361 }
1362
1363 /**
1364 * Whether this value is greater than or equal to x
1365 * @param {BigInteger} x
1366 * @returns {Boolean}
1367 */
1368 gte(x) {
1369 return this.value >= x.value;
1370 }
1371
1372 isZero() {
1373 return this.value === BigInt(0);
1374 }
1375
1376 isOne() {
1377 return this.value === BigInt(1);
1378 }
1379
1380 isNegative() {
1381 return this.value < BigInt(0);
1382 }
1383
1384 isEven() {
1385 return !(this.value & BigInt(1));
1386 }
1387
1388 abs() {
1389 const res = this.clone();
1390 if (this.isNegative()) {
1391 res.value = -res.value;
1392 }
1393 return res;
1394 }
1395
1396 /**
1397 * Get this value as a string
1398 * @returns {String} this value.
1399 */
1400 toString() {
1401 return this.value.toString();
1402 }
1403
1404 /**
1405 * Get this value as an exact Number (max 53 bits)
1406 * Fails if this value is too large
1407 * @returns {Number}
1408 */
1409 toNumber() {
1410 const number = Number(this.value);
1411 if (number > Number.MAX_SAFE_INTEGER) {
1412 // We throw and error to conform with the bn.js implementation
1413 throw new Error('Number can only safely store up to 53 bits');
1414 }
1415 return number;
1416 }
1417
1418 /**
1419 * Get value of i-th bit
1420 * @param {Number} i - Bit index
1421 * @returns {Number} Bit value.
1422 */
1423 getBit(i) {
1424 const bit = (this.value >> BigInt(i)) & BigInt(1);
1425 return (bit === BigInt(0)) ? 0 : 1;
1426 }
1427
1428 /**
1429 * Compute bit length
1430 * @returns {Number} Bit length.
1431 */
1432 bitLength() {
1433 const zero = new BigInteger(0);
1434 const one = new BigInteger(1);
1435 const negOne = new BigInteger(-1);
1436
1437 // -1n >> -1n is -1n
1438 // 1n >> 1n is 0n
1439 const target = this.isNegative() ? negOne : zero;
1440 let bitlen = 1;
1441 const tmp = this.clone();
1442 while (!tmp.irightShift(one).equal(target)) {
1443 bitlen++;
1444 }
1445 return bitlen;
1446 }
1447
1448 /**
1449 * Compute byte length
1450 * @returns {Number} Byte length.
1451 */
1452 byteLength() {
1453 const zero = new BigInteger(0);
1454 const negOne = new BigInteger(-1);
1455
1456 const target = this.isNegative() ? negOne : zero;
1457 const eight = new BigInteger(8);
1458 let len = 1;
1459 const tmp = this.clone();
1460 while (!tmp.irightShift(eight).equal(target)) {
1461 len++;
1462 }
1463 return len;
1464 }
1465
1466 /**
1467 * Get Uint8Array representation of this number
1468 * @param {String} endian - Endianess of output array (defaults to 'be')
1469 * @param {Number} length - Of output array
1470 * @returns {Uint8Array}
1471 */
1472 toUint8Array(endian = 'be', length) {
1473 // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)
1474 // this is faster than shift+mod iterations
1475 let hex = this.value.toString(16);
1476 if (hex.length % 2 === 1) {
1477 hex = '0' + hex;
1478 }
1479
1480 const rawLength = hex.length / 2;
1481 const bytes = new Uint8Array(length || rawLength);
1482 // parse hex
1483 const offset = length ? (length - rawLength) : 0;
1484 let i = 0;
1485 while (i < rawLength) {
1486 bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);
1487 i++;
1488 }
1489
1490 if (endian !== 'be') {
1491 bytes.reverse();
1492 }
1493
1494 return bytes;
1495 }
1496}
1497
1498const detectBigInt = () => typeof BigInt !== 'undefined';
1499
1500async function getBigInteger() {
1501 if (detectBigInt()) {
1502 return BigInteger;
1503 } else {
1504 const { default: BigInteger } = await Promise.resolve().then(function () { return bn_interface; });
1505 return BigInteger;
1506 }
1507}
1508
1509/**
1510 * @module enums
1511 */
1512
1513const byValue = Symbol('byValue');
1514
1515var enums = {
1516
1517 /** Maps curve names under various standards to one
1518 * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}
1519 * @enum {String}
1520 * @readonly
1521 */
1522 curve: {
1523 /** NIST P-256 Curve */
1524 'p256': 'p256',
1525 'P-256': 'p256',
1526 'secp256r1': 'p256',
1527 'prime256v1': 'p256',
1528 '1.2.840.10045.3.1.7': 'p256',
1529 '2a8648ce3d030107': 'p256',
1530 '2A8648CE3D030107': 'p256',
1531
1532 /** NIST P-384 Curve */
1533 'p384': 'p384',
1534 'P-384': 'p384',
1535 'secp384r1': 'p384',
1536 '1.3.132.0.34': 'p384',
1537 '2b81040022': 'p384',
1538 '2B81040022': 'p384',
1539
1540 /** NIST P-521 Curve */
1541 'p521': 'p521',
1542 'P-521': 'p521',
1543 'secp521r1': 'p521',
1544 '1.3.132.0.35': 'p521',
1545 '2b81040023': 'p521',
1546 '2B81040023': 'p521',
1547
1548 /** SECG SECP256k1 Curve */
1549 'secp256k1': 'secp256k1',
1550 '1.3.132.0.10': 'secp256k1',
1551 '2b8104000a': 'secp256k1',
1552 '2B8104000A': 'secp256k1',
1553
1554 /** Ed25519 - deprecated by crypto-refresh (replaced by standaone Ed25519 algo) */
1555 'ed25519Legacy': 'ed25519',
1556 'ED25519': 'ed25519',
1557 /** @deprecated use `ed25519Legacy` instead */
1558 'ed25519': 'ed25519',
1559 'Ed25519': 'ed25519',
1560 '1.3.6.1.4.1.11591.15.1': 'ed25519',
1561 '2b06010401da470f01': 'ed25519',
1562 '2B06010401DA470F01': 'ed25519',
1563
1564 /** Curve25519 - deprecated by crypto-refresh (replaced by standaone X25519 algo) */
1565 'curve25519Legacy': 'curve25519',
1566 'X25519': 'curve25519',
1567 'cv25519': 'curve25519',
1568 /** @deprecated use `curve25519Legacy` instead */
1569 'curve25519': 'curve25519',
1570 'Curve25519': 'curve25519',
1571 '1.3.6.1.4.1.3029.1.5.1': 'curve25519',
1572 '2b060104019755010501': 'curve25519',
1573 '2B060104019755010501': 'curve25519',
1574
1575 /** BrainpoolP256r1 Curve */
1576 'brainpoolP256r1': 'brainpoolP256r1',
1577 '1.3.36.3.3.2.8.1.1.7': 'brainpoolP256r1',
1578 '2b2403030208010107': 'brainpoolP256r1',
1579 '2B2403030208010107': 'brainpoolP256r1',
1580
1581 /** BrainpoolP384r1 Curve */
1582 'brainpoolP384r1': 'brainpoolP384r1',
1583 '1.3.36.3.3.2.8.1.1.11': 'brainpoolP384r1',
1584 '2b240303020801010b': 'brainpoolP384r1',
1585 '2B240303020801010B': 'brainpoolP384r1',
1586
1587 /** BrainpoolP512r1 Curve */
1588 'brainpoolP512r1': 'brainpoolP512r1',
1589 '1.3.36.3.3.2.8.1.1.13': 'brainpoolP512r1',
1590 '2b240303020801010d': 'brainpoolP512r1',
1591 '2B240303020801010D': 'brainpoolP512r1'
1592 },
1593
1594 /** A string to key specifier type
1595 * @enum {Integer}
1596 * @readonly
1597 */
1598 s2k: {
1599 simple: 0,
1600 salted: 1,
1601 iterated: 3,
1602 gnu: 101
1603 },
1604
1605 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-crypto-refresh-08.html#section-9.1|crypto-refresh RFC, section 9.1}
1606 * @enum {Integer}
1607 * @readonly
1608 */
1609 publicKey: {
1610 /** RSA (Encrypt or Sign) [HAC] */
1611 rsaEncryptSign: 1,
1612 /** RSA (Encrypt only) [HAC] */
1613 rsaEncrypt: 2,
1614 /** RSA (Sign only) [HAC] */
1615 rsaSign: 3,
1616 /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */
1617 elgamal: 16,
1618 /** DSA (Sign only) [FIPS186] [HAC] */
1619 dsa: 17,
1620 /** ECDH (Encrypt only) [RFC6637] */
1621 ecdh: 18,
1622 /** ECDSA (Sign only) [RFC6637] */
1623 ecdsa: 19,
1624 /** EdDSA (Sign only) - deprecated by crypto-refresh (replaced by `ed25519` identifier below)
1625 * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */
1626 eddsaLegacy: 22, // NB: this is declared before `eddsa` to translate 22 to 'eddsa' for backwards compatibility
1627 /** @deprecated use `eddsaLegacy` instead */
1628 ed25519Legacy: 22,
1629 /** @deprecated use `eddsaLegacy` instead */
1630 eddsa: 22,
1631 /** Reserved for AEDH */
1632 aedh: 23,
1633 /** Reserved for AEDSA */
1634 aedsa: 24,
1635 /** X25519 (Encrypt only) */
1636 x25519: 25,
1637 /** X448 (Encrypt only) */
1638 x448: 26,
1639 /** Ed25519 (Sign only) */
1640 ed25519: 27,
1641 /** Ed448 (Sign only) */
1642 ed448: 28
1643 },
1644
1645 /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}
1646 * @enum {Integer}
1647 * @readonly
1648 */
1649 symmetric: {
1650 plaintext: 0,
1651 /** Not implemented! */
1652 idea: 1,
1653 tripledes: 2,
1654 cast5: 3,
1655 blowfish: 4,
1656 aes128: 7,
1657 aes192: 8,
1658 aes256: 9,
1659 twofish: 10
1660 },
1661
1662 /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}
1663 * @enum {Integer}
1664 * @readonly
1665 */
1666 compression: {
1667 uncompressed: 0,
1668 /** RFC1951 */
1669 zip: 1,
1670 /** RFC1950 */
1671 zlib: 2,
1672 bzip2: 3
1673 },
1674
1675 /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}
1676 * @enum {Integer}
1677 * @readonly
1678 */
1679 hash: {
1680 md5: 1,
1681 sha1: 2,
1682 ripemd: 3,
1683 sha256: 8,
1684 sha384: 9,
1685 sha512: 10,
1686 sha224: 11
1687 },
1688
1689 /** A list of hash names as accepted by webCrypto functions.
1690 * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}
1691 * @enum {String}
1692 */
1693 webHash: {
1694 'SHA-1': 2,
1695 'SHA-256': 8,
1696 'SHA-384': 9,
1697 'SHA-512': 10
1698 },
1699
1700 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}
1701 * @enum {Integer}
1702 * @readonly
1703 */
1704 aead: {
1705 eax: 1,
1706 ocb: 2,
1707 experimentalGCM: 100 // Private algorithm
1708 },
1709
1710 /** A list of packet types and numeric tags associated with them.
1711 * @enum {Integer}
1712 * @readonly
1713 */
1714 packet: {
1715 publicKeyEncryptedSessionKey: 1,
1716 signature: 2,
1717 symEncryptedSessionKey: 3,
1718 onePassSignature: 4,
1719 secretKey: 5,
1720 publicKey: 6,
1721 secretSubkey: 7,
1722 compressedData: 8,
1723 symmetricallyEncryptedData: 9,
1724 marker: 10,
1725 literalData: 11,
1726 trust: 12,
1727 userID: 13,
1728 publicSubkey: 14,
1729 userAttribute: 17,
1730 symEncryptedIntegrityProtectedData: 18,
1731 modificationDetectionCode: 19,
1732 aeadEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1
1733 },
1734
1735 /** Data types in the literal packet
1736 * @enum {Integer}
1737 * @readonly
1738 */
1739 literal: {
1740 /** Binary data 'b' */
1741 binary: 'b'.charCodeAt(),
1742 /** Text data 't' */
1743 text: 't'.charCodeAt(),
1744 /** Utf8 data 'u' */
1745 utf8: 'u'.charCodeAt(),
1746 /** MIME message body part 'm' */
1747 mime: 'm'.charCodeAt()
1748 },
1749
1750
1751 /** One pass signature packet type
1752 * @enum {Integer}
1753 * @readonly
1754 */
1755 signature: {
1756 /** 0x00: Signature of a binary document. */
1757 binary: 0,
1758 /** 0x01: Signature of a canonical text document.
1759 *
1760 * Canonicalyzing the document by converting line endings. */
1761 text: 1,
1762 /** 0x02: Standalone signature.
1763 *
1764 * This signature is a signature of only its own subpacket contents.
1765 * It is calculated identically to a signature over a zero-lengh
1766 * binary document. Note that it doesn't make sense to have a V3
1767 * standalone signature. */
1768 standalone: 2,
1769 /** 0x10: Generic certification of a User ID and Public-Key packet.
1770 *
1771 * The issuer of this certification does not make any particular
1772 * assertion as to how well the certifier has checked that the owner
1773 * of the key is in fact the person described by the User ID. */
1774 certGeneric: 16,
1775 /** 0x11: Persona certification of a User ID and Public-Key packet.
1776 *
1777 * The issuer of this certification has not done any verification of
1778 * the claim that the owner of this key is the User ID specified. */
1779 certPersona: 17,
1780 /** 0x12: Casual certification of a User ID and Public-Key packet.
1781 *
1782 * The issuer of this certification has done some casual
1783 * verification of the claim of identity. */
1784 certCasual: 18,
1785 /** 0x13: Positive certification of a User ID and Public-Key packet.
1786 *
1787 * The issuer of this certification has done substantial
1788 * verification of the claim of identity.
1789 *
1790 * Most OpenPGP implementations make their "key signatures" as 0x10
1791 * certifications. Some implementations can issue 0x11-0x13
1792 * certifications, but few differentiate between the types. */
1793 certPositive: 19,
1794 /** 0x30: Certification revocation signature
1795 *
1796 * This signature revokes an earlier User ID certification signature
1797 * (signature class 0x10 through 0x13) or direct-key signature
1798 * (0x1F). It should be issued by the same key that issued the
1799 * revoked signature or an authorized revocation key. The signature
1800 * is computed over the same data as the certificate that it
1801 * revokes, and should have a later creation date than that
1802 * certificate. */
1803 certRevocation: 48,
1804 /** 0x18: Subkey Binding Signature
1805 *
1806 * This signature is a statement by the top-level signing key that
1807 * indicates that it owns the subkey. This signature is calculated
1808 * directly on the primary key and subkey, and not on any User ID or
1809 * other packets. A signature that binds a signing subkey MUST have
1810 * an Embedded Signature subpacket in this binding signature that
1811 * contains a 0x19 signature made by the signing subkey on the
1812 * primary key and subkey. */
1813 subkeyBinding: 24,
1814 /** 0x19: Primary Key Binding Signature
1815 *
1816 * This signature is a statement by a signing subkey, indicating
1817 * that it is owned by the primary key and subkey. This signature
1818 * is calculated the same way as a 0x18 signature: directly on the
1819 * primary key and subkey, and not on any User ID or other packets.
1820 *
1821 * When a signature is made over a key, the hash data starts with the
1822 * octet 0x99, followed by a two-octet length of the key, and then body
1823 * of the key packet. (Note that this is an old-style packet header for
1824 * a key packet with two-octet length.) A subkey binding signature
1825 * (type 0x18) or primary key binding signature (type 0x19) then hashes
1826 * the subkey using the same format as the main key (also using 0x99 as
1827 * the first octet). */
1828 keyBinding: 25,
1829 /** 0x1F: Signature directly on a key
1830 *
1831 * This signature is calculated directly on a key. It binds the
1832 * information in the Signature subpackets to the key, and is
1833 * appropriate to be used for subpackets that provide information
1834 * about the key, such as the Revocation Key subpacket. It is also
1835 * appropriate for statements that non-self certifiers want to make
1836 * about the key itself, rather than the binding between a key and a
1837 * name. */
1838 key: 31,
1839 /** 0x20: Key revocation signature
1840 *
1841 * The signature is calculated directly on the key being revoked. A
1842 * revoked key is not to be used. Only revocation signatures by the
1843 * key being revoked, or by an authorized revocation key, should be
1844 * considered valid revocation signatures.a */
1845 keyRevocation: 32,
1846 /** 0x28: Subkey revocation signature
1847 *
1848 * The signature is calculated directly on the subkey being revoked.
1849 * A revoked subkey is not to be used. Only revocation signatures
1850 * by the top-level signature key that is bound to this subkey, or
1851 * by an authorized revocation key, should be considered valid
1852 * revocation signatures.
1853 *
1854 * Key revocation signatures (types 0x20 and 0x28)
1855 * hash only the key being revoked. */
1856 subkeyRevocation: 40,
1857 /** 0x40: Timestamp signature.
1858 * This signature is only meaningful for the timestamp contained in
1859 * it. */
1860 timestamp: 64,
1861 /** 0x50: Third-Party Confirmation signature.
1862 *
1863 * This signature is a signature over some other OpenPGP Signature
1864 * packet(s). It is analogous to a notary seal on the signed data.
1865 * A third-party signature SHOULD include Signature Target
1866 * subpacket(s) to give easy identification. Note that we really do
1867 * mean SHOULD. There are plausible uses for this (such as a blind
1868 * party that only sees the signature, not the key or source
1869 * document) that cannot include a target subpacket. */
1870 thirdParty: 80
1871 },
1872
1873 /** Signature subpacket type
1874 * @enum {Integer}
1875 * @readonly
1876 */
1877 signatureSubpacket: {
1878 signatureCreationTime: 2,
1879 signatureExpirationTime: 3,
1880 exportableCertification: 4,
1881 trustSignature: 5,
1882 regularExpression: 6,
1883 revocable: 7,
1884 keyExpirationTime: 9,
1885 placeholderBackwardsCompatibility: 10,
1886 preferredSymmetricAlgorithms: 11,
1887 revocationKey: 12,
1888 issuer: 16,
1889 notationData: 20,
1890 preferredHashAlgorithms: 21,
1891 preferredCompressionAlgorithms: 22,
1892 keyServerPreferences: 23,
1893 preferredKeyServer: 24,
1894 primaryUserID: 25,
1895 policyURI: 26,
1896 keyFlags: 27,
1897 signersUserID: 28,
1898 reasonForRevocation: 29,
1899 features: 30,
1900 signatureTarget: 31,
1901 embeddedSignature: 32,
1902 issuerFingerprint: 33,
1903 preferredAEADAlgorithms: 34
1904 },
1905
1906 /** Key flags
1907 * @enum {Integer}
1908 * @readonly
1909 */
1910 keyFlags: {
1911 /** 0x01 - This key may be used to certify other keys. */
1912 certifyKeys: 1,
1913 /** 0x02 - This key may be used to sign data. */
1914 signData: 2,
1915 /** 0x04 - This key may be used to encrypt communications. */
1916 encryptCommunication: 4,
1917 /** 0x08 - This key may be used to encrypt storage. */
1918 encryptStorage: 8,
1919 /** 0x10 - The private component of this key may have been split
1920 * by a secret-sharing mechanism. */
1921 splitPrivateKey: 16,
1922 /** 0x20 - This key may be used for authentication. */
1923 authentication: 32,
1924 /** 0x80 - The private component of this key may be in the
1925 * possession of more than one person. */
1926 sharedPrivateKey: 128
1927 },
1928
1929 /** Armor type
1930 * @enum {Integer}
1931 * @readonly
1932 */
1933 armor: {
1934 multipartSection: 0,
1935 multipartLast: 1,
1936 signed: 2,
1937 message: 3,
1938 publicKey: 4,
1939 privateKey: 5,
1940 signature: 6
1941 },
1942
1943 /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}
1944 * @enum {Integer}
1945 * @readonly
1946 */
1947 reasonForRevocation: {
1948 /** No reason specified (key revocations or cert revocations) */
1949 noReason: 0,
1950 /** Key is superseded (key revocations) */
1951 keySuperseded: 1,
1952 /** Key material has been compromised (key revocations) */
1953 keyCompromised: 2,
1954 /** Key is retired and no longer used (key revocations) */
1955 keyRetired: 3,
1956 /** User ID information is no longer valid (cert revocations) */
1957 userIDInvalid: 32
1958 },
1959
1960 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}
1961 * @enum {Integer}
1962 * @readonly
1963 */
1964 features: {
1965 /** 0x01 - Modification Detection (packets 18 and 19) */
1966 modificationDetection: 1,
1967 /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5
1968 * Symmetric-Key Encrypted Session Key Packets (packet 3) */
1969 aead: 2,
1970 /** 0x04 - Version 5 Public-Key Packet format and corresponding new
1971 * fingerprint format */
1972 v5Keys: 4
1973 },
1974
1975 /**
1976 * Asserts validity of given value and converts from string/integer to integer.
1977 * @param {Object} type target enum type
1978 * @param {String|Integer} e value to check and/or convert
1979 * @returns {Integer} enum value if it exists
1980 * @throws {Error} if the value is invalid
1981 */
1982 write: function(type, e) {
1983 if (typeof e === 'number') {
1984 e = this.read(type, e);
1985 }
1986
1987 if (type[e] !== undefined) {
1988 return type[e];
1989 }
1990
1991 throw new Error('Invalid enum value.');
1992 },
1993
1994 /**
1995 * Converts enum integer value to the corresponding string, if it exists.
1996 * @param {Object} type target enum type
1997 * @param {Integer} e value to convert
1998 * @returns {String} name of enum value if it exists
1999 * @throws {Error} if the value is invalid
2000 */
2001 read: function(type, e) {
2002 if (!type[byValue]) {
2003 type[byValue] = [];
2004 Object.entries(type).forEach(([key, value]) => {
2005 type[byValue][value] = key;
2006 });
2007 }
2008
2009 if (type[byValue][e] !== undefined) {
2010 return type[byValue][e];
2011 }
2012
2013 throw new Error('Invalid enum value.');
2014 }
2015};
2016
2017// GPG4Browsers - An OpenPGP implementation in javascript
2018
2019const debugMode = (() => {
2020 try {
2021 return process.env.NODE_ENV === 'development'; // eslint-disable-line no-process-env
2022 } catch (e) {}
2023 return false;
2024})();
2025
2026const util = {
2027 isString: function(data) {
2028 return typeof data === 'string' || data instanceof String;
2029 },
2030
2031 isArray: function(data) {
2032 return data instanceof Array;
2033 },
2034
2035 isUint8Array: isUint8Array,
2036
2037 isStream: isStream,
2038
2039 readNumber: function (bytes) {
2040 let n = 0;
2041 for (let i = 0; i < bytes.length; i++) {
2042 n += (256 ** i) * bytes[bytes.length - 1 - i];
2043 }
2044 return n;
2045 },
2046
2047 writeNumber: function (n, bytes) {
2048 const b = new Uint8Array(bytes);
2049 for (let i = 0; i < bytes; i++) {
2050 b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;
2051 }
2052
2053 return b;
2054 },
2055
2056 readDate: function (bytes) {
2057 const n = util.readNumber(bytes);
2058 const d = new Date(n * 1000);
2059 return d;
2060 },
2061
2062 writeDate: function (time) {
2063 const numeric = Math.floor(time.getTime() / 1000);
2064
2065 return util.writeNumber(numeric, 4);
2066 },
2067
2068 normalizeDate: function (time = Date.now()) {
2069 return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);
2070 },
2071
2072 /**
2073 * Read one MPI from bytes in input
2074 * @param {Uint8Array} bytes - Input data to parse
2075 * @returns {Uint8Array} Parsed MPI.
2076 */
2077 readMPI: function (bytes) {
2078 const bits = (bytes[0] << 8) | bytes[1];
2079 const bytelen = (bits + 7) >>> 3;
2080 return bytes.subarray(2, 2 + bytelen);
2081 },
2082
2083 /**
2084 * Left-pad Uint8Array to length by adding 0x0 bytes
2085 * @param {Uint8Array} bytes - Data to pad
2086 * @param {Number} length - Padded length
2087 * @returns {Uint8Array} Padded bytes.
2088 */
2089 leftPad(bytes, length) {
2090 const padded = new Uint8Array(length);
2091 const offset = length - bytes.length;
2092 padded.set(bytes, offset);
2093 return padded;
2094 },
2095
2096 /**
2097 * Convert a Uint8Array to an MPI-formatted Uint8Array.
2098 * @param {Uint8Array} bin - An array of 8-bit integers to convert
2099 * @returns {Uint8Array} MPI-formatted Uint8Array.
2100 */
2101 uint8ArrayToMPI: function (bin) {
2102 const bitSize = util.uint8ArrayBitLength(bin);
2103 if (bitSize === 0) {
2104 throw new Error('Zero MPI');
2105 }
2106 const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));
2107 const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);
2108 return util.concatUint8Array([prefix, stripped]);
2109 },
2110
2111 /**
2112 * Return bit length of the input data
2113 * @param {Uint8Array} bin input data (big endian)
2114 * @returns bit length
2115 */
2116 uint8ArrayBitLength: function (bin) {
2117 let i; // index of leading non-zero byte
2118 for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;
2119 if (i === bin.length) {
2120 return 0;
2121 }
2122 const stripped = bin.subarray(i);
2123 return (stripped.length - 1) * 8 + util.nbits(stripped[0]);
2124 },
2125
2126 /**
2127 * Convert a hex string to an array of 8-bit integers
2128 * @param {String} hex - A hex string to convert
2129 * @returns {Uint8Array} An array of 8-bit integers.
2130 */
2131 hexToUint8Array: function (hex) {
2132 const result = new Uint8Array(hex.length >> 1);
2133 for (let k = 0; k < hex.length >> 1; k++) {
2134 result[k] = parseInt(hex.substr(k << 1, 2), 16);
2135 }
2136 return result;
2137 },
2138
2139 /**
2140 * Convert an array of 8-bit integers to a hex string
2141 * @param {Uint8Array} bytes - Array of 8-bit integers to convert
2142 * @returns {String} Hexadecimal representation of the array.
2143 */
2144 uint8ArrayToHex: function (bytes) {
2145 const r = [];
2146 const e = bytes.length;
2147 let c = 0;
2148 let h;
2149 while (c < e) {
2150 h = bytes[c++].toString(16);
2151 while (h.length < 2) {
2152 h = '0' + h;
2153 }
2154 r.push('' + h);
2155 }
2156 return r.join('');
2157 },
2158
2159 /**
2160 * Convert a string to an array of 8-bit integers
2161 * @param {String} str - String to convert
2162 * @returns {Uint8Array} An array of 8-bit integers.
2163 */
2164 stringToUint8Array: function (str) {
2165 return transform(str, str => {
2166 if (!util.isString(str)) {
2167 throw new Error('stringToUint8Array: Data must be in the form of a string');
2168 }
2169
2170 const result = new Uint8Array(str.length);
2171 for (let i = 0; i < str.length; i++) {
2172 result[i] = str.charCodeAt(i);
2173 }
2174 return result;
2175 });
2176 },
2177
2178 /**
2179 * Convert an array of 8-bit integers to a string
2180 * @param {Uint8Array} bytes - An array of 8-bit integers to convert
2181 * @returns {String} String representation of the array.
2182 */
2183 uint8ArrayToString: function (bytes) {
2184 bytes = new Uint8Array(bytes);
2185 const result = [];
2186 const bs = 1 << 14;
2187 const j = bytes.length;
2188
2189 for (let i = 0; i < j; i += bs) {
2190 result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));
2191 }
2192 return result.join('');
2193 },
2194
2195 /**
2196 * Convert a native javascript string to a Uint8Array of utf8 bytes
2197 * @param {String|ReadableStream} str - The string to convert
2198 * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.
2199 */
2200 encodeUTF8: function (str) {
2201 const encoder = new TextEncoder('utf-8');
2202 // eslint-disable-next-line no-inner-declarations
2203 function process(value, lastChunk = false) {
2204 return encoder.encode(value, { stream: !lastChunk });
2205 }
2206 return transform(str, process, () => process('', true));
2207 },
2208
2209 /**
2210 * Convert a Uint8Array of utf8 bytes to a native javascript string
2211 * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes
2212 * @returns {String|ReadableStream} A native javascript string.
2213 */
2214 decodeUTF8: function (utf8) {
2215 const decoder = new TextDecoder('utf-8');
2216 // eslint-disable-next-line no-inner-declarations
2217 function process(value, lastChunk = false) {
2218 return decoder.decode(value, { stream: !lastChunk });
2219 }
2220 return transform(utf8, process, () => process(new Uint8Array(), true));
2221 },
2222
2223 /**
2224 * Concat a list of Uint8Arrays, Strings or Streams
2225 * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
2226 * @param {Array<Uint8Array|String|ReadableStream>} Array - Of Uint8Arrays/Strings/Streams to concatenate
2227 * @returns {Uint8Array|String|ReadableStream} Concatenated array.
2228 */
2229 concat: concat,
2230
2231 /**
2232 * Concat Uint8Arrays
2233 * @param {Array<Uint8Array>} Array - Of Uint8Arrays to concatenate
2234 * @returns {Uint8Array} Concatenated array.
2235 */
2236 concatUint8Array: concatUint8Array,
2237
2238 /**
2239 * Check Uint8Array equality
2240 * @param {Uint8Array} array1 - First array
2241 * @param {Uint8Array} array2 - Second array
2242 * @returns {Boolean} Equality.
2243 */
2244 equalsUint8Array: function (array1, array2) {
2245 if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {
2246 throw new Error('Data must be in the form of a Uint8Array');
2247 }
2248
2249 if (array1.length !== array2.length) {
2250 return false;
2251 }
2252
2253 for (let i = 0; i < array1.length; i++) {
2254 if (array1[i] !== array2[i]) {
2255 return false;
2256 }
2257 }
2258 return true;
2259 },
2260
2261 /**
2262 * Calculates a 16bit sum of a Uint8Array by adding each character
2263 * codes modulus 65535
2264 * @param {Uint8Array} Uint8Array - To create a sum of
2265 * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.
2266 */
2267 writeChecksum: function (text) {
2268 let s = 0;
2269 for (let i = 0; i < text.length; i++) {
2270 s = (s + text[i]) & 0xFFFF;
2271 }
2272 return util.writeNumber(s, 2);
2273 },
2274
2275 /**
2276 * Helper function to print a debug message. Debug
2277 * messages are only printed if
2278 * @param {String} str - String of the debug message
2279 */
2280 printDebug: function (str) {
2281 if (debugMode) {
2282 console.log('[OpenPGP.js debug]', str);
2283 }
2284 },
2285
2286 /**
2287 * Helper function to print a debug error. Debug
2288 * messages are only printed if
2289 * @param {String} str - String of the debug message
2290 */
2291 printDebugError: function (error) {
2292 if (debugMode) {
2293 console.error('[OpenPGP.js debug]', error);
2294 }
2295 },
2296
2297 // returns bit length of the integer x
2298 nbits: function (x) {
2299 let r = 1;
2300 let t = x >>> 16;
2301 if (t !== 0) {
2302 x = t;
2303 r += 16;
2304 }
2305 t = x >> 8;
2306 if (t !== 0) {
2307 x = t;
2308 r += 8;
2309 }
2310 t = x >> 4;
2311 if (t !== 0) {
2312 x = t;
2313 r += 4;
2314 }
2315 t = x >> 2;
2316 if (t !== 0) {
2317 x = t;
2318 r += 2;
2319 }
2320 t = x >> 1;
2321 if (t !== 0) {
2322 x = t;
2323 r += 1;
2324 }
2325 return r;
2326 },
2327
2328 /**
2329 * If S[1] == 0, then double(S) == (S[2..128] || 0);
2330 * otherwise, double(S) == (S[2..128] || 0) xor
2331 * (zeros(120) || 10000111).
2332 *
2333 * Both OCB and EAX (through CMAC) require this function to be constant-time.
2334 *
2335 * @param {Uint8Array} data
2336 */
2337 double: function(data) {
2338 const doubleVar = new Uint8Array(data.length);
2339 const last = data.length - 1;
2340 for (let i = 0; i < last; i++) {
2341 doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);
2342 }
2343 doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);
2344 return doubleVar;
2345 },
2346
2347 /**
2348 * Shift a Uint8Array to the right by n bits
2349 * @param {Uint8Array} array - The array to shift
2350 * @param {Integer} bits - Amount of bits to shift (MUST be smaller
2351 * than 8)
2352 * @returns {String} Resulting array.
2353 */
2354 shiftRight: function (array, bits) {
2355 if (bits) {
2356 for (let i = array.length - 1; i >= 0; i--) {
2357 array[i] >>= bits;
2358 if (i > 0) {
2359 array[i] |= (array[i - 1] << (8 - bits));
2360 }
2361 }
2362 }
2363 return array;
2364 },
2365
2366 /**
2367 * Get native Web Cryptography api, only the current version of the spec.
2368 * @returns {Object} The SubtleCrypto api or 'undefined'.
2369 */
2370 getWebCrypto: function() {
2371 return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;
2372 },
2373
2374 /**
2375 * Get BigInteger class
2376 * It wraps the native BigInt type if it's available
2377 * Otherwise it relies on bn.js
2378 * @returns {BigInteger}
2379 * @async
2380 */
2381 getBigInteger,
2382
2383 /**
2384 * Get native Node.js crypto api.
2385 * @returns {Object} The crypto module or 'undefined'.
2386 */
2387 getNodeCrypto: function() {
2388 return void('crypto');
2389 },
2390
2391 getNodeZlib: function() {
2392 return void('zlib');
2393 },
2394
2395 /**
2396 * Get native Node.js Buffer constructor. This should be used since
2397 * Buffer is not available under browserify.
2398 * @returns {Function} The Buffer constructor or 'undefined'.
2399 */
2400 getNodeBuffer: function() {
2401 return ({}).Buffer;
2402 },
2403
2404 getHardwareConcurrency: function() {
2405 if (typeof navigator !== 'undefined') {
2406 return navigator.hardwareConcurrency || 1;
2407 }
2408
2409 const os = void('os'); // Assume we're on Node.js.
2410 return os.cpus().length;
2411 },
2412
2413 isEmailAddress: function(data) {
2414 if (!util.isString(data)) {
2415 return false;
2416 }
2417 const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+([a-zA-Z]{2,}[0-9]*|xn--[a-zA-Z\-0-9]+)))$/;
2418 return re.test(data);
2419 },
2420
2421 /**
2422 * Normalize line endings to <CR><LF>
2423 * Support any encoding where CR=0x0D, LF=0x0A
2424 */
2425 canonicalizeEOL: function(data) {
2426 const CR = 13;
2427 const LF = 10;
2428 let carryOverCR = false;
2429
2430 return transform(data, bytes => {
2431 if (carryOverCR) {
2432 bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);
2433 }
2434
2435 if (bytes[bytes.length - 1] === CR) {
2436 carryOverCR = true;
2437 bytes = bytes.subarray(0, -1);
2438 } else {
2439 carryOverCR = false;
2440 }
2441
2442 let index;
2443 const indices = [];
2444 for (let i = 0; ; i = index) {
2445 index = bytes.indexOf(LF, i) + 1;
2446 if (index) {
2447 if (bytes[index - 2] !== CR) indices.push(index);
2448 } else {
2449 break;
2450 }
2451 }
2452 if (!indices.length) {
2453 return bytes;
2454 }
2455
2456 const normalized = new Uint8Array(bytes.length + indices.length);
2457 let j = 0;
2458 for (let i = 0; i < indices.length; i++) {
2459 const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);
2460 normalized.set(sub, j);
2461 j += sub.length;
2462 normalized[j - 1] = CR;
2463 normalized[j] = LF;
2464 j++;
2465 }
2466 normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);
2467 return normalized;
2468 }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));
2469 },
2470
2471 /**
2472 * Convert line endings from canonicalized <CR><LF> to native <LF>
2473 * Support any encoding where CR=0x0D, LF=0x0A
2474 */
2475 nativeEOL: function(data) {
2476 const CR = 13;
2477 const LF = 10;
2478 let carryOverCR = false;
2479
2480 return transform(data, bytes => {
2481 if (carryOverCR && bytes[0] !== LF) {
2482 bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);
2483 } else {
2484 bytes = new Uint8Array(bytes); // Don't mutate passed bytes
2485 }
2486
2487 if (bytes[bytes.length - 1] === CR) {
2488 carryOverCR = true;
2489 bytes = bytes.subarray(0, -1);
2490 } else {
2491 carryOverCR = false;
2492 }
2493
2494 let index;
2495 let j = 0;
2496 for (let i = 0; i !== bytes.length; i = index) {
2497 index = bytes.indexOf(CR, i) + 1;
2498 if (!index) index = bytes.length;
2499 const last = index - (bytes[index] === LF ? 1 : 0);
2500 if (i) bytes.copyWithin(j, i, last);
2501 j += last - i;
2502 }
2503 return bytes.subarray(0, j);
2504 }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));
2505 },
2506
2507 /**
2508 * Remove trailing spaces, carriage returns and tabs from each line
2509 */
2510 removeTrailingSpaces: function(text) {
2511 return text.split('\n').map(line => {
2512 let i = line.length - 1;
2513 for (; i >= 0 && (line[i] === ' ' || line[i] === '\t' || line[i] === '\r'); i--);
2514 return line.substr(0, i + 1);
2515 }).join('\n');
2516 },
2517
2518 wrapError: function(message, error) {
2519 if (!error) {
2520 return new Error(message);
2521 }
2522
2523 // update error message
2524 try {
2525 error.message = message + ': ' + error.message;
2526 } catch (e) {}
2527
2528 return error;
2529 },
2530
2531 /**
2532 * Map allowed packet tags to corresponding classes
2533 * Meant to be used to format `allowedPacket` for Packetlist.read
2534 * @param {Array<Object>} allowedClasses
2535 * @returns {Object} map from enum.packet to corresponding *Packet class
2536 */
2537 constructAllowedPackets: function(allowedClasses) {
2538 const map = {};
2539 allowedClasses.forEach(PacketClass => {
2540 if (!PacketClass.tag) {
2541 throw new Error('Invalid input: expected a packet class');
2542 }
2543 map[PacketClass.tag] = PacketClass;
2544 });
2545 return map;
2546 },
2547
2548 /**
2549 * Return a Promise that will resolve as soon as one of the promises in input resolves
2550 * or will reject if all input promises all rejected
2551 * (similar to Promise.any, but with slightly different error handling)
2552 * @param {Array<Promise>} promises
2553 * @return {Promise<Any>} Promise resolving to the result of the fastest fulfilled promise
2554 * or rejected with the Error of the last resolved Promise (if all promises are rejected)
2555 */
2556 anyPromise: function(promises) {
2557 // eslint-disable-next-line no-async-promise-executor
2558 return new Promise(async (resolve, reject) => {
2559 let exception;
2560 await Promise.all(promises.map(async promise => {
2561 try {
2562 resolve(await promise);
2563 } catch (e) {
2564 exception = e;
2565 }
2566 }));
2567 reject(exception);
2568 });
2569 },
2570
2571 /**
2572 * Return either `a` or `b` based on `cond`, in algorithmic constant time.
2573 * @param {Boolean} cond
2574 * @param {Uint8Array} a
2575 * @param {Uint8Array} b
2576 * @returns `a` if `cond` is true, `b` otherwise
2577 */
2578 selectUint8Array: function(cond, a, b) {
2579 const length = Math.max(a.length, b.length);
2580 const result = new Uint8Array(length);
2581 let end = 0;
2582 for (let i = 0; i < result.length; i++) {
2583 result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond));
2584 end += (cond & i < a.length) | ((1 - cond) & i < b.length);
2585 }
2586 return result.subarray(0, end);
2587 },
2588 /**
2589 * Return either `a` or `b` based on `cond`, in algorithmic constant time.
2590 * NB: it only supports `a, b` with values between 0-255.
2591 * @param {Boolean} cond
2592 * @param {Uint8} a
2593 * @param {Uint8} b
2594 * @returns `a` if `cond` is true, `b` otherwise
2595 */
2596 selectUint8: function(cond, a, b) {
2597 return (a & (256 - cond)) | (b & (255 + cond));
2598 },
2599 /**
2600 * @param {module:enums.symmetric} cipherAlgo
2601 */
2602 isAES: function(cipherAlgo) {
2603 return cipherAlgo === enums.symmetric.aes128 || cipherAlgo === enums.symmetric.aes192 || cipherAlgo === enums.symmetric.aes256;
2604 }
2605};
2606
2607/* OpenPGP radix-64/base64 string encoding/decoding
2608 * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de
2609 * version 1.0, check www.haneWIN.de for the latest version
2610 *
2611 * This software is provided as-is, without express or implied warranty.
2612 * Permission to use, copy, modify, distribute or sell this software, with or
2613 * without fee, for any purpose and by any individual or organization, is hereby
2614 * granted, provided that the above copyright notice and this paragraph appear
2615 * in all copies. Distribution as a part of an application or binary must
2616 * include the above copyright notice in the documentation and/or other materials
2617 * provided with the application or distribution.
2618 */
2619
2620const Buffer = util.getNodeBuffer();
2621
2622let encodeChunk;
2623let decodeChunk;
2624if (Buffer) {
2625 encodeChunk = buf => Buffer.from(buf).toString('base64');
2626 decodeChunk = str => {
2627 const b = Buffer.from(str, 'base64');
2628 return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
2629 };
2630} else {
2631 encodeChunk = buf => btoa(util.uint8ArrayToString(buf));
2632 decodeChunk = str => util.stringToUint8Array(atob(str));
2633}
2634
2635/**
2636 * Convert binary array to radix-64
2637 * @param {Uint8Array | ReadableStream<Uint8Array>} data - Uint8Array to convert
2638 * @returns {String | ReadableStream<String>} Radix-64 version of input string.
2639 * @static
2640 */
2641function encode(data) {
2642 let buf = new Uint8Array();
2643 return transform(data, value => {
2644 buf = util.concatUint8Array([buf, value]);
2645 const r = [];
2646 const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).
2647 const lines = Math.floor(buf.length / bytesPerLine);
2648 const bytes = lines * bytesPerLine;
2649 const encoded = encodeChunk(buf.subarray(0, bytes));
2650 for (let i = 0; i < lines; i++) {
2651 r.push(encoded.substr(i * 60, 60));
2652 r.push('\n');
2653 }
2654 buf = buf.subarray(bytes);
2655 return r.join('');
2656 }, () => (buf.length ? encodeChunk(buf) + '\n' : ''));
2657}
2658
2659/**
2660 * Convert radix-64 to binary array
2661 * @param {String | ReadableStream<String>} data - Radix-64 string to convert
2662 * @returns {Uint8Array | ReadableStream<Uint8Array>} Binary array version of input string.
2663 * @static
2664 */
2665function decode(data) {
2666 let buf = '';
2667 return transform(data, value => {
2668 buf += value;
2669
2670 // Count how many whitespace characters there are in buf
2671 let spaces = 0;
2672 const spacechars = [' ', '\t', '\r', '\n'];
2673 for (let i = 0; i < spacechars.length; i++) {
2674 const spacechar = spacechars[i];
2675 for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {
2676 spaces++;
2677 }
2678 }
2679
2680 // Backtrack until we have 4n non-whitespace characters
2681 // that we can safely base64-decode
2682 let length = buf.length;
2683 for (; length > 0 && (length - spaces) % 4 !== 0; length--) {
2684 if (spacechars.includes(buf[length])) spaces--;
2685 }
2686
2687 const decoded = decodeChunk(buf.substr(0, length));
2688 buf = buf.substr(length);
2689 return decoded;
2690 }, () => decodeChunk(buf));
2691}
2692
2693/**
2694 * Convert a Base-64 encoded string an array of 8-bit integer
2695 *
2696 * Note: accepts both Radix-64 and URL-safe strings
2697 * @param {String} base64 - Base-64 encoded string to convert
2698 * @returns {Uint8Array} An array of 8-bit integers.
2699 */
2700function b64ToUint8Array(base64) {
2701 return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));
2702}
2703
2704/**
2705 * Convert an array of 8-bit integer to a Base-64 encoded string
2706 * @param {Uint8Array} bytes - An array of 8-bit integers to convert
2707 * @param {bool} url - If true, output is URL-safe
2708 * @returns {String} Base-64 encoded string.
2709 */
2710function uint8ArrayToB64(bytes, url) {
2711 let encoded = encode(bytes).replace(/[\r\n]/g, '');
2712 if (url) {
2713 encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');
2714 }
2715 return encoded;
2716}
2717
2718// GPG4Browsers - An OpenPGP implementation in javascript
2719
2720var config = {
2721 /**
2722 * @memberof module:config
2723 * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}
2724 */
2725 preferredHashAlgorithm: enums.hash.sha256,
2726 /**
2727 * @memberof module:config
2728 * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}
2729 */
2730 preferredSymmetricAlgorithm: enums.symmetric.aes256,
2731 /**
2732 * @memberof module:config
2733 * @property {Integer} compression Default compression algorithm {@link module:enums.compression}
2734 */
2735 preferredCompressionAlgorithm: enums.compression.uncompressed,
2736 /**
2737 * @memberof module:config
2738 * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9
2739 */
2740 deflateLevel: 6,
2741
2742 /**
2743 * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.
2744 * Note: not all OpenPGP implementations are compatible with this option.
2745 * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
2746 * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07}
2747 * @memberof module:config
2748 * @property {Boolean} aeadProtect
2749 */
2750 aeadProtect: false,
2751 /**
2752 * Default Authenticated Encryption with Additional Data (AEAD) encryption mode
2753 * Only has an effect when aeadProtect is set to true.
2754 * @memberof module:config
2755 * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}
2756 */
2757 preferredAEADAlgorithm: enums.aead.eax,
2758 /**
2759 * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode
2760 * Only has an effect when aeadProtect is set to true.
2761 * Must be an integer value from 0 to 56.
2762 * @memberof module:config
2763 * @property {Integer} aeadChunkSizeByte
2764 */
2765 aeadChunkSizeByte: 12,
2766 /**
2767 * Use V5 keys.
2768 * Note: not all OpenPGP implementations are compatible with this option.
2769 * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
2770 * @memberof module:config
2771 * @property {Boolean} v5Keys
2772 */
2773 v5Keys: false,
2774 /**
2775 * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}:
2776 * Iteration Count Byte for S2K (String to Key)
2777 * @memberof module:config
2778 * @property {Integer} s2kIterationCountByte
2779 */
2780 s2kIterationCountByte: 224,
2781 /**
2782 * Allow decryption of messages without integrity protection.
2783 * This is an **insecure** setting:
2784 * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.
2785 * - it enables downgrade attacks against integrity-protected messages.
2786 * @memberof module:config
2787 * @property {Boolean} allowUnauthenticatedMessages
2788 */
2789 allowUnauthenticatedMessages: false,
2790 /**
2791 * Allow streaming unauthenticated data before its integrity has been checked. This would allow the application to
2792 * process large streams while limiting memory usage by releasing the decrypted chunks as soon as possible
2793 * and deferring checking their integrity until the decrypted stream has been read in full.
2794 *
2795 * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user.
2796 * @memberof module:config
2797 * @property {Boolean} allowUnauthenticatedStream
2798 */
2799 allowUnauthenticatedStream: false,
2800 /**
2801 * @memberof module:config
2802 * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum
2803 */
2804 checksumRequired: false,
2805 /**
2806 * Minimum RSA key size allowed for key generation and message signing, verification and encryption.
2807 * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.
2808 * @memberof module:config
2809 * @property {Number} minRSABits
2810 */
2811 minRSABits: 2047,
2812 /**
2813 * Work-around for rare GPG decryption bug when encrypting with multiple passwords.
2814 * **Slower and slightly less secure**
2815 * @memberof module:config
2816 * @property {Boolean} passwordCollisionCheck
2817 */
2818 passwordCollisionCheck: false,
2819 /**
2820 * @memberof module:config
2821 * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored
2822 */
2823 revocationsExpire: false,
2824 /**
2825 * Allow decryption using RSA keys without `encrypt` flag.
2826 * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug
2827 * where key flags were ignored when selecting a key for encryption.
2828 * @memberof module:config
2829 * @property {Boolean} allowInsecureDecryptionWithSigningKeys
2830 */
2831 allowInsecureDecryptionWithSigningKeys: false,
2832 /**
2833 * Allow verification of message signatures with keys whose validity at the time of signing cannot be determined.
2834 * Instead, a verification key will also be consider valid as long as it is valid at the current time.
2835 * This setting is potentially insecure, but it is needed to verify messages signed with keys that were later reformatted,
2836 * and have self-signature's creation date that does not match the primary key creation date.
2837 * @memberof module:config
2838 * @property {Boolean} allowInsecureDecryptionWithSigningKeys
2839 */
2840 allowInsecureVerificationWithReformattedKeys: false,
2841
2842 /**
2843 * Enable constant-time decryption of RSA- and ElGamal-encrypted session keys, to hinder Bleichenbacher-like attacks (https://link.springer.com/chapter/10.1007/BFb0055716).
2844 * This setting has measurable performance impact and it is only helpful in application scenarios where both of the following conditions apply:
2845 * - new/incoming messages are automatically decrypted (without user interaction);
2846 * - an attacker can determine how long it takes to decrypt each message (e.g. due to decryption errors being logged remotely).
2847 * See also `constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`.
2848 * @memberof module:config
2849 * @property {Boolean} constantTimePKCS1Decryption
2850 */
2851 constantTimePKCS1Decryption: false,
2852 /**
2853 * This setting is only meaningful if `constantTimePKCS1Decryption` is enabled.
2854 * Decryption of RSA- and ElGamal-encrypted session keys of symmetric algorithms different from the ones specified here will fail.
2855 * However, the more algorithms are added, the slower the decryption procedure becomes.
2856 * @memberof module:config
2857 * @property {Set<Integer>} constantTimePKCS1DecryptionSupportedSymmetricAlgorithms {@link module:enums.symmetric}
2858 */
2859 constantTimePKCS1DecryptionSupportedSymmetricAlgorithms: new Set([enums.symmetric.aes128, enums.symmetric.aes192, enums.symmetric.aes256]),
2860
2861 /**
2862 * @memberof module:config
2863 * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available
2864 */
2865 minBytesForWebCrypto: 1000,
2866 /**
2867 * @memberof module:config
2868 * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error
2869 */
2870 ignoreUnsupportedPackets: true,
2871 /**
2872 * @memberof module:config
2873 * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error
2874 */
2875 ignoreMalformedPackets: false,
2876 /**
2877 * Parsing of packets is normally restricted to a predefined set of packets. For example a Sym. Encrypted Integrity Protected Data Packet can only
2878 * contain a certain set of packets including LiteralDataPacket. With this setting we can allow additional packets, which is probably not advisable
2879 * as a global config setting, but can be used for specific function calls (e.g. decrypt method of Message).
2880 * @memberof module:config
2881 * @property {Array} additionalAllowedPackets Allow additional packets on parsing. Defined as array of packet classes, e.g. [PublicKeyPacket]
2882 */
2883 additionalAllowedPackets: [],
2884 /**
2885 * @memberof module:config
2886 * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages
2887 */
2888 showVersion: false,
2889 /**
2890 * @memberof module:config
2891 * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages
2892 */
2893 showComment: false,
2894 /**
2895 * @memberof module:config
2896 * @property {String} versionString A version string to be included in armored messages
2897 */
2898 versionString: 'OpenPGP.js 5.11.0',
2899 /**
2900 * @memberof module:config
2901 * @property {String} commentString A comment string to be included in armored messages
2902 */
2903 commentString: 'https://openpgpjs.org',
2904
2905 /**
2906 * Max userID string length (used for parsing)
2907 * @memberof module:config
2908 * @property {Integer} maxUserIDLength
2909 */
2910 maxUserIDLength: 1024 * 5,
2911 /**
2912 * Contains notatations that are considered "known". Known notations do not trigger
2913 * validation error when the notation is marked as critical.
2914 * @memberof module:config
2915 * @property {Array} knownNotations
2916 */
2917 knownNotations: [],
2918 /**
2919 * Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API.
2920 * When false, certain standard curves will not be supported (depending on the platform).
2921 * Note: the indutny/elliptic curve library is not designed to be constant time.
2922 * @memberof module:config
2923 * @property {Boolean} useIndutnyElliptic
2924 */
2925 useIndutnyElliptic: true,
2926 /**
2927 * Reject insecure hash algorithms
2928 * @memberof module:config
2929 * @property {Set<Integer>} rejectHashAlgorithms {@link module:enums.hash}
2930 */
2931 rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),
2932 /**
2933 * Reject insecure message hash algorithms
2934 * @memberof module:config
2935 * @property {Set<Integer>} rejectMessageHashAlgorithms {@link module:enums.hash}
2936 */
2937 rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),
2938 /**
2939 * Reject insecure public key algorithms for key generation and message encryption, signing or verification
2940 * @memberof module:config
2941 * @property {Set<Integer>} rejectPublicKeyAlgorithms {@link module:enums.publicKey}
2942 */
2943 rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),
2944 /**
2945 * Reject non-standard curves for key generation, message encryption, signing or verification
2946 * @memberof module:config
2947 * @property {Set<String>} rejectCurves {@link module:enums.curve}
2948 */
2949 rejectCurves: new Set([enums.curve.secp256k1])
2950};
2951
2952/**
2953 * @fileoverview This object contains global configuration values.
2954 * @see module:config/config
2955 * @module config
2956 */
2957
2958// GPG4Browsers - An OpenPGP implementation in javascript
2959
2960/**
2961 * Finds out which Ascii Armoring type is used. Throws error if unknown type.
2962 * @param {String} text - ascii armored text
2963 * @returns {Integer} 0 = MESSAGE PART n of m.
2964 * 1 = MESSAGE PART n
2965 * 2 = SIGNED MESSAGE
2966 * 3 = PGP MESSAGE
2967 * 4 = PUBLIC KEY BLOCK
2968 * 5 = PRIVATE KEY BLOCK
2969 * 6 = SIGNATURE
2970 * @private
2971 */
2972function getType(text) {
2973 const reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;
2974
2975 const header = text.match(reHeader);
2976
2977 if (!header) {
2978 throw new Error('Unknown ASCII armor type');
2979 }
2980
2981 // BEGIN PGP MESSAGE, PART X/Y
2982 // Used for multi-part messages, where the armor is split amongst Y
2983 // parts, and this is the Xth part out of Y.
2984 if (/MESSAGE, PART \d+\/\d+/.test(header[1])) {
2985 return enums.armor.multipartSection;
2986 } else
2987 // BEGIN PGP MESSAGE, PART X
2988 // Used for multi-part messages, where this is the Xth part of an
2989 // unspecified number of parts. Requires the MESSAGE-ID Armor
2990 // Header to be used.
2991 if (/MESSAGE, PART \d+/.test(header[1])) {
2992 return enums.armor.multipartLast;
2993 } else
2994 // BEGIN PGP SIGNED MESSAGE
2995 if (/SIGNED MESSAGE/.test(header[1])) {
2996 return enums.armor.signed;
2997 } else
2998 // BEGIN PGP MESSAGE
2999 // Used for signed, encrypted, or compressed files.
3000 if (/MESSAGE/.test(header[1])) {
3001 return enums.armor.message;
3002 } else
3003 // BEGIN PGP PUBLIC KEY BLOCK
3004 // Used for armoring public keys.
3005 if (/PUBLIC KEY BLOCK/.test(header[1])) {
3006 return enums.armor.publicKey;
3007 } else
3008 // BEGIN PGP PRIVATE KEY BLOCK
3009 // Used for armoring private keys.
3010 if (/PRIVATE KEY BLOCK/.test(header[1])) {
3011 return enums.armor.privateKey;
3012 } else
3013 // BEGIN PGP SIGNATURE
3014 // Used for detached signatures, OpenPGP/MIME signatures, and
3015 // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE
3016 // for detached signatures.
3017 if (/SIGNATURE/.test(header[1])) {
3018 return enums.armor.signature;
3019 }
3020}
3021
3022/**
3023 * Add additional information to the armor version of an OpenPGP binary
3024 * packet block.
3025 * @author Alex
3026 * @version 2011-12-16
3027 * @param {String} [customComment] - Additional comment to add to the armored string
3028 * @returns {String} The header information.
3029 * @private
3030 */
3031function addheader(customComment, config) {
3032 let result = '';
3033 if (config.showVersion) {
3034 result += 'Version: ' + config.versionString + '\n';
3035 }
3036 if (config.showComment) {
3037 result += 'Comment: ' + config.commentString + '\n';
3038 }
3039 if (customComment) {
3040 result += 'Comment: ' + customComment + '\n';
3041 }
3042 result += '\n';
3043 return result;
3044}
3045
3046
3047/**
3048 * Calculates a checksum over the given data and returns it base64 encoded
3049 * @param {String | ReadableStream<String>} data - Data to create a CRC-24 checksum for
3050 * @returns {String | ReadableStream<String>} Base64 encoded checksum.
3051 * @private
3052 */
3053function getCheckSum(data) {
3054 const crc = createcrc24(data);
3055 return encode(crc);
3056}
3057
3058// https://create.stephan-brumme.com/crc32/#slicing-by-8-overview
3059
3060const crc_table = [
3061 new Array(0xFF),
3062 new Array(0xFF),
3063 new Array(0xFF),
3064 new Array(0xFF)
3065];
3066
3067for (let i = 0; i <= 0xFF; i++) {
3068 let crc = i << 16;
3069 for (let j = 0; j < 8; j++) {
3070 crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);
3071 }
3072 crc_table[0][i] =
3073 ((crc & 0xFF0000) >> 16) |
3074 (crc & 0x00FF00) |
3075 ((crc & 0x0000FF) << 16);
3076}
3077for (let i = 0; i <= 0xFF; i++) {
3078 crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];
3079}
3080for (let i = 0; i <= 0xFF; i++) {
3081 crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];
3082}
3083for (let i = 0; i <= 0xFF; i++) {
3084 crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];
3085}
3086
3087// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness
3088const isLittleEndian = (function() {
3089 const buffer = new ArrayBuffer(2);
3090 new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);
3091 // Int16Array uses the platform's endianness.
3092 return new Int16Array(buffer)[0] === 0xFF;
3093}());
3094
3095/**
3096 * Internal function to calculate a CRC-24 checksum over a given string (data)
3097 * @param {String | ReadableStream<String>} input - Data to create a CRC-24 checksum for
3098 * @returns {Uint8Array | ReadableStream<Uint8Array>} The CRC-24 checksum.
3099 * @private
3100 */
3101function createcrc24(input) {
3102 let crc = 0xCE04B7;
3103 return transform(input, value => {
3104 const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;
3105 const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);
3106 for (let i = 0; i < len32; i++) {
3107 crc ^= arr32[i];
3108 crc =
3109 crc_table[0][(crc >> 24) & 0xFF] ^
3110 crc_table[1][(crc >> 16) & 0xFF] ^
3111 crc_table[2][(crc >> 8) & 0xFF] ^
3112 crc_table[3][(crc >> 0) & 0xFF];
3113 }
3114 for (let i = len32 * 4; i < value.length; i++) {
3115 crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];
3116 }
3117 }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));
3118}
3119
3120/**
3121 * Verify armored headers. crypto-refresh-06, section 6.2:
3122 * "An OpenPGP implementation may consider improperly formatted Armor
3123 * Headers to be corruption of the ASCII Armor, but SHOULD make an
3124 * effort to recover."
3125 * @private
3126 * @param {Array<String>} headers - Armor headers
3127 */
3128function verifyHeaders(headers) {
3129 for (let i = 0; i < headers.length; i++) {
3130 if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) {
3131 util.printDebugError(new Error('Improperly formatted armor header: ' + headers[i]));
3132 }
3133 if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {
3134 util.printDebugError(new Error('Unknown header: ' + headers[i]));
3135 }
3136 }
3137}
3138
3139/**
3140 * Splits a message into two parts, the body and the checksum. This is an internal function
3141 * @param {String} text - OpenPGP armored message part
3142 * @returns {Object} An object with attribute "body" containing the body.
3143 * and an attribute "checksum" containing the checksum.
3144 * @private
3145 */
3146function splitChecksum(text) {
3147 let body = text;
3148 let checksum = '';
3149
3150 const lastEquals = text.lastIndexOf('=');
3151
3152 if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum
3153 body = text.slice(0, lastEquals);
3154 checksum = text.slice(lastEquals + 1).substr(0, 4);
3155 }
3156
3157 return { body: body, checksum: checksum };
3158}
3159
3160/**
3161 * Dearmor an OpenPGP armored message; verify the checksum and return
3162 * the encoded bytes
3163 * @param {String} input - OpenPGP armored message
3164 * @returns {Promise<Object>} An object with attribute "text" containing the message text,
3165 * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type
3166 * @async
3167 * @static
3168 */
3169function unarmor(input, config$1 = config) {
3170 // eslint-disable-next-line no-async-promise-executor
3171 return new Promise(async (resolve, reject) => {
3172 try {
3173 const reSplit = /^-----[^-]+-----$/m;
3174 const reEmptyLine = /^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;
3175
3176 let type;
3177 const headers = [];
3178 let lastHeaders = headers;
3179 let headersDone;
3180 let text = [];
3181 let textDone;
3182 let checksum;
3183 let data = decode(transformPair(input, async (readable, writable) => {
3184 const reader = getReader(readable);
3185 try {
3186 while (true) {
3187 let line = await reader.readLine();
3188 if (line === undefined) {
3189 throw new Error('Misformed armored text');
3190 }
3191 // remove trailing whitespace at end of lines
3192 line = util.removeTrailingSpaces(line.replace(/[\r\n]/g, ''));
3193 if (!type) {
3194 if (reSplit.test(line)) {
3195 type = getType(line);
3196 }
3197 } else if (!headersDone) {
3198 if (reSplit.test(line)) {
3199 reject(new Error('Mandatory blank line missing between armor headers and armor data'));
3200 }
3201 if (!reEmptyLine.test(line)) {
3202 lastHeaders.push(line);
3203 } else {
3204 verifyHeaders(lastHeaders);
3205 headersDone = true;
3206 if (textDone || type !== 2) {
3207 resolve({ text, data, headers, type });
3208 break;
3209 }
3210 }
3211 } else if (!textDone && type === 2) {
3212 if (!reSplit.test(line)) {
3213 // Reverse dash-escaping for msg
3214 text.push(line.replace(/^- /, ''));
3215 } else {
3216 text = text.join('\r\n');
3217 textDone = true;
3218 verifyHeaders(lastHeaders);
3219 lastHeaders = [];
3220 headersDone = false;
3221 }
3222 }
3223 }
3224 } catch (e) {
3225 reject(e);
3226 return;
3227 }
3228 const writer = getWriter(writable);
3229 try {
3230 while (true) {
3231 await writer.ready;
3232 const { done, value } = await reader.read();
3233 if (done) {
3234 throw new Error('Misformed armored text');
3235 }
3236 const line = value + '';
3237 if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {
3238 await writer.write(line);
3239 } else {
3240 let remainder = await reader.readToEnd();
3241 if (!remainder.length) remainder = '';
3242 remainder = line + remainder;
3243 remainder = util.removeTrailingSpaces(remainder.replace(/\r/g, ''));
3244 const parts = remainder.split(reSplit);
3245 if (parts.length === 1) {
3246 throw new Error('Misformed armored text');
3247 }
3248 const split = splitChecksum(parts[0].slice(0, -1));
3249 checksum = split.checksum;
3250 await writer.write(split.body);
3251 break;
3252 }
3253 }
3254 await writer.ready;
3255 await writer.close();
3256 } catch (e) {
3257 await writer.abort(e);
3258 }
3259 }));
3260 data = transformPair(data, async (readable, writable) => {
3261 const checksumVerified = readToEnd(getCheckSum(passiveClone(readable)));
3262 checksumVerified.catch(() => {});
3263 await pipe(readable, writable, {
3264 preventClose: true
3265 });
3266 const writer = getWriter(writable);
3267 try {
3268 const checksumVerifiedString = (await checksumVerified).replace('\n', '');
3269 if (checksum !== checksumVerifiedString && (checksum || config$1.checksumRequired)) {
3270 throw new Error('Ascii armor integrity check failed');
3271 }
3272 await writer.ready;
3273 await writer.close();
3274 } catch (e) {
3275 await writer.abort(e);
3276 }
3277 });
3278 } catch (e) {
3279 reject(e);
3280 }
3281 }).then(async result => {
3282 if (isArrayStream(result.data)) {
3283 result.data = await readToEnd(result.data);
3284 }
3285 return result;
3286 });
3287}
3288
3289
3290/**
3291 * Armor an OpenPGP binary packet block
3292 * @param {module:enums.armor} messageType - Type of the message
3293 * @param {Uint8Array | ReadableStream<Uint8Array>} body - The message body to armor
3294 * @param {Integer} [partIndex]
3295 * @param {Integer} [partTotal]
3296 * @param {String} [customComment] - Additional comment to add to the armored string
3297 * @returns {String | ReadableStream<String>} Armored text.
3298 * @static
3299 */
3300function armor(messageType, body, partIndex, partTotal, customComment, config$1 = config) {
3301 let text;
3302 let hash;
3303 if (messageType === enums.armor.signed) {
3304 text = body.text;
3305 hash = body.hash;
3306 body = body.data;
3307 }
3308 const bodyClone = passiveClone(body);
3309 const result = [];
3310 switch (messageType) {
3311 case enums.armor.multipartSection:
3312 result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n');
3313 result.push(addheader(customComment, config$1));
3314 result.push(encode(body));
3315 result.push('=', getCheckSum(bodyClone));
3316 result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n');
3317 break;
3318 case enums.armor.multipartLast:
3319 result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\n');
3320 result.push(addheader(customComment, config$1));
3321 result.push(encode(body));
3322 result.push('=', getCheckSum(bodyClone));
3323 result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\n');
3324 break;
3325 case enums.armor.signed:
3326 result.push('-----BEGIN PGP SIGNED MESSAGE-----\n');
3327 result.push('Hash: ' + hash + '\n\n');
3328 result.push(text.replace(/^-/mg, '- -'));
3329 result.push('\n-----BEGIN PGP SIGNATURE-----\n');
3330 result.push(addheader(customComment, config$1));
3331 result.push(encode(body));
3332 result.push('=', getCheckSum(bodyClone));
3333 result.push('-----END PGP SIGNATURE-----\n');
3334 break;
3335 case enums.armor.message:
3336 result.push('-----BEGIN PGP MESSAGE-----\n');
3337 result.push(addheader(customComment, config$1));
3338 result.push(encode(body));
3339 result.push('=', getCheckSum(bodyClone));
3340 result.push('-----END PGP MESSAGE-----\n');
3341 break;
3342 case enums.armor.publicKey:
3343 result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\n');
3344 result.push(addheader(customComment, config$1));
3345 result.push(encode(body));
3346 result.push('=', getCheckSum(bodyClone));
3347 result.push('-----END PGP PUBLIC KEY BLOCK-----\n');
3348 break;
3349 case enums.armor.privateKey:
3350 result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\n');
3351 result.push(addheader(customComment, config$1));
3352 result.push(encode(body));
3353 result.push('=', getCheckSum(bodyClone));
3354 result.push('-----END PGP PRIVATE KEY BLOCK-----\n');
3355 break;
3356 case enums.armor.signature:
3357 result.push('-----BEGIN PGP SIGNATURE-----\n');
3358 result.push(addheader(customComment, config$1));
3359 result.push(encode(body));
3360 result.push('=', getCheckSum(bodyClone));
3361 result.push('-----END PGP SIGNATURE-----\n');
3362 break;
3363 }
3364
3365 return util.concat(result);
3366}
3367
3368// GPG4Browsers - An OpenPGP implementation in javascript
3369
3370/**
3371 * Implementation of type key id
3372 *
3373 * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:
3374 * A Key ID is an eight-octet scalar that identifies a key.
3375 * Implementations SHOULD NOT assume that Key IDs are unique. The
3376 * section "Enhanced Key Formats" below describes how Key IDs are
3377 * formed.
3378 */
3379class KeyID {
3380 constructor() {
3381 this.bytes = '';
3382 }
3383
3384 /**
3385 * Parsing method for a key id
3386 * @param {Uint8Array} bytes - Input to read the key id from
3387 */
3388 read(bytes) {
3389 this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));
3390 return this.bytes.length;
3391 }
3392
3393 /**
3394 * Serializes the Key ID
3395 * @returns {Uint8Array} Key ID as a Uint8Array.
3396 */
3397 write() {
3398 return util.stringToUint8Array(this.bytes);
3399 }
3400
3401 /**
3402 * Returns the Key ID represented as a hexadecimal string
3403 * @returns {String} Key ID as a hexadecimal string.
3404 */
3405 toHex() {
3406 return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));
3407 }
3408
3409 /**
3410 * Checks equality of Key ID's
3411 * @param {KeyID} keyID
3412 * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard
3413 */
3414 equals(keyID, matchWildcard = false) {
3415 return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;
3416 }
3417
3418 /**
3419 * Checks to see if the Key ID is unset
3420 * @returns {Boolean} True if the Key ID is null.
3421 */
3422 isNull() {
3423 return this.bytes === '';
3424 }
3425
3426 /**
3427 * Checks to see if the Key ID is a "wildcard" Key ID (all zeros)
3428 * @returns {Boolean} True if this is a wildcard Key ID.
3429 */
3430 isWildcard() {
3431 return /^0+$/.test(this.toHex());
3432 }
3433
3434 static mapToHex(keyID) {
3435 return keyID.toHex();
3436 }
3437
3438 static fromID(hex) {
3439 const keyID = new KeyID();
3440 keyID.read(util.hexToUint8Array(hex));
3441 return keyID;
3442 }
3443
3444 static wildcard() {
3445 const keyID = new KeyID();
3446 keyID.read(new Uint8Array(8));
3447 return keyID;
3448 }
3449}
3450
3451/**
3452 * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}.
3453 * @author Artem S Vybornov <vybornov@gmail.com>
3454 * @license MIT
3455 */
3456var AES_asm = function () {
3457
3458 /**
3459 * Galois Field stuff init flag
3460 */
3461 var ginit_done = false;
3462
3463 /**
3464 * Galois Field exponentiation and logarithm tables for 3 (the generator)
3465 */
3466 var gexp3, glog3;
3467
3468 /**
3469 * Init Galois Field tables
3470 */
3471 function ginit() {
3472 gexp3 = [],
3473 glog3 = [];
3474
3475 var a = 1, c, d;
3476 for (c = 0; c < 255; c++) {
3477 gexp3[c] = a;
3478
3479 // Multiply by three
3480 d = a & 0x80, a <<= 1, a &= 255;
3481 if (d === 0x80) a ^= 0x1b;
3482 a ^= gexp3[c];
3483
3484 // Set the log table value
3485 glog3[gexp3[c]] = c;
3486 }
3487 gexp3[255] = gexp3[0];
3488 glog3[0] = 0;
3489
3490 ginit_done = true;
3491 }
3492
3493 /**
3494 * Galois Field multiplication
3495 * @param {number} a
3496 * @param {number} b
3497 * @return {number}
3498 */
3499 function gmul(a, b) {
3500 var c = gexp3[(glog3[a] + glog3[b]) % 255];
3501 if (a === 0 || b === 0) c = 0;
3502 return c;
3503 }
3504
3505 /**
3506 * Galois Field reciprocal
3507 * @param {number} a
3508 * @return {number}
3509 */
3510 function ginv(a) {
3511 var i = gexp3[255 - glog3[a]];
3512 if (a === 0) i = 0;
3513 return i;
3514 }
3515
3516 /**
3517 * AES stuff init flag
3518 */
3519 var aes_init_done = false;
3520
3521 /**
3522 * Encryption, Decryption, S-Box and KeyTransform tables
3523 *
3524 * @type {number[]}
3525 */
3526 var aes_sbox;
3527
3528 /**
3529 * @type {number[]}
3530 */
3531 var aes_sinv;
3532
3533 /**
3534 * @type {number[][]}
3535 */
3536 var aes_enc;
3537
3538 /**
3539 * @type {number[][]}
3540 */
3541 var aes_dec;
3542
3543 /**
3544 * Init AES tables
3545 */
3546 function aes_init() {
3547 if (!ginit_done) ginit();
3548
3549 // Calculates AES S-Box value
3550 function _s(a) {
3551 var c, s, x;
3552 s = x = ginv(a);
3553 for (c = 0; c < 4; c++) {
3554 s = ((s << 1) | (s >>> 7)) & 255;
3555 x ^= s;
3556 }
3557 x ^= 99;
3558 return x;
3559 }
3560
3561 // Tables
3562 aes_sbox = [],
3563 aes_sinv = [],
3564 aes_enc = [[], [], [], []],
3565 aes_dec = [[], [], [], []];
3566
3567 for (var i = 0; i < 256; i++) {
3568 var s = _s(i);
3569
3570 // S-Box and its inverse
3571 aes_sbox[i] = s;
3572 aes_sinv[s] = i;
3573
3574 // Ecryption and Decryption tables
3575 aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s);
3576 aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i);
3577 // Rotate tables
3578 for (var t = 1; t < 4; t++) {
3579 aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24);
3580 aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24);
3581 }
3582 }
3583
3584 aes_init_done = true;
3585 }
3586
3587 /**
3588 * Asm.js module constructor.
3589 *
3590 * <p>
3591 * Heap buffer layout by offset:
3592 * <pre>
3593 * 0x0000 encryption key schedule
3594 * 0x0400 decryption key schedule
3595 * 0x0800 sbox
3596 * 0x0c00 inv sbox
3597 * 0x1000 encryption tables
3598 * 0x2000 decryption tables
3599 * 0x3000 reserved (future GCM multiplication lookup table)
3600 * 0x4000 data
3601 * </pre>
3602 * Don't touch anything before <code>0x400</code>.
3603 * </p>
3604 *
3605 * @alias AES_asm
3606 * @class
3607 * @param foreign - <i>ignored</i>
3608 * @param buffer - heap buffer to link with
3609 */
3610 var wrapper = function (foreign, buffer) {
3611 // Init AES stuff for the first time
3612 if (!aes_init_done) aes_init();
3613
3614 // Fill up AES tables
3615 var heap = new Uint32Array(buffer);
3616 heap.set(aes_sbox, 0x0800 >> 2);
3617 heap.set(aes_sinv, 0x0c00 >> 2);
3618 for (var i = 0; i < 4; i++) {
3619 heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2);
3620 heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2);
3621 }
3622
3623 /**
3624 * Calculate AES key schedules.
3625 * @instance
3626 * @memberof AES_asm
3627 * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly)
3628 * @param {number} k0 - key vector components
3629 * @param {number} k1 - key vector components
3630 * @param {number} k2 - key vector components
3631 * @param {number} k3 - key vector components
3632 * @param {number} k4 - key vector components
3633 * @param {number} k5 - key vector components
3634 * @param {number} k6 - key vector components
3635 * @param {number} k7 - key vector components
3636 */
3637 function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) {
3638 var ekeys = heap.subarray(0x000, 60),
3639 dkeys = heap.subarray(0x100, 0x100 + 60);
3640
3641 // Encryption key schedule
3642 ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]);
3643 for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) {
3644 var k = ekeys[i - 1];
3645 if ((i % ks === 0) || (ks === 8 && i % ks === 4)) {
3646 k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255];
3647 }
3648 if (i % ks === 0) {
3649 k = (k << 8) ^ (k >>> 24) ^ (rcon << 24);
3650 rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0);
3651 }
3652 ekeys[i] = ekeys[i - ks] ^ k;
3653 }
3654
3655 // Decryption key schedule
3656 for (var j = 0; j < i; j += 4) {
3657 for (var jj = 0; jj < 4; jj++) {
3658 var k = ekeys[i - (4 + j) + (4 - jj) % 4];
3659 if (j < 4 || j >= i - 4) {
3660 dkeys[j + jj] = k;
3661 } else {
3662 dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]]
3663 ^ aes_dec[1][aes_sbox[k >>> 16 & 255]]
3664 ^ aes_dec[2][aes_sbox[k >>> 8 & 255]]
3665 ^ aes_dec[3][aes_sbox[k & 255]];
3666 }
3667 }
3668 }
3669
3670 // Set rounds number
3671 asm.set_rounds(ks + 5);
3672 }
3673
3674 // create library object with necessary properties
3675 var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array};
3676
3677 var asm = function (stdlib, foreign, buffer) {
3678 "use asm";
3679
3680 var S0 = 0, S1 = 0, S2 = 0, S3 = 0,
3681 I0 = 0, I1 = 0, I2 = 0, I3 = 0,
3682 N0 = 0, N1 = 0, N2 = 0, N3 = 0,
3683 M0 = 0, M1 = 0, M2 = 0, M3 = 0,
3684 H0 = 0, H1 = 0, H2 = 0, H3 = 0,
3685 R = 0;
3686
3687 var HEAP = new stdlib.Uint32Array(buffer),
3688 DATA = new stdlib.Uint8Array(buffer);
3689
3690 /**
3691 * AES core
3692 * @param {number} k - precomputed key schedule offset
3693 * @param {number} s - precomputed sbox table offset
3694 * @param {number} t - precomputed round table offset
3695 * @param {number} r - number of inner rounds to perform
3696 * @param {number} x0 - 128-bit input block vector
3697 * @param {number} x1 - 128-bit input block vector
3698 * @param {number} x2 - 128-bit input block vector
3699 * @param {number} x3 - 128-bit input block vector
3700 */
3701 function _core(k, s, t, r, x0, x1, x2, x3) {
3702 k = k | 0;
3703 s = s | 0;
3704 t = t | 0;
3705 r = r | 0;
3706 x0 = x0 | 0;
3707 x1 = x1 | 0;
3708 x2 = x2 | 0;
3709 x3 = x3 | 0;
3710
3711 var t1 = 0, t2 = 0, t3 = 0,
3712 y0 = 0, y1 = 0, y2 = 0, y3 = 0,
3713 i = 0;
3714
3715 t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00;
3716
3717 // round 0
3718 x0 = x0 ^ HEAP[(k | 0) >> 2],
3719 x1 = x1 ^ HEAP[(k | 4) >> 2],
3720 x2 = x2 ^ HEAP[(k | 8) >> 2],
3721 x3 = x3 ^ HEAP[(k | 12) >> 2];
3722
3723 // round 1..r
3724 for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) {
3725 y0 = HEAP[(t | x0 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x1 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x2 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2],
3726 y1 = HEAP[(t | x1 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x2 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x3 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2],
3727 y2 = HEAP[(t | x2 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x3 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x0 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2],
3728 y3 = HEAP[(t | x3 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x0 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x1 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2];
3729 x0 = y0, x1 = y1, x2 = y2, x3 = y3;
3730 }
3731
3732 // final round
3733 S0 = HEAP[(s | x0 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x1 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x2 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2],
3734 S1 = HEAP[(s | x1 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x2 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x3 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2],
3735 S2 = HEAP[(s | x2 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x3 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x0 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2],
3736 S3 = HEAP[(s | x3 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x0 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x1 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2];
3737 }
3738
3739 /**
3740 * ECB mode encryption
3741 * @param {number} x0 - 128-bit input block vector
3742 * @param {number} x1 - 128-bit input block vector
3743 * @param {number} x2 - 128-bit input block vector
3744 * @param {number} x3 - 128-bit input block vector
3745 */
3746 function _ecb_enc(x0, x1, x2, x3) {
3747 x0 = x0 | 0;
3748 x1 = x1 | 0;
3749 x2 = x2 | 0;
3750 x3 = x3 | 0;
3751
3752 _core(
3753 0x0000, 0x0800, 0x1000,
3754 R,
3755 x0,
3756 x1,
3757 x2,
3758 x3
3759 );
3760 }
3761
3762 /**
3763 * ECB mode decryption
3764 * @param {number} x0 - 128-bit input block vector
3765 * @param {number} x1 - 128-bit input block vector
3766 * @param {number} x2 - 128-bit input block vector
3767 * @param {number} x3 - 128-bit input block vector
3768 */
3769 function _ecb_dec(x0, x1, x2, x3) {
3770 x0 = x0 | 0;
3771 x1 = x1 | 0;
3772 x2 = x2 | 0;
3773 x3 = x3 | 0;
3774
3775 var t = 0;
3776
3777 _core(
3778 0x0400, 0x0c00, 0x2000,
3779 R,
3780 x0,
3781 x3,
3782 x2,
3783 x1
3784 );
3785
3786 t = S1, S1 = S3, S3 = t;
3787 }
3788
3789
3790 /**
3791 * CBC mode encryption
3792 * @param {number} x0 - 128-bit input block vector
3793 * @param {number} x1 - 128-bit input block vector
3794 * @param {number} x2 - 128-bit input block vector
3795 * @param {number} x3 - 128-bit input block vector
3796 */
3797 function _cbc_enc(x0, x1, x2, x3) {
3798 x0 = x0 | 0;
3799 x1 = x1 | 0;
3800 x2 = x2 | 0;
3801 x3 = x3 | 0;
3802
3803 _core(
3804 0x0000, 0x0800, 0x1000,
3805 R,
3806 I0 ^ x0,
3807 I1 ^ x1,
3808 I2 ^ x2,
3809 I3 ^ x3
3810 );
3811
3812 I0 = S0,
3813 I1 = S1,
3814 I2 = S2,
3815 I3 = S3;
3816 }
3817
3818 /**
3819 * CBC mode decryption
3820 * @param {number} x0 - 128-bit input block vector
3821 * @param {number} x1 - 128-bit input block vector
3822 * @param {number} x2 - 128-bit input block vector
3823 * @param {number} x3 - 128-bit input block vector
3824 */
3825 function _cbc_dec(x0, x1, x2, x3) {
3826 x0 = x0 | 0;
3827 x1 = x1 | 0;
3828 x2 = x2 | 0;
3829 x3 = x3 | 0;
3830
3831 var t = 0;
3832
3833 _core(
3834 0x0400, 0x0c00, 0x2000,
3835 R,
3836 x0,
3837 x3,
3838 x2,
3839 x1
3840 );
3841
3842 t = S1, S1 = S3, S3 = t;
3843
3844 S0 = S0 ^ I0,
3845 S1 = S1 ^ I1,
3846 S2 = S2 ^ I2,
3847 S3 = S3 ^ I3;
3848
3849 I0 = x0,
3850 I1 = x1,
3851 I2 = x2,
3852 I3 = x3;
3853 }
3854
3855 /**
3856 * CFB mode encryption
3857 * @param {number} x0 - 128-bit input block vector
3858 * @param {number} x1 - 128-bit input block vector
3859 * @param {number} x2 - 128-bit input block vector
3860 * @param {number} x3 - 128-bit input block vector
3861 */
3862 function _cfb_enc(x0, x1, x2, x3) {
3863 x0 = x0 | 0;
3864 x1 = x1 | 0;
3865 x2 = x2 | 0;
3866 x3 = x3 | 0;
3867
3868 _core(
3869 0x0000, 0x0800, 0x1000,
3870 R,
3871 I0,
3872 I1,
3873 I2,
3874 I3
3875 );
3876
3877 I0 = S0 = S0 ^ x0,
3878 I1 = S1 = S1 ^ x1,
3879 I2 = S2 = S2 ^ x2,
3880 I3 = S3 = S3 ^ x3;
3881 }
3882
3883
3884 /**
3885 * CFB mode decryption
3886 * @param {number} x0 - 128-bit input block vector
3887 * @param {number} x1 - 128-bit input block vector
3888 * @param {number} x2 - 128-bit input block vector
3889 * @param {number} x3 - 128-bit input block vector
3890 */
3891 function _cfb_dec(x0, x1, x2, x3) {
3892 x0 = x0 | 0;
3893 x1 = x1 | 0;
3894 x2 = x2 | 0;
3895 x3 = x3 | 0;
3896
3897 _core(
3898 0x0000, 0x0800, 0x1000,
3899 R,
3900 I0,
3901 I1,
3902 I2,
3903 I3
3904 );
3905
3906 S0 = S0 ^ x0,
3907 S1 = S1 ^ x1,
3908 S2 = S2 ^ x2,
3909 S3 = S3 ^ x3;
3910
3911 I0 = x0,
3912 I1 = x1,
3913 I2 = x2,
3914 I3 = x3;
3915 }
3916
3917 /**
3918 * OFB mode encryption / decryption
3919 * @param {number} x0 - 128-bit input block vector
3920 * @param {number} x1 - 128-bit input block vector
3921 * @param {number} x2 - 128-bit input block vector
3922 * @param {number} x3 - 128-bit input block vector
3923 */
3924 function _ofb(x0, x1, x2, x3) {
3925 x0 = x0 | 0;
3926 x1 = x1 | 0;
3927 x2 = x2 | 0;
3928 x3 = x3 | 0;
3929
3930 _core(
3931 0x0000, 0x0800, 0x1000,
3932 R,
3933 I0,
3934 I1,
3935 I2,
3936 I3
3937 );
3938
3939 I0 = S0,
3940 I1 = S1,
3941 I2 = S2,
3942 I3 = S3;
3943
3944 S0 = S0 ^ x0,
3945 S1 = S1 ^ x1,
3946 S2 = S2 ^ x2,
3947 S3 = S3 ^ x3;
3948 }
3949
3950 /**
3951 * CTR mode encryption / decryption
3952 * @param {number} x0 - 128-bit input block vector
3953 * @param {number} x1 - 128-bit input block vector
3954 * @param {number} x2 - 128-bit input block vector
3955 * @param {number} x3 - 128-bit input block vector
3956 */
3957 function _ctr(x0, x1, x2, x3) {
3958 x0 = x0 | 0;
3959 x1 = x1 | 0;
3960 x2 = x2 | 0;
3961 x3 = x3 | 0;
3962
3963 _core(
3964 0x0000, 0x0800, 0x1000,
3965 R,
3966 N0,
3967 N1,
3968 N2,
3969 N3
3970 );
3971
3972 N3 = (~M3 & N3) | M3 & (N3 + 1);
3973 N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0));
3974 N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0));
3975 N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0));
3976
3977 S0 = S0 ^ x0;
3978 S1 = S1 ^ x1;
3979 S2 = S2 ^ x2;
3980 S3 = S3 ^ x3;
3981 }
3982
3983 /**
3984 * GCM mode MAC calculation
3985 * @param {number} x0 - 128-bit input block vector
3986 * @param {number} x1 - 128-bit input block vector
3987 * @param {number} x2 - 128-bit input block vector
3988 * @param {number} x3 - 128-bit input block vector
3989 */
3990 function _gcm_mac(x0, x1, x2, x3) {
3991 x0 = x0 | 0;
3992 x1 = x1 | 0;
3993 x2 = x2 | 0;
3994 x3 = x3 | 0;
3995
3996 var y0 = 0, y1 = 0, y2 = 0, y3 = 0,
3997 z0 = 0, z1 = 0, z2 = 0, z3 = 0,
3998 i = 0, c = 0;
3999
4000 x0 = x0 ^ I0,
4001 x1 = x1 ^ I1,
4002 x2 = x2 ^ I2,
4003 x3 = x3 ^ I3;
4004
4005 y0 = H0 | 0,
4006 y1 = H1 | 0,
4007 y2 = H2 | 0,
4008 y3 = H3 | 0;
4009
4010 for (; (i | 0) < 128; i = (i + 1) | 0) {
4011 if (y0 >>> 31) {
4012 z0 = z0 ^ x0,
4013 z1 = z1 ^ x1,
4014 z2 = z2 ^ x2,
4015 z3 = z3 ^ x3;
4016 }
4017
4018 y0 = (y0 << 1) | (y1 >>> 31),
4019 y1 = (y1 << 1) | (y2 >>> 31),
4020 y2 = (y2 << 1) | (y3 >>> 31),
4021 y3 = (y3 << 1);
4022
4023 c = x3 & 1;
4024
4025 x3 = (x3 >>> 1) | (x2 << 31),
4026 x2 = (x2 >>> 1) | (x1 << 31),
4027 x1 = (x1 >>> 1) | (x0 << 31),
4028 x0 = (x0 >>> 1);
4029
4030 if (c) x0 = x0 ^ 0xe1000000;
4031 }
4032
4033 I0 = z0,
4034 I1 = z1,
4035 I2 = z2,
4036 I3 = z3;
4037 }
4038
4039 /**
4040 * Set the internal rounds number.
4041 * @instance
4042 * @memberof AES_asm
4043 * @param {number} r - number if inner AES rounds
4044 */
4045 function set_rounds(r) {
4046 r = r | 0;
4047 R = r;
4048 }
4049
4050 /**
4051 * Populate the internal state of the module.
4052 * @instance
4053 * @memberof AES_asm
4054 * @param {number} s0 - state vector
4055 * @param {number} s1 - state vector
4056 * @param {number} s2 - state vector
4057 * @param {number} s3 - state vector
4058 */
4059 function set_state(s0, s1, s2, s3) {
4060 s0 = s0 | 0;
4061 s1 = s1 | 0;
4062 s2 = s2 | 0;
4063 s3 = s3 | 0;
4064
4065 S0 = s0,
4066 S1 = s1,
4067 S2 = s2,
4068 S3 = s3;
4069 }
4070
4071 /**
4072 * Populate the internal iv of the module.
4073 * @instance
4074 * @memberof AES_asm
4075 * @param {number} i0 - iv vector
4076 * @param {number} i1 - iv vector
4077 * @param {number} i2 - iv vector
4078 * @param {number} i3 - iv vector
4079 */
4080 function set_iv(i0, i1, i2, i3) {
4081 i0 = i0 | 0;
4082 i1 = i1 | 0;
4083 i2 = i2 | 0;
4084 i3 = i3 | 0;
4085
4086 I0 = i0,
4087 I1 = i1,
4088 I2 = i2,
4089 I3 = i3;
4090 }
4091
4092 /**
4093 * Set nonce for CTR-family modes.
4094 * @instance
4095 * @memberof AES_asm
4096 * @param {number} n0 - nonce vector
4097 * @param {number} n1 - nonce vector
4098 * @param {number} n2 - nonce vector
4099 * @param {number} n3 - nonce vector
4100 */
4101 function set_nonce(n0, n1, n2, n3) {
4102 n0 = n0 | 0;
4103 n1 = n1 | 0;
4104 n2 = n2 | 0;
4105 n3 = n3 | 0;
4106
4107 N0 = n0,
4108 N1 = n1,
4109 N2 = n2,
4110 N3 = n3;
4111 }
4112
4113 /**
4114 * Set counter mask for CTR-family modes.
4115 * @instance
4116 * @memberof AES_asm
4117 * @param {number} m0 - counter mask vector
4118 * @param {number} m1 - counter mask vector
4119 * @param {number} m2 - counter mask vector
4120 * @param {number} m3 - counter mask vector
4121 */
4122 function set_mask(m0, m1, m2, m3) {
4123 m0 = m0 | 0;
4124 m1 = m1 | 0;
4125 m2 = m2 | 0;
4126 m3 = m3 | 0;
4127
4128 M0 = m0,
4129 M1 = m1,
4130 M2 = m2,
4131 M3 = m3;
4132 }
4133
4134 /**
4135 * Set counter for CTR-family modes.
4136 * @instance
4137 * @memberof AES_asm
4138 * @param {number} c0 - counter vector
4139 * @param {number} c1 - counter vector
4140 * @param {number} c2 - counter vector
4141 * @param {number} c3 - counter vector
4142 */
4143 function set_counter(c0, c1, c2, c3) {
4144 c0 = c0 | 0;
4145 c1 = c1 | 0;
4146 c2 = c2 | 0;
4147 c3 = c3 | 0;
4148
4149 N3 = (~M3 & N3) | M3 & c3,
4150 N2 = (~M2 & N2) | M2 & c2,
4151 N1 = (~M1 & N1) | M1 & c1,
4152 N0 = (~M0 & N0) | M0 & c0;
4153 }
4154
4155 /**
4156 * Store the internal state vector into the heap.
4157 * @instance
4158 * @memberof AES_asm
4159 * @param {number} pos - offset where to put the data
4160 * @return {number} The number of bytes have been written into the heap, always 16.
4161 */
4162 function get_state(pos) {
4163 pos = pos | 0;
4164
4165 if (pos & 15) return -1;
4166
4167 DATA[pos | 0] = S0 >>> 24,
4168 DATA[pos | 1] = S0 >>> 16 & 255,
4169 DATA[pos | 2] = S0 >>> 8 & 255,
4170 DATA[pos | 3] = S0 & 255,
4171 DATA[pos | 4] = S1 >>> 24,
4172 DATA[pos | 5] = S1 >>> 16 & 255,
4173 DATA[pos | 6] = S1 >>> 8 & 255,
4174 DATA[pos | 7] = S1 & 255,
4175 DATA[pos | 8] = S2 >>> 24,
4176 DATA[pos | 9] = S2 >>> 16 & 255,
4177 DATA[pos | 10] = S2 >>> 8 & 255,
4178 DATA[pos | 11] = S2 & 255,
4179 DATA[pos | 12] = S3 >>> 24,
4180 DATA[pos | 13] = S3 >>> 16 & 255,
4181 DATA[pos | 14] = S3 >>> 8 & 255,
4182 DATA[pos | 15] = S3 & 255;
4183
4184 return 16;
4185 }
4186
4187 /**
4188 * Store the internal iv vector into the heap.
4189 * @instance
4190 * @memberof AES_asm
4191 * @param {number} pos - offset where to put the data
4192 * @return {number} The number of bytes have been written into the heap, always 16.
4193 */
4194 function get_iv(pos) {
4195 pos = pos | 0;
4196
4197 if (pos & 15) return -1;
4198
4199 DATA[pos | 0] = I0 >>> 24,
4200 DATA[pos | 1] = I0 >>> 16 & 255,
4201 DATA[pos | 2] = I0 >>> 8 & 255,
4202 DATA[pos | 3] = I0 & 255,
4203 DATA[pos | 4] = I1 >>> 24,
4204 DATA[pos | 5] = I1 >>> 16 & 255,
4205 DATA[pos | 6] = I1 >>> 8 & 255,
4206 DATA[pos | 7] = I1 & 255,
4207 DATA[pos | 8] = I2 >>> 24,
4208 DATA[pos | 9] = I2 >>> 16 & 255,
4209 DATA[pos | 10] = I2 >>> 8 & 255,
4210 DATA[pos | 11] = I2 & 255,
4211 DATA[pos | 12] = I3 >>> 24,
4212 DATA[pos | 13] = I3 >>> 16 & 255,
4213 DATA[pos | 14] = I3 >>> 8 & 255,
4214 DATA[pos | 15] = I3 & 255;
4215
4216 return 16;
4217 }
4218
4219 /**
4220 * GCM initialization.
4221 * @instance
4222 * @memberof AES_asm
4223 */
4224 function gcm_init() {
4225 _ecb_enc(0, 0, 0, 0);
4226 H0 = S0,
4227 H1 = S1,
4228 H2 = S2,
4229 H3 = S3;
4230 }
4231
4232 /**
4233 * Perform ciphering operation on the supplied data.
4234 * @instance
4235 * @memberof AES_asm
4236 * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)
4237 * @param {number} pos - offset of the data being processed
4238 * @param {number} len - length of the data being processed
4239 * @return {number} Actual amount of data have been processed.
4240 */
4241 function cipher(mode, pos, len) {
4242 mode = mode | 0;
4243 pos = pos | 0;
4244 len = len | 0;
4245
4246 var ret = 0;
4247
4248 if (pos & 15) return -1;
4249
4250 while ((len | 0) >= 16) {
4251 _cipher_modes[mode & 7](
4252 DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],
4253 DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],
4254 DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],
4255 DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]
4256 );
4257
4258 DATA[pos | 0] = S0 >>> 24,
4259 DATA[pos | 1] = S0 >>> 16 & 255,
4260 DATA[pos | 2] = S0 >>> 8 & 255,
4261 DATA[pos | 3] = S0 & 255,
4262 DATA[pos | 4] = S1 >>> 24,
4263 DATA[pos | 5] = S1 >>> 16 & 255,
4264 DATA[pos | 6] = S1 >>> 8 & 255,
4265 DATA[pos | 7] = S1 & 255,
4266 DATA[pos | 8] = S2 >>> 24,
4267 DATA[pos | 9] = S2 >>> 16 & 255,
4268 DATA[pos | 10] = S2 >>> 8 & 255,
4269 DATA[pos | 11] = S2 & 255,
4270 DATA[pos | 12] = S3 >>> 24,
4271 DATA[pos | 13] = S3 >>> 16 & 255,
4272 DATA[pos | 14] = S3 >>> 8 & 255,
4273 DATA[pos | 15] = S3 & 255;
4274
4275 ret = (ret + 16) | 0,
4276 pos = (pos + 16) | 0,
4277 len = (len - 16) | 0;
4278 }
4279
4280 return ret | 0;
4281 }
4282
4283 /**
4284 * Calculates MAC of the supplied data.
4285 * @instance
4286 * @memberof AES_asm
4287 * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)
4288 * @param {number} pos - offset of the data being processed
4289 * @param {number} len - length of the data being processed
4290 * @return {number} Actual amount of data have been processed.
4291 */
4292 function mac(mode, pos, len) {
4293 mode = mode | 0;
4294 pos = pos | 0;
4295 len = len | 0;
4296
4297 var ret = 0;
4298
4299 if (pos & 15) return -1;
4300
4301 while ((len | 0) >= 16) {
4302 _mac_modes[mode & 1](
4303 DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],
4304 DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],
4305 DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],
4306 DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]
4307 );
4308
4309 ret = (ret + 16) | 0,
4310 pos = (pos + 16) | 0,
4311 len = (len - 16) | 0;
4312 }
4313
4314 return ret | 0;
4315 }
4316
4317 /**
4318 * AES cipher modes table (virual methods)
4319 */
4320 var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr];
4321
4322 /**
4323 * AES MAC modes table (virual methods)
4324 */
4325 var _mac_modes = [_cbc_enc, _gcm_mac];
4326
4327 /**
4328 * Asm.js module exports
4329 */
4330 return {
4331 set_rounds: set_rounds,
4332 set_state: set_state,
4333 set_iv: set_iv,
4334 set_nonce: set_nonce,
4335 set_mask: set_mask,
4336 set_counter: set_counter,
4337 get_state: get_state,
4338 get_iv: get_iv,
4339 gcm_init: gcm_init,
4340 cipher: cipher,
4341 mac: mac,
4342 };
4343 }(stdlib, foreign, buffer);
4344
4345 asm.set_key = set_key;
4346
4347 return asm;
4348 };
4349
4350 /**
4351 * AES enciphering mode constants
4352 * @enum {number}
4353 * @const
4354 */
4355 wrapper.ENC = {
4356 ECB: 0,
4357 CBC: 2,
4358 CFB: 4,
4359 OFB: 6,
4360 CTR: 7,
4361 },
4362
4363 /**
4364 * AES deciphering mode constants
4365 * @enum {number}
4366 * @const
4367 */
4368 wrapper.DEC = {
4369 ECB: 1,
4370 CBC: 3,
4371 CFB: 5,
4372 OFB: 6,
4373 CTR: 7,
4374 },
4375
4376 /**
4377 * AES MAC mode constants
4378 * @enum {number}
4379 * @const
4380 */
4381 wrapper.MAC = {
4382 CBC: 0,
4383 GCM: 1,
4384 };
4385
4386 /**
4387 * Heap data offset
4388 * @type {number}
4389 * @const
4390 */
4391 wrapper.HEAP_DATA = 0x4000;
4392
4393 return wrapper;
4394}();
4395
4396function is_bytes(a) {
4397 return a instanceof Uint8Array;
4398}
4399function _heap_init(heap, heapSize) {
4400 const size = heap ? heap.byteLength : heapSize || 65536;
4401 if (size & 0xfff || size <= 0)
4402 throw new Error('heap size must be a positive integer and a multiple of 4096');
4403 heap = heap || new Uint8Array(new ArrayBuffer(size));
4404 return heap;
4405}
4406function _heap_write(heap, hpos, data, dpos, dlen) {
4407 const hlen = heap.length - hpos;
4408 const wlen = hlen < dlen ? hlen : dlen;
4409 heap.set(data.subarray(dpos, dpos + wlen), hpos);
4410 return wlen;
4411}
4412function joinBytes(...arg) {
4413 const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0);
4414 const ret = new Uint8Array(totalLenght);
4415 let cursor = 0;
4416 for (let i = 0; i < arg.length; i++) {
4417 ret.set(arg[i], cursor);
4418 cursor += arg[i].length;
4419 }
4420 return ret;
4421}
4422
4423class IllegalStateError extends Error {
4424 constructor(...args) {
4425 super(...args);
4426 }
4427}
4428class IllegalArgumentError extends Error {
4429 constructor(...args) {
4430 super(...args);
4431 }
4432}
4433class SecurityError extends Error {
4434 constructor(...args) {
4435 super(...args);
4436 }
4437}
4438
4439const heap_pool = [];
4440const asm_pool = [];
4441class AES {
4442 constructor(key, iv, padding = true, mode, heap, asm) {
4443 this.pos = 0;
4444 this.len = 0;
4445 this.mode = mode;
4446 // The AES object state
4447 this.pos = 0;
4448 this.len = 0;
4449 this.key = key;
4450 this.iv = iv;
4451 this.padding = padding;
4452 // The AES "worker"
4453 this.acquire_asm(heap, asm);
4454 }
4455 acquire_asm(heap, asm) {
4456 if (this.heap === undefined || this.asm === undefined) {
4457 this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA);
4458 this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer);
4459 this.reset(this.key, this.iv);
4460 }
4461 return { heap: this.heap, asm: this.asm };
4462 }
4463 release_asm() {
4464 if (this.heap !== undefined && this.asm !== undefined) {
4465 heap_pool.push(this.heap);
4466 asm_pool.push(this.asm);
4467 }
4468 this.heap = undefined;
4469 this.asm = undefined;
4470 }
4471 reset(key, iv) {
4472 const { asm } = this.acquire_asm();
4473 // Key
4474 const keylen = key.length;
4475 if (keylen !== 16 && keylen !== 24 && keylen !== 32)
4476 throw new IllegalArgumentError('illegal key size');
4477 const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength);
4478 asm.set_key(keylen >> 2, keyview.getUint32(0), keyview.getUint32(4), keyview.getUint32(8), keyview.getUint32(12), keylen > 16 ? keyview.getUint32(16) : 0, keylen > 16 ? keyview.getUint32(20) : 0, keylen > 24 ? keyview.getUint32(24) : 0, keylen > 24 ? keyview.getUint32(28) : 0);
4479 // IV
4480 if (iv !== undefined) {
4481 if (iv.length !== 16)
4482 throw new IllegalArgumentError('illegal iv size');
4483 let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);
4484 asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12));
4485 }
4486 else {
4487 asm.set_iv(0, 0, 0, 0);
4488 }
4489 }
4490 AES_Encrypt_process(data) {
4491 if (!is_bytes(data))
4492 throw new TypeError("data isn't of expected type");
4493 let { heap, asm } = this.acquire_asm();
4494 let amode = AES_asm.ENC[this.mode];
4495 let hpos = AES_asm.HEAP_DATA;
4496 let pos = this.pos;
4497 let len = this.len;
4498 let dpos = 0;
4499 let dlen = data.length || 0;
4500 let rpos = 0;
4501 let rlen = (len + dlen) & -16;
4502 let wlen = 0;
4503 let result = new Uint8Array(rlen);
4504 while (dlen > 0) {
4505 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
4506 len += wlen;
4507 dpos += wlen;
4508 dlen -= wlen;
4509 wlen = asm.cipher(amode, hpos + pos, len);
4510 if (wlen)
4511 result.set(heap.subarray(pos, pos + wlen), rpos);
4512 rpos += wlen;
4513 if (wlen < len) {
4514 pos += wlen;
4515 len -= wlen;
4516 }
4517 else {
4518 pos = 0;
4519 len = 0;
4520 }
4521 }
4522 this.pos = pos;
4523 this.len = len;
4524 return result;
4525 }
4526 AES_Encrypt_finish() {
4527 let { heap, asm } = this.acquire_asm();
4528 let amode = AES_asm.ENC[this.mode];
4529 let hpos = AES_asm.HEAP_DATA;
4530 let pos = this.pos;
4531 let len = this.len;
4532 let plen = 16 - (len % 16);
4533 let rlen = len;
4534 if (this.hasOwnProperty('padding')) {
4535 if (this.padding) {
4536 for (let p = 0; p < plen; ++p) {
4537 heap[pos + len + p] = plen;
4538 }
4539 len += plen;
4540 rlen = len;
4541 }
4542 else if (len % 16) {
4543 throw new IllegalArgumentError('data length must be a multiple of the block size');
4544 }
4545 }
4546 else {
4547 len += plen;
4548 }
4549 const result = new Uint8Array(rlen);
4550 if (len)
4551 asm.cipher(amode, hpos + pos, len);
4552 if (rlen)
4553 result.set(heap.subarray(pos, pos + rlen));
4554 this.pos = 0;
4555 this.len = 0;
4556 this.release_asm();
4557 return result;
4558 }
4559 AES_Decrypt_process(data) {
4560 if (!is_bytes(data))
4561 throw new TypeError("data isn't of expected type");
4562 let { heap, asm } = this.acquire_asm();
4563 let amode = AES_asm.DEC[this.mode];
4564 let hpos = AES_asm.HEAP_DATA;
4565 let pos = this.pos;
4566 let len = this.len;
4567 let dpos = 0;
4568 let dlen = data.length || 0;
4569 let rpos = 0;
4570 let rlen = (len + dlen) & -16;
4571 let plen = 0;
4572 let wlen = 0;
4573 if (this.padding) {
4574 plen = len + dlen - rlen || 16;
4575 rlen -= plen;
4576 }
4577 const result = new Uint8Array(rlen);
4578 while (dlen > 0) {
4579 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
4580 len += wlen;
4581 dpos += wlen;
4582 dlen -= wlen;
4583 wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0));
4584 if (wlen)
4585 result.set(heap.subarray(pos, pos + wlen), rpos);
4586 rpos += wlen;
4587 if (wlen < len) {
4588 pos += wlen;
4589 len -= wlen;
4590 }
4591 else {
4592 pos = 0;
4593 len = 0;
4594 }
4595 }
4596 this.pos = pos;
4597 this.len = len;
4598 return result;
4599 }
4600 AES_Decrypt_finish() {
4601 let { heap, asm } = this.acquire_asm();
4602 let amode = AES_asm.DEC[this.mode];
4603 let hpos = AES_asm.HEAP_DATA;
4604 let pos = this.pos;
4605 let len = this.len;
4606 let rlen = len;
4607 if (len > 0) {
4608 if (len % 16) {
4609 if (this.hasOwnProperty('padding')) {
4610 throw new IllegalArgumentError('data length must be a multiple of the block size');
4611 }
4612 else {
4613 len += 16 - (len % 16);
4614 }
4615 }
4616 asm.cipher(amode, hpos + pos, len);
4617 if (this.hasOwnProperty('padding') && this.padding) {
4618 let pad = heap[pos + rlen - 1];
4619 if (pad < 1 || pad > 16 || pad > rlen)
4620 throw new SecurityError('bad padding');
4621 let pcheck = 0;
4622 for (let i = pad; i > 1; i--)
4623 pcheck |= pad ^ heap[pos + rlen - i];
4624 if (pcheck)
4625 throw new SecurityError('bad padding');
4626 rlen -= pad;
4627 }
4628 }
4629 const result = new Uint8Array(rlen);
4630 if (rlen > 0) {
4631 result.set(heap.subarray(pos, pos + rlen));
4632 }
4633 this.pos = 0;
4634 this.len = 0;
4635 this.release_asm();
4636 return result;
4637 }
4638}
4639
4640class AES_ECB {
4641 static encrypt(data, key, padding = false) {
4642 return new AES_ECB(key, padding).encrypt(data);
4643 }
4644 static decrypt(data, key, padding = false) {
4645 return new AES_ECB(key, padding).decrypt(data);
4646 }
4647 constructor(key, padding = false, aes) {
4648 this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB');
4649 }
4650 encrypt(data) {
4651 const r1 = this.aes.AES_Encrypt_process(data);
4652 const r2 = this.aes.AES_Encrypt_finish();
4653 return joinBytes(r1, r2);
4654 }
4655 decrypt(data) {
4656 const r1 = this.aes.AES_Decrypt_process(data);
4657 const r2 = this.aes.AES_Decrypt_finish();
4658 return joinBytes(r1, r2);
4659 }
4660}
4661
4662/**
4663 * Javascript AES implementation.
4664 * This is used as fallback if the native Crypto APIs are not available.
4665 */
4666function aes(length) {
4667 const C = function(key) {
4668 const aesECB = new AES_ECB(key);
4669
4670 this.encrypt = function(block) {
4671 return aesECB.encrypt(block);
4672 };
4673
4674 this.decrypt = function(block) {
4675 return aesECB.decrypt(block);
4676 };
4677 };
4678
4679 C.blockSize = C.prototype.blockSize = 16;
4680 C.keySize = C.prototype.keySize = length / 8;
4681
4682 return C;
4683}
4684
4685//Paul Tero, July 2001
4686//http://www.tero.co.uk/des/
4687//
4688//Optimised for performance with large blocks by Michael Hayworth, November 2001
4689//http://www.netdealing.com
4690//
4691// Modified by Recurity Labs GmbH
4692
4693//THIS SOFTWARE IS PROVIDED "AS IS" AND
4694//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4695//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4696//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
4697//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4698//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4699//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4700//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4701//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
4702//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
4703//SUCH DAMAGE.
4704
4705//des
4706//this takes the key, the message, and whether to encrypt or decrypt
4707
4708function des(keys, message, encrypt, mode, iv, padding) {
4709 //declaring this locally speeds things up a bit
4710 const spfunction1 = [
4711 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,
4712 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,
4713 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,
4714 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,
4715 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,
4716 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004
4717 ];
4718 const spfunction2 = [
4719 -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0,
4720 -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020,
4721 -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000,
4722 -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000,
4723 -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0,
4724 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0,
4725 -0x7fef7fe0, 0x108000
4726 ];
4727 const spfunction3 = [
4728 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,
4729 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,
4730 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,
4731 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,
4732 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,
4733 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200
4734 ];
4735 const spfunction4 = [
4736 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,
4737 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,
4738 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,
4739 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,
4740 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080
4741 ];
4742 const spfunction5 = [
4743 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,
4744 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,
4745 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,
4746 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,
4747 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,
4748 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,
4749 0x40080000, 0x2080100, 0x40000100
4750 ];
4751 const spfunction6 = [
4752 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,
4753 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,
4754 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,
4755 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,
4756 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,
4757 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010
4758 ];
4759 const spfunction7 = [
4760 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,
4761 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,
4762 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,
4763 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,
4764 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,
4765 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002
4766 ];
4767 const spfunction8 = [
4768 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,
4769 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,
4770 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,
4771 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,
4772 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,
4773 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000
4774 ];
4775
4776 //create the 16 or 48 subkeys we will need
4777 let m = 0;
4778 let i;
4779 let j;
4780 let temp;
4781 let right1;
4782 let right2;
4783 let left;
4784 let right;
4785 let looping;
4786 let cbcleft;
4787 let cbcleft2;
4788 let cbcright;
4789 let cbcright2;
4790 let endloop;
4791 let loopinc;
4792 let len = message.length;
4793
4794 //set up the loops for single and triple des
4795 const iterations = keys.length === 32 ? 3 : 9; //single or triple des
4796 if (iterations === 3) {
4797 looping = encrypt ? [0, 32, 2] : [30, -2, -2];
4798 } else {
4799 looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];
4800 }
4801
4802 //pad the message depending on the padding parameter
4803 //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt
4804 if (encrypt) {
4805 message = desAddPadding(message, padding);
4806 len = message.length;
4807 }
4808
4809 //store the result here
4810 let result = new Uint8Array(len);
4811 let k = 0;
4812
4813 if (mode === 1) { //CBC mode
4814 cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];
4815 cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];
4816 m = 0;
4817 }
4818
4819 //loop through each 64 bit chunk of the message
4820 while (m < len) {
4821 left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];
4822 right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];
4823
4824 //for Cipher Block Chaining mode, xor the message with the previous result
4825 if (mode === 1) {
4826 if (encrypt) {
4827 left ^= cbcleft;
4828 right ^= cbcright;
4829 } else {
4830 cbcleft2 = cbcleft;
4831 cbcright2 = cbcright;
4832 cbcleft = left;
4833 cbcright = right;
4834 }
4835 }
4836
4837 //first each 64 but chunk of the message must be permuted according to IP
4838 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
4839 right ^= temp;
4840 left ^= (temp << 4);
4841 temp = ((left >>> 16) ^ right) & 0x0000ffff;
4842 right ^= temp;
4843 left ^= (temp << 16);
4844 temp = ((right >>> 2) ^ left) & 0x33333333;
4845 left ^= temp;
4846 right ^= (temp << 2);
4847 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
4848 left ^= temp;
4849 right ^= (temp << 8);
4850 temp = ((left >>> 1) ^ right) & 0x55555555;
4851 right ^= temp;
4852 left ^= (temp << 1);
4853
4854 left = ((left << 1) | (left >>> 31));
4855 right = ((right << 1) | (right >>> 31));
4856
4857 //do this either 1 or 3 times for each chunk of the message
4858 for (j = 0; j < iterations; j += 3) {
4859 endloop = looping[j + 1];
4860 loopinc = looping[j + 2];
4861 //now go through and perform the encryption or decryption
4862 for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency
4863 right1 = right ^ keys[i];
4864 right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];
4865 //the result is attained by passing these bytes through the S selection functions
4866 temp = left;
4867 left = right;
4868 right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>
4869 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &
4870 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);
4871 }
4872 temp = left;
4873 left = right;
4874 right = temp; //unreverse left and right
4875 } //for either 1 or 3 iterations
4876
4877 //move then each one bit to the right
4878 left = ((left >>> 1) | (left << 31));
4879 right = ((right >>> 1) | (right << 31));
4880
4881 //now perform IP-1, which is IP in the opposite direction
4882 temp = ((left >>> 1) ^ right) & 0x55555555;
4883 right ^= temp;
4884 left ^= (temp << 1);
4885 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
4886 left ^= temp;
4887 right ^= (temp << 8);
4888 temp = ((right >>> 2) ^ left) & 0x33333333;
4889 left ^= temp;
4890 right ^= (temp << 2);
4891 temp = ((left >>> 16) ^ right) & 0x0000ffff;
4892 right ^= temp;
4893 left ^= (temp << 16);
4894 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
4895 right ^= temp;
4896 left ^= (temp << 4);
4897
4898 //for Cipher Block Chaining mode, xor the message with the previous result
4899 if (mode === 1) {
4900 if (encrypt) {
4901 cbcleft = left;
4902 cbcright = right;
4903 } else {
4904 left ^= cbcleft2;
4905 right ^= cbcright2;
4906 }
4907 }
4908
4909 result[k++] = (left >>> 24);
4910 result[k++] = ((left >>> 16) & 0xff);
4911 result[k++] = ((left >>> 8) & 0xff);
4912 result[k++] = (left & 0xff);
4913 result[k++] = (right >>> 24);
4914 result[k++] = ((right >>> 16) & 0xff);
4915 result[k++] = ((right >>> 8) & 0xff);
4916 result[k++] = (right & 0xff);
4917 } //for every 8 characters, or 64 bits in the message
4918
4919 //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt
4920 if (!encrypt) {
4921 result = desRemovePadding(result, padding);
4922 }
4923
4924 return result;
4925} //end of des
4926
4927
4928//desCreateKeys
4929//this takes as input a 64 bit key (even though only 56 bits are used)
4930//as an array of 2 integers, and returns 16 48 bit keys
4931
4932function desCreateKeys(key) {
4933 //declaring this locally speeds things up a bit
4934 const pc2bytes0 = [
4935 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,
4936 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204
4937 ];
4938 const pc2bytes1 = [
4939 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,
4940 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101
4941 ];
4942 const pc2bytes2 = [
4943 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,
4944 0x1000000, 0x1000008, 0x1000800, 0x1000808
4945 ];
4946 const pc2bytes3 = [
4947 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,
4948 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000
4949 ];
4950 const pc2bytes4 = [
4951 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,
4952 0x41000, 0x1010, 0x41010
4953 ];
4954 const pc2bytes5 = [
4955 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,
4956 0x2000000, 0x2000400, 0x2000020, 0x2000420
4957 ];
4958 const pc2bytes6 = [
4959 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,
4960 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002
4961 ];
4962 const pc2bytes7 = [
4963 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,
4964 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800
4965 ];
4966 const pc2bytes8 = [
4967 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,
4968 0x2000002, 0x2040002, 0x2000002, 0x2040002
4969 ];
4970 const pc2bytes9 = [
4971 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,
4972 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408
4973 ];
4974 const pc2bytes10 = [
4975 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,
4976 0x102000, 0x102020, 0x102000, 0x102020
4977 ];
4978 const pc2bytes11 = [
4979 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,
4980 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200
4981 ];
4982 const pc2bytes12 = [
4983 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,
4984 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010
4985 ];
4986 const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];
4987
4988 //how many iterations (1 for des, 3 for triple des)
4989 const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys
4990 //stores the return keys
4991 const keys = new Array(32 * iterations);
4992 //now define the left shifts which need to be done
4993 const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];
4994 //other variables
4995 let lefttemp;
4996 let righttemp;
4997 let m = 0;
4998 let n = 0;
4999 let temp;
5000
5001 for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations
5002 let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];
5003 let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];
5004
5005 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
5006 right ^= temp;
5007 left ^= (temp << 4);
5008 temp = ((right >>> -16) ^ left) & 0x0000ffff;
5009 left ^= temp;
5010 right ^= (temp << -16);
5011 temp = ((left >>> 2) ^ right) & 0x33333333;
5012 right ^= temp;
5013 left ^= (temp << 2);
5014 temp = ((right >>> -16) ^ left) & 0x0000ffff;
5015 left ^= temp;
5016 right ^= (temp << -16);
5017 temp = ((left >>> 1) ^ right) & 0x55555555;
5018 right ^= temp;
5019 left ^= (temp << 1);
5020 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
5021 left ^= temp;
5022 right ^= (temp << 8);
5023 temp = ((left >>> 1) ^ right) & 0x55555555;
5024 right ^= temp;
5025 left ^= (temp << 1);
5026
5027 //the right side needs to be shifted and to get the last four bits of the left side
5028 temp = (left << 8) | ((right >>> 20) & 0x000000f0);
5029 //left needs to be put upside down
5030 left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);
5031 right = temp;
5032
5033 //now go through and perform these shifts on the left and right keys
5034 for (let i = 0; i < shifts.length; i++) {
5035 //shift the keys either one or two bits to the left
5036 if (shifts[i]) {
5037 left = (left << 2) | (left >>> 26);
5038 right = (right << 2) | (right >>> 26);
5039 } else {
5040 left = (left << 1) | (left >>> 27);
5041 right = (right << 1) | (right >>> 27);
5042 }
5043 left &= -0xf;
5044 right &= -0xf;
5045
5046 //now apply PC-2, in such a way that E is easier when encrypting or decrypting
5047 //this conversion will look like PC-2 except only the last 6 bits of each byte are used
5048 //rather than 48 consecutive bits and the order of lines will be according to
5049 //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7
5050 lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(
5051 left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &
5052 0xf];
5053 righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |
5054 pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |
5055 pc2bytes13[(right >>> 4) & 0xf];
5056 temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;
5057 keys[n++] = lefttemp ^ temp;
5058 keys[n++] = righttemp ^ (temp << 16);
5059 }
5060 } //for each iterations
5061 //return the keys we've created
5062 return keys;
5063} //end of desCreateKeys
5064
5065
5066function desAddPadding(message, padding) {
5067 const padLength = 8 - (message.length % 8);
5068
5069 let pad;
5070 if (padding === 2 && (padLength < 8)) { //pad the message with spaces
5071 pad = ' '.charCodeAt(0);
5072 } else if (padding === 1) { //PKCS7 padding
5073 pad = padLength;
5074 } else if (!padding && (padLength < 8)) { //pad the message out with null bytes
5075 pad = 0;
5076 } else if (padLength === 8) {
5077 return message;
5078 } else {
5079 throw new Error('des: invalid padding');
5080 }
5081
5082 const paddedMessage = new Uint8Array(message.length + padLength);
5083 for (let i = 0; i < message.length; i++) {
5084 paddedMessage[i] = message[i];
5085 }
5086 for (let j = 0; j < padLength; j++) {
5087 paddedMessage[message.length + j] = pad;
5088 }
5089
5090 return paddedMessage;
5091}
5092
5093function desRemovePadding(message, padding) {
5094 let padLength = null;
5095 let pad;
5096 if (padding === 2) { // space padded
5097 pad = ' '.charCodeAt(0);
5098 } else if (padding === 1) { // PKCS7
5099 padLength = message[message.length - 1];
5100 } else if (!padding) { // null padding
5101 pad = 0;
5102 } else {
5103 throw new Error('des: invalid padding');
5104 }
5105
5106 if (!padLength) {
5107 padLength = 1;
5108 while (message[message.length - padLength] === pad) {
5109 padLength++;
5110 }
5111 padLength--;
5112 }
5113
5114 return message.subarray(0, message.length - padLength);
5115}
5116
5117// added by Recurity Labs
5118
5119function TripleDES(key) {
5120 this.key = [];
5121
5122 for (let i = 0; i < 3; i++) {
5123 this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));
5124 }
5125
5126 this.encrypt = function(block) {
5127 return des(
5128 desCreateKeys(this.key[2]),
5129 des(
5130 desCreateKeys(this.key[1]),
5131 des(
5132 desCreateKeys(this.key[0]),
5133 block, true, 0, null, null
5134 ),
5135 false, 0, null, null
5136 ), true, 0, null, null
5137 );
5138 };
5139}
5140
5141TripleDES.keySize = TripleDES.prototype.keySize = 24;
5142TripleDES.blockSize = TripleDES.prototype.blockSize = 8;
5143
5144// This is "original" DES
5145
5146function DES(key) {
5147 this.key = key;
5148
5149 this.encrypt = function(block, padding) {
5150 const keys = desCreateKeys(this.key);
5151 return des(keys, block, true, 0, null, padding);
5152 };
5153
5154 this.decrypt = function(block, padding) {
5155 const keys = desCreateKeys(this.key);
5156 return des(keys, block, false, 0, null, padding);
5157 };
5158}
5159
5160// Use of this source code is governed by a BSD-style
5161// license that can be found in the LICENSE file.
5162
5163// Copyright 2010 pjacobs@xeekr.com . All rights reserved.
5164
5165// Modified by Recurity Labs GmbH
5166
5167// fixed/modified by Herbert Hanewinkel, www.haneWIN.de
5168// check www.haneWIN.de for the latest version
5169
5170// cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.
5171// CAST-128 is a common OpenPGP cipher.
5172
5173
5174// CAST5 constructor
5175
5176function OpenPGPSymEncCAST5() {
5177 this.BlockSize = 8;
5178 this.KeySize = 16;
5179
5180 this.setKey = function(key) {
5181 this.masking = new Array(16);
5182 this.rotate = new Array(16);
5183
5184 this.reset();
5185
5186 if (key.length === this.KeySize) {
5187 this.keySchedule(key);
5188 } else {
5189 throw new Error('CAST-128: keys must be 16 bytes');
5190 }
5191 return true;
5192 };
5193
5194 this.reset = function() {
5195 for (let i = 0; i < 16; i++) {
5196 this.masking[i] = 0;
5197 this.rotate[i] = 0;
5198 }
5199 };
5200
5201 this.getBlockSize = function() {
5202 return this.BlockSize;
5203 };
5204
5205 this.encrypt = function(src) {
5206 const dst = new Array(src.length);
5207
5208 for (let i = 0; i < src.length; i += 8) {
5209 let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];
5210 let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];
5211 let t;
5212
5213 t = r;
5214 r = l ^ f1(r, this.masking[0], this.rotate[0]);
5215 l = t;
5216 t = r;
5217 r = l ^ f2(r, this.masking[1], this.rotate[1]);
5218 l = t;
5219 t = r;
5220 r = l ^ f3(r, this.masking[2], this.rotate[2]);
5221 l = t;
5222 t = r;
5223 r = l ^ f1(r, this.masking[3], this.rotate[3]);
5224 l = t;
5225
5226 t = r;
5227 r = l ^ f2(r, this.masking[4], this.rotate[4]);
5228 l = t;
5229 t = r;
5230 r = l ^ f3(r, this.masking[5], this.rotate[5]);
5231 l = t;
5232 t = r;
5233 r = l ^ f1(r, this.masking[6], this.rotate[6]);
5234 l = t;
5235 t = r;
5236 r = l ^ f2(r, this.masking[7], this.rotate[7]);
5237 l = t;
5238
5239 t = r;
5240 r = l ^ f3(r, this.masking[8], this.rotate[8]);
5241 l = t;
5242 t = r;
5243 r = l ^ f1(r, this.masking[9], this.rotate[9]);
5244 l = t;
5245 t = r;
5246 r = l ^ f2(r, this.masking[10], this.rotate[10]);
5247 l = t;
5248 t = r;
5249 r = l ^ f3(r, this.masking[11], this.rotate[11]);
5250 l = t;
5251
5252 t = r;
5253 r = l ^ f1(r, this.masking[12], this.rotate[12]);
5254 l = t;
5255 t = r;
5256 r = l ^ f2(r, this.masking[13], this.rotate[13]);
5257 l = t;
5258 t = r;
5259 r = l ^ f3(r, this.masking[14], this.rotate[14]);
5260 l = t;
5261 t = r;
5262 r = l ^ f1(r, this.masking[15], this.rotate[15]);
5263 l = t;
5264
5265 dst[i] = (r >>> 24) & 255;
5266 dst[i + 1] = (r >>> 16) & 255;
5267 dst[i + 2] = (r >>> 8) & 255;
5268 dst[i + 3] = r & 255;
5269 dst[i + 4] = (l >>> 24) & 255;
5270 dst[i + 5] = (l >>> 16) & 255;
5271 dst[i + 6] = (l >>> 8) & 255;
5272 dst[i + 7] = l & 255;
5273 }
5274
5275 return dst;
5276 };
5277
5278 this.decrypt = function(src) {
5279 const dst = new Array(src.length);
5280
5281 for (let i = 0; i < src.length; i += 8) {
5282 let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];
5283 let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];
5284 let t;
5285
5286 t = r;
5287 r = l ^ f1(r, this.masking[15], this.rotate[15]);
5288 l = t;
5289 t = r;
5290 r = l ^ f3(r, this.masking[14], this.rotate[14]);
5291 l = t;
5292 t = r;
5293 r = l ^ f2(r, this.masking[13], this.rotate[13]);
5294 l = t;
5295 t = r;
5296 r = l ^ f1(r, this.masking[12], this.rotate[12]);
5297 l = t;
5298
5299 t = r;
5300 r = l ^ f3(r, this.masking[11], this.rotate[11]);
5301 l = t;
5302 t = r;
5303 r = l ^ f2(r, this.masking[10], this.rotate[10]);
5304 l = t;
5305 t = r;
5306 r = l ^ f1(r, this.masking[9], this.rotate[9]);
5307 l = t;
5308 t = r;
5309 r = l ^ f3(r, this.masking[8], this.rotate[8]);
5310 l = t;
5311
5312 t = r;
5313 r = l ^ f2(r, this.masking[7], this.rotate[7]);
5314 l = t;
5315 t = r;
5316 r = l ^ f1(r, this.masking[6], this.rotate[6]);
5317 l = t;
5318 t = r;
5319 r = l ^ f3(r, this.masking[5], this.rotate[5]);
5320 l = t;
5321 t = r;
5322 r = l ^ f2(r, this.masking[4], this.rotate[4]);
5323 l = t;
5324
5325 t = r;
5326 r = l ^ f1(r, this.masking[3], this.rotate[3]);
5327 l = t;
5328 t = r;
5329 r = l ^ f3(r, this.masking[2], this.rotate[2]);
5330 l = t;
5331 t = r;
5332 r = l ^ f2(r, this.masking[1], this.rotate[1]);
5333 l = t;
5334 t = r;
5335 r = l ^ f1(r, this.masking[0], this.rotate[0]);
5336 l = t;
5337
5338 dst[i] = (r >>> 24) & 255;
5339 dst[i + 1] = (r >>> 16) & 255;
5340 dst[i + 2] = (r >>> 8) & 255;
5341 dst[i + 3] = r & 255;
5342 dst[i + 4] = (l >>> 24) & 255;
5343 dst[i + 5] = (l >> 16) & 255;
5344 dst[i + 6] = (l >> 8) & 255;
5345 dst[i + 7] = l & 255;
5346 }
5347
5348 return dst;
5349 };
5350 const scheduleA = new Array(4);
5351
5352 scheduleA[0] = new Array(4);
5353 scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];
5354 scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
5355 scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
5356 scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
5357
5358 scheduleA[1] = new Array(4);
5359 scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
5360 scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
5361 scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
5362 scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
5363
5364 scheduleA[2] = new Array(4);
5365 scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];
5366 scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
5367 scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
5368 scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
5369
5370
5371 scheduleA[3] = new Array(4);
5372 scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
5373 scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
5374 scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
5375 scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
5376
5377 const scheduleB = new Array(4);
5378
5379 scheduleB[0] = new Array(4);
5380 scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];
5381 scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];
5382 scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];
5383 scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];
5384
5385 scheduleB[1] = new Array(4);
5386 scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];
5387 scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];
5388 scheduleB[1][2] = [7, 6, 8, 9, 3];
5389 scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];
5390
5391
5392 scheduleB[2] = new Array(4);
5393 scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];
5394 scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];
5395 scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];
5396 scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];
5397
5398
5399 scheduleB[3] = new Array(4);
5400 scheduleB[3][0] = [8, 9, 7, 6, 3];
5401 scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];
5402 scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];
5403 scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];
5404
5405 // changed 'in' to 'inn' (in javascript 'in' is a reserved word)
5406 this.keySchedule = function(inn) {
5407 const t = new Array(8);
5408 const k = new Array(32);
5409
5410 let j;
5411
5412 for (let i = 0; i < 4; i++) {
5413 j = i * 4;
5414 t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];
5415 }
5416
5417 const x = [6, 7, 4, 5];
5418 let ki = 0;
5419 let w;
5420
5421 for (let half = 0; half < 2; half++) {
5422 for (let round = 0; round < 4; round++) {
5423 for (j = 0; j < 4; j++) {
5424 const a = scheduleA[round][j];
5425 w = t[a[1]];
5426
5427 w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];
5428 w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];
5429 w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];
5430 w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];
5431 w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];
5432 t[a[0]] = w;
5433 }
5434
5435 for (j = 0; j < 4; j++) {
5436 const b = scheduleB[round][j];
5437 w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];
5438
5439 w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];
5440 w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];
5441 w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];
5442 w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];
5443 k[ki] = w;
5444 ki++;
5445 }
5446 }
5447 }
5448
5449 for (let i = 0; i < 16; i++) {
5450 this.masking[i] = k[i];
5451 this.rotate[i] = k[16 + i] & 0x1f;
5452 }
5453 };
5454
5455 // These are the three 'f' functions. See RFC 2144, section 2.2.
5456
5457 function f1(d, m, r) {
5458 const t = m + d;
5459 const I = (t << r) | (t >>> (32 - r));
5460 return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];
5461 }
5462
5463 function f2(d, m, r) {
5464 const t = m ^ d;
5465 const I = (t << r) | (t >>> (32 - r));
5466 return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];
5467 }
5468
5469 function f3(d, m, r) {
5470 const t = m - d;
5471 const I = (t << r) | (t >>> (32 - r));
5472 return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];
5473 }
5474
5475 const sBox = new Array(8);
5476 sBox[0] = [
5477 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,
5478 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,
5479 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,
5480 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,
5481 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,
5482 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,
5483 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,
5484 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,
5485 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,
5486 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,
5487 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,
5488 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,
5489 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,
5490 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,
5491 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,
5492 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,
5493 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,
5494 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,
5495 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,
5496 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,
5497 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,
5498 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,
5499 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,
5500 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,
5501 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,
5502 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,
5503 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,
5504 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,
5505 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,
5506 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,
5507 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,
5508 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf
5509 ];
5510
5511 sBox[1] = [
5512 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,
5513 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,
5514 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,
5515 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,
5516 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,
5517 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,
5518 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,
5519 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,
5520 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,
5521 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,
5522 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,
5523 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,
5524 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,
5525 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,
5526 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,
5527 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,
5528 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,
5529 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,
5530 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,
5531 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,
5532 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,
5533 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,
5534 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,
5535 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,
5536 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,
5537 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,
5538 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,
5539 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,
5540 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,
5541 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,
5542 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,
5543 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1
5544 ];
5545
5546 sBox[2] = [
5547 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,
5548 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,
5549 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,
5550 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,
5551 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,
5552 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,
5553 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,
5554 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,
5555 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,
5556 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,
5557 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,
5558 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,
5559 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,
5560 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,
5561 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,
5562 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,
5563 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,
5564 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,
5565 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,
5566 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,
5567 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,
5568 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,
5569 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,
5570 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,
5571 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,
5572 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,
5573 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,
5574 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,
5575 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,
5576 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,
5577 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,
5578 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783
5579 ];
5580
5581 sBox[3] = [
5582 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,
5583 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,
5584 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,
5585 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,
5586 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,
5587 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,
5588 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,
5589 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,
5590 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,
5591 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,
5592 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,
5593 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,
5594 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,
5595 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,
5596 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,
5597 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,
5598 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,
5599 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,
5600 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,
5601 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,
5602 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,
5603 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,
5604 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,
5605 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,
5606 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,
5607 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,
5608 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,
5609 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,
5610 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,
5611 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,
5612 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,
5613 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2
5614 ];
5615
5616 sBox[4] = [
5617 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,
5618 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,
5619 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,
5620 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,
5621 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,
5622 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,
5623 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,
5624 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,
5625 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,
5626 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,
5627 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,
5628 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,
5629 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,
5630 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,
5631 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,
5632 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,
5633 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,
5634 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,
5635 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,
5636 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,
5637 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,
5638 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,
5639 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,
5640 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,
5641 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,
5642 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,
5643 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,
5644 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,
5645 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,
5646 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,
5647 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,
5648 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4
5649 ];
5650
5651 sBox[5] = [
5652 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,
5653 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,
5654 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,
5655 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,
5656 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,
5657 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,
5658 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,
5659 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,
5660 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,
5661 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,
5662 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,
5663 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,
5664 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,
5665 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,
5666 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,
5667 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,
5668 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,
5669 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,
5670 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,
5671 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,
5672 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,
5673 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,
5674 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,
5675 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,
5676 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,
5677 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,
5678 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,
5679 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,
5680 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,
5681 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,
5682 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,
5683 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f
5684 ];
5685
5686 sBox[6] = [
5687 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,
5688 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,
5689 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,
5690 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,
5691 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,
5692 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,
5693 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,
5694 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,
5695 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,
5696 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,
5697 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,
5698 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,
5699 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,
5700 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,
5701 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,
5702 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,
5703 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,
5704 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,
5705 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,
5706 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,
5707 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,
5708 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,
5709 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,
5710 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,
5711 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,
5712 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,
5713 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,
5714 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,
5715 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,
5716 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,
5717 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,
5718 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3
5719 ];
5720
5721 sBox[7] = [
5722 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,
5723 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,
5724 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,
5725 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,
5726 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,
5727 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,
5728 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,
5729 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,
5730 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,
5731 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,
5732 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,
5733 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,
5734 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,
5735 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,
5736 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,
5737 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,
5738 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,
5739 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,
5740 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,
5741 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,
5742 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,
5743 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,
5744 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,
5745 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,
5746 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,
5747 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,
5748 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,
5749 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,
5750 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,
5751 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,
5752 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,
5753 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e
5754 ];
5755}
5756
5757function CAST5(key) {
5758 this.cast5 = new OpenPGPSymEncCAST5();
5759 this.cast5.setKey(key);
5760
5761 this.encrypt = function(block) {
5762 return this.cast5.encrypt(block);
5763 };
5764}
5765
5766CAST5.blockSize = CAST5.prototype.blockSize = 8;
5767CAST5.keySize = CAST5.prototype.keySize = 16;
5768
5769/* eslint-disable no-mixed-operators, no-fallthrough */
5770
5771
5772/* Modified by Recurity Labs GmbH
5773 *
5774 * Cipher.js
5775 * A block-cipher algorithm implementation on JavaScript
5776 * See Cipher.readme.txt for further information.
5777 *
5778 * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]
5779 * This script file is distributed under the LGPL
5780 *
5781 * ACKNOWLEDGMENT
5782 *
5783 * The main subroutines are written by Michiel van Everdingen.
5784 *
5785 * Michiel van Everdingen
5786 * http://home.versatel.nl/MAvanEverdingen/index.html
5787 *
5788 * All rights for these routines are reserved to Michiel van Everdingen.
5789 *
5790 */
5791
5792////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5793//Math
5794////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5795
5796const MAXINT = 0xFFFFFFFF;
5797
5798function rotw(w, n) {
5799 return (w << n | w >>> (32 - n)) & MAXINT;
5800}
5801
5802function getW(a, i) {
5803 return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;
5804}
5805
5806function setW(a, i, w) {
5807 a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);
5808}
5809
5810function getB(x, n) {
5811 return (x >>> (n * 8)) & 0xFF;
5812}
5813
5814// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5815// Twofish
5816// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5817
5818function createTwofish() {
5819 //
5820 let keyBytes = null;
5821 let dataBytes = null;
5822 let dataOffset = -1;
5823 // var dataLength = -1;
5824 // var idx2 = -1;
5825 //
5826
5827 let tfsKey = [];
5828 let tfsM = [
5829 [],
5830 [],
5831 [],
5832 []
5833 ];
5834
5835 function tfsInit(key) {
5836 keyBytes = key;
5837 let i;
5838 let a;
5839 let b;
5840 let c;
5841 let d;
5842 const meKey = [];
5843 const moKey = [];
5844 const inKey = [];
5845 let kLen;
5846 const sKey = [];
5847 let f01;
5848 let f5b;
5849 let fef;
5850
5851 const q0 = [
5852 [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],
5853 [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]
5854 ];
5855 const q1 = [
5856 [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],
5857 [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]
5858 ];
5859 const q2 = [
5860 [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],
5861 [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]
5862 ];
5863 const q3 = [
5864 [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],
5865 [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]
5866 ];
5867 const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];
5868 const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];
5869 const q = [
5870 [],
5871 []
5872 ];
5873 const m = [
5874 [],
5875 [],
5876 [],
5877 []
5878 ];
5879
5880 function ffm5b(x) {
5881 return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];
5882 }
5883
5884 function ffmEf(x) {
5885 return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];
5886 }
5887
5888 function mdsRem(p, q) {
5889 let i;
5890 let t;
5891 let u;
5892 for (i = 0; i < 8; i++) {
5893 t = q >>> 24;
5894 q = ((q << 8) & MAXINT) | p >>> 24;
5895 p = (p << 8) & MAXINT;
5896 u = t << 1;
5897 if (t & 128) {
5898 u ^= 333;
5899 }
5900 q ^= t ^ (u << 16);
5901 u ^= t >>> 1;
5902 if (t & 1) {
5903 u ^= 166;
5904 }
5905 q ^= u << 24 | u << 8;
5906 }
5907 return q;
5908 }
5909
5910 function qp(n, x) {
5911 const a = x >> 4;
5912 const b = x & 15;
5913 const c = q0[n][a ^ b];
5914 const d = q1[n][ror4[b] ^ ashx[a]];
5915 return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];
5916 }
5917
5918 function hFun(x, key) {
5919 let a = getB(x, 0);
5920 let b = getB(x, 1);
5921 let c = getB(x, 2);
5922 let d = getB(x, 3);
5923 switch (kLen) {
5924 case 4:
5925 a = q[1][a] ^ getB(key[3], 0);
5926 b = q[0][b] ^ getB(key[3], 1);
5927 c = q[0][c] ^ getB(key[3], 2);
5928 d = q[1][d] ^ getB(key[3], 3);
5929 case 3:
5930 a = q[1][a] ^ getB(key[2], 0);
5931 b = q[1][b] ^ getB(key[2], 1);
5932 c = q[0][c] ^ getB(key[2], 2);
5933 d = q[0][d] ^ getB(key[2], 3);
5934 case 2:
5935 a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);
5936 b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);
5937 c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);
5938 d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);
5939 }
5940 return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];
5941 }
5942
5943 keyBytes = keyBytes.slice(0, 32);
5944 i = keyBytes.length;
5945 while (i !== 16 && i !== 24 && i !== 32) {
5946 keyBytes[i++] = 0;
5947 }
5948
5949 for (i = 0; i < keyBytes.length; i += 4) {
5950 inKey[i >> 2] = getW(keyBytes, i);
5951 }
5952 for (i = 0; i < 256; i++) {
5953 q[0][i] = qp(0, i);
5954 q[1][i] = qp(1, i);
5955 }
5956 for (i = 0; i < 256; i++) {
5957 f01 = q[1][i];
5958 f5b = ffm5b(f01);
5959 fef = ffmEf(f01);
5960 m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);
5961 m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);
5962 f01 = q[0][i];
5963 f5b = ffm5b(f01);
5964 fef = ffmEf(f01);
5965 m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);
5966 m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);
5967 }
5968
5969 kLen = inKey.length / 2;
5970 for (i = 0; i < kLen; i++) {
5971 a = inKey[i + i];
5972 meKey[i] = a;
5973 b = inKey[i + i + 1];
5974 moKey[i] = b;
5975 sKey[kLen - i - 1] = mdsRem(a, b);
5976 }
5977 for (i = 0; i < 40; i += 2) {
5978 a = 0x1010101 * i;
5979 b = a + 0x1010101;
5980 a = hFun(a, meKey);
5981 b = rotw(hFun(b, moKey), 8);
5982 tfsKey[i] = (a + b) & MAXINT;
5983 tfsKey[i + 1] = rotw(a + 2 * b, 9);
5984 }
5985 for (i = 0; i < 256; i++) {
5986 a = b = c = d = i;
5987 switch (kLen) {
5988 case 4:
5989 a = q[1][a] ^ getB(sKey[3], 0);
5990 b = q[0][b] ^ getB(sKey[3], 1);
5991 c = q[0][c] ^ getB(sKey[3], 2);
5992 d = q[1][d] ^ getB(sKey[3], 3);
5993 case 3:
5994 a = q[1][a] ^ getB(sKey[2], 0);
5995 b = q[1][b] ^ getB(sKey[2], 1);
5996 c = q[0][c] ^ getB(sKey[2], 2);
5997 d = q[0][d] ^ getB(sKey[2], 3);
5998 case 2:
5999 tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];
6000 tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];
6001 tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];
6002 tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];
6003 }
6004 }
6005 }
6006
6007 function tfsG0(x) {
6008 return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];
6009 }
6010
6011 function tfsG1(x) {
6012 return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];
6013 }
6014
6015 function tfsFrnd(r, blk) {
6016 let a = tfsG0(blk[0]);
6017 let b = tfsG1(blk[1]);
6018 blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);
6019 blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;
6020 a = tfsG0(blk[2]);
6021 b = tfsG1(blk[3]);
6022 blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);
6023 blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;
6024 }
6025
6026 function tfsIrnd(i, blk) {
6027 let a = tfsG0(blk[0]);
6028 let b = tfsG1(blk[1]);
6029 blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;
6030 blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);
6031 a = tfsG0(blk[2]);
6032 b = tfsG1(blk[3]);
6033 blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;
6034 blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);
6035 }
6036
6037 function tfsClose() {
6038 tfsKey = [];
6039 tfsM = [
6040 [],
6041 [],
6042 [],
6043 []
6044 ];
6045 }
6046
6047 function tfsEncrypt(data, offset) {
6048 dataBytes = data;
6049 dataOffset = offset;
6050 const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],
6051 getW(dataBytes, dataOffset + 4) ^ tfsKey[1],
6052 getW(dataBytes, dataOffset + 8) ^ tfsKey[2],
6053 getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];
6054 for (let j = 0; j < 8; j++) {
6055 tfsFrnd(j, blk);
6056 }
6057 setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);
6058 setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);
6059 setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);
6060 setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);
6061 dataOffset += 16;
6062 return dataBytes;
6063 }
6064
6065 function tfsDecrypt(data, offset) {
6066 dataBytes = data;
6067 dataOffset = offset;
6068 const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],
6069 getW(dataBytes, dataOffset + 4) ^ tfsKey[5],
6070 getW(dataBytes, dataOffset + 8) ^ tfsKey[6],
6071 getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];
6072 for (let j = 7; j >= 0; j--) {
6073 tfsIrnd(j, blk);
6074 }
6075 setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);
6076 setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);
6077 setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);
6078 setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);
6079 dataOffset += 16;
6080 }
6081
6082 // added by Recurity Labs
6083
6084 function tfsFinal() {
6085 return dataBytes;
6086 }
6087
6088 return {
6089 name: 'twofish',
6090 blocksize: 128 / 8,
6091 open: tfsInit,
6092 close: tfsClose,
6093 encrypt: tfsEncrypt,
6094 decrypt: tfsDecrypt,
6095 // added by Recurity Labs
6096 finalize: tfsFinal
6097 };
6098}
6099
6100// added by Recurity Labs
6101
6102function TF(key) {
6103 this.tf = createTwofish();
6104 this.tf.open(Array.from(key), 0);
6105
6106 this.encrypt = function(block) {
6107 return this.tf.encrypt(Array.from(block), 0);
6108 };
6109}
6110
6111TF.keySize = TF.prototype.keySize = 32;
6112TF.blockSize = TF.prototype.blockSize = 16;
6113
6114/* Modified by Recurity Labs GmbH
6115 *
6116 * Originally written by nklein software (nklein.com)
6117 */
6118
6119/*
6120 * Javascript implementation based on Bruce Schneier's reference implementation.
6121 *
6122 *
6123 * The constructor doesn't do much of anything. It's just here
6124 * so we can start defining properties and methods and such.
6125 */
6126function Blowfish() {}
6127
6128/*
6129 * Declare the block size so that protocols know what size
6130 * Initialization Vector (IV) they will need.
6131 */
6132Blowfish.prototype.BLOCKSIZE = 8;
6133
6134/*
6135 * These are the default SBOXES.
6136 */
6137Blowfish.prototype.SBOXES = [
6138 [
6139 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
6140 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
6141 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,
6142 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
6143 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
6144 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
6145 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,
6146 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
6147 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,
6148 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
6149 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,
6150 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
6151 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
6152 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
6153 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
6154 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
6155 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,
6156 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
6157 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,
6158 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
6159 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,
6160 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
6161 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,
6162 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
6163 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
6164 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
6165 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,
6166 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
6167 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,
6168 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
6169 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,
6170 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
6171 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,
6172 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
6173 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
6174 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
6175 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,
6176 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
6177 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,
6178 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
6179 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,
6180 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
6181 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a
6182 ],
6183 [
6184 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,
6185 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
6186 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,
6187 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
6188 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
6189 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
6190 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
6191 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
6192 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
6193 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
6194 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,
6195 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
6196 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,
6197 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
6198 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,
6199 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
6200 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,
6201 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
6202 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
6203 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
6204 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,
6205 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
6206 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,
6207 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
6208 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,
6209 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
6210 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
6211 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
6212 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
6213 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
6214 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,
6215 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
6216 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,
6217 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
6218 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,
6219 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
6220 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,
6221 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
6222 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
6223 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
6224 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,
6225 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
6226 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7
6227 ],
6228 [
6229 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,
6230 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
6231 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,
6232 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
6233 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,
6234 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
6235 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,
6236 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
6237 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,
6238 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
6239 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,
6240 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
6241 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,
6242 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
6243 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,
6244 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
6245 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,
6246 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
6247 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,
6248 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
6249 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,
6250 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
6251 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,
6252 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
6253 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,
6254 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
6255 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,
6256 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
6257 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,
6258 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
6259 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,
6260 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
6261 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,
6262 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
6263 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,
6264 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
6265 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,
6266 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
6267 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,
6268 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
6269 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,
6270 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
6271 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0
6272 ],
6273 [
6274 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,
6275 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
6276 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,
6277 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
6278 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
6279 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
6280 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
6281 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
6282 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,
6283 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
6284 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,
6285 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
6286 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,
6287 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
6288 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
6289 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
6290 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
6291 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
6292 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,
6293 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
6294 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,
6295 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
6296 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,
6297 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
6298 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,
6299 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
6300 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
6301 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
6302 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,
6303 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
6304 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,
6305 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
6306 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,
6307 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
6308 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,
6309 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
6310 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
6311 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
6312 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,
6313 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
6314 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
6315 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
6316 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
6317 ]
6318];
6319
6320//*
6321//* This is the default PARRAY
6322//*
6323Blowfish.prototype.PARRAY = [
6324 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
6325 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
6326 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b
6327];
6328
6329//*
6330//* This is the number of rounds the cipher will go
6331//*
6332Blowfish.prototype.NN = 16;
6333
6334//*
6335//* This function is needed to get rid of problems
6336//* with the high-bit getting set. If we don't do
6337//* this, then sometimes ( aa & 0x00FFFFFFFF ) is not
6338//* equal to ( bb & 0x00FFFFFFFF ) even when they
6339//* agree bit-for-bit for the first 32 bits.
6340//*
6341Blowfish.prototype._clean = function(xx) {
6342 if (xx < 0) {
6343 const yy = xx & 0x7FFFFFFF;
6344 xx = yy + 0x80000000;
6345 }
6346 return xx;
6347};
6348
6349//*
6350//* This is the mixing function that uses the sboxes
6351//*
6352Blowfish.prototype._F = function(xx) {
6353 let yy;
6354
6355 const dd = xx & 0x00FF;
6356 xx >>>= 8;
6357 const cc = xx & 0x00FF;
6358 xx >>>= 8;
6359 const bb = xx & 0x00FF;
6360 xx >>>= 8;
6361 const aa = xx & 0x00FF;
6362
6363 yy = this.sboxes[0][aa] + this.sboxes[1][bb];
6364 yy ^= this.sboxes[2][cc];
6365 yy += this.sboxes[3][dd];
6366
6367 return yy;
6368};
6369
6370//*
6371//* This method takes an array with two values, left and right
6372//* and does NN rounds of Blowfish on them.
6373//*
6374Blowfish.prototype._encryptBlock = function(vals) {
6375 let dataL = vals[0];
6376 let dataR = vals[1];
6377
6378 let ii;
6379
6380 for (ii = 0; ii < this.NN; ++ii) {
6381 dataL ^= this.parray[ii];
6382 dataR = this._F(dataL) ^ dataR;
6383
6384 const tmp = dataL;
6385 dataL = dataR;
6386 dataR = tmp;
6387 }
6388
6389 dataL ^= this.parray[this.NN + 0];
6390 dataR ^= this.parray[this.NN + 1];
6391
6392 vals[0] = this._clean(dataR);
6393 vals[1] = this._clean(dataL);
6394};
6395
6396//*
6397//* This method takes a vector of numbers and turns them
6398//* into long words so that they can be processed by the
6399//* real algorithm.
6400//*
6401//* Maybe I should make the real algorithm above take a vector
6402//* instead. That will involve more looping, but it won't require
6403//* the F() method to deconstruct the vector.
6404//*
6405Blowfish.prototype.encryptBlock = function(vector) {
6406 let ii;
6407 const vals = [0, 0];
6408 const off = this.BLOCKSIZE / 2;
6409 for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
6410 vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);
6411 vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);
6412 }
6413
6414 this._encryptBlock(vals);
6415
6416 const ret = [];
6417 for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
6418 ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);
6419 ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);
6420 // vals[ 0 ] = ( vals[ 0 ] >>> 8 );
6421 // vals[ 1 ] = ( vals[ 1 ] >>> 8 );
6422 }
6423
6424 return ret;
6425};
6426
6427//*
6428//* This method takes an array with two values, left and right
6429//* and undoes NN rounds of Blowfish on them.
6430//*
6431Blowfish.prototype._decryptBlock = function(vals) {
6432 let dataL = vals[0];
6433 let dataR = vals[1];
6434
6435 let ii;
6436
6437 for (ii = this.NN + 1; ii > 1; --ii) {
6438 dataL ^= this.parray[ii];
6439 dataR = this._F(dataL) ^ dataR;
6440
6441 const tmp = dataL;
6442 dataL = dataR;
6443 dataR = tmp;
6444 }
6445
6446 dataL ^= this.parray[1];
6447 dataR ^= this.parray[0];
6448
6449 vals[0] = this._clean(dataR);
6450 vals[1] = this._clean(dataL);
6451};
6452
6453//*
6454//* This method takes a key array and initializes the
6455//* sboxes and parray for this encryption.
6456//*
6457Blowfish.prototype.init = function(key) {
6458 let ii;
6459 let jj = 0;
6460
6461 this.parray = [];
6462 for (ii = 0; ii < this.NN + 2; ++ii) {
6463 let data = 0x00000000;
6464 for (let kk = 0; kk < 4; ++kk) {
6465 data = (data << 8) | (key[jj] & 0x00FF);
6466 if (++jj >= key.length) {
6467 jj = 0;
6468 }
6469 }
6470 this.parray[ii] = this.PARRAY[ii] ^ data;
6471 }
6472
6473 this.sboxes = [];
6474 for (ii = 0; ii < 4; ++ii) {
6475 this.sboxes[ii] = [];
6476 for (jj = 0; jj < 256; ++jj) {
6477 this.sboxes[ii][jj] = this.SBOXES[ii][jj];
6478 }
6479 }
6480
6481 const vals = [0x00000000, 0x00000000];
6482
6483 for (ii = 0; ii < this.NN + 2; ii += 2) {
6484 this._encryptBlock(vals);
6485 this.parray[ii + 0] = vals[0];
6486 this.parray[ii + 1] = vals[1];
6487 }
6488
6489 for (ii = 0; ii < 4; ++ii) {
6490 for (jj = 0; jj < 256; jj += 2) {
6491 this._encryptBlock(vals);
6492 this.sboxes[ii][jj + 0] = vals[0];
6493 this.sboxes[ii][jj + 1] = vals[1];
6494 }
6495 }
6496};
6497
6498// added by Recurity Labs
6499function BF(key) {
6500 this.bf = new Blowfish();
6501 this.bf.init(key);
6502
6503 this.encrypt = function(block) {
6504 return this.bf.encryptBlock(block);
6505 };
6506}
6507
6508BF.keySize = BF.prototype.keySize = 16;
6509BF.blockSize = BF.prototype.blockSize = 8;
6510
6511/**
6512 * @fileoverview Symmetric cryptography functions
6513 * @module crypto/cipher
6514 * @private
6515 */
6516
6517/**
6518 * AES-128 encryption and decryption (ID 7)
6519 * @function
6520 * @param {String} key - 128-bit key
6521 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
6522 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
6523 * @returns {Object}
6524 */
6525const aes128 = aes(128);
6526/**
6527 * AES-128 Block Cipher (ID 8)
6528 * @function
6529 * @param {String} key - 192-bit key
6530 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
6531 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
6532 * @returns {Object}
6533 */
6534const aes192 = aes(192);
6535/**
6536 * AES-128 Block Cipher (ID 9)
6537 * @function
6538 * @param {String} key - 256-bit key
6539 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
6540 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
6541 * @returns {Object}
6542 */
6543const aes256 = aes(256);
6544// Not in OpenPGP specifications
6545const des$1 = DES;
6546/**
6547 * Triple DES Block Cipher (ID 2)
6548 * @function
6549 * @param {String} key - 192-bit key
6550 * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67}
6551 * @returns {Object}
6552 */
6553const tripledes = TripleDES;
6554/**
6555 * CAST-128 Block Cipher (ID 3)
6556 * @function
6557 * @param {String} key - 128-bit key
6558 * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm}
6559 * @returns {Object}
6560 */
6561const cast5 = CAST5;
6562/**
6563 * Twofish Block Cipher (ID 10)
6564 * @function
6565 * @param {String} key - 256-bit key
6566 * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH}
6567 * @returns {Object}
6568 */
6569const twofish = TF;
6570/**
6571 * Blowfish Block Cipher (ID 4)
6572 * @function
6573 * @param {String} key - 128-bit key
6574 * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH}
6575 * @returns {Object}
6576 */
6577const blowfish = BF;
6578/**
6579 * Not implemented
6580 * @function
6581 * @throws {Error}
6582 */
6583const idea = function() {
6584 throw new Error('IDEA symmetric-key algorithm not implemented');
6585};
6586
6587var cipher = /*#__PURE__*/Object.freeze({
6588 __proto__: null,
6589 aes128: aes128,
6590 aes192: aes192,
6591 aes256: aes256,
6592 des: des$1,
6593 tripledes: tripledes,
6594 cast5: cast5,
6595 twofish: twofish,
6596 blowfish: blowfish,
6597 idea: idea
6598});
6599
6600var sha1_asm = function ( stdlib, foreign, buffer ) {
6601 "use asm";
6602
6603 // SHA256 state
6604 var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0,
6605 TOTAL0 = 0, TOTAL1 = 0;
6606
6607 // HMAC state
6608 var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0,
6609 O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0;
6610
6611 // I/O buffer
6612 var HEAP = new stdlib.Uint8Array(buffer);
6613
6614 function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {
6615 w0 = w0|0;
6616 w1 = w1|0;
6617 w2 = w2|0;
6618 w3 = w3|0;
6619 w4 = w4|0;
6620 w5 = w5|0;
6621 w6 = w6|0;
6622 w7 = w7|0;
6623 w8 = w8|0;
6624 w9 = w9|0;
6625 w10 = w10|0;
6626 w11 = w11|0;
6627 w12 = w12|0;
6628 w13 = w13|0;
6629 w14 = w14|0;
6630 w15 = w15|0;
6631
6632 var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0,
6633 w16 = 0, w17 = 0, w18 = 0, w19 = 0,
6634 w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0,
6635 w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0,
6636 w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0,
6637 w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0,
6638 w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0,
6639 w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0;
6640
6641 a = H0;
6642 b = H1;
6643 c = H2;
6644 d = H3;
6645 e = H4;
6646
6647 // 0
6648 t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6649 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6650
6651 // 1
6652 t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6653 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6654
6655 // 2
6656 t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6657 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6658
6659 // 3
6660 t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6661 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6662
6663 // 4
6664 t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6665 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6666
6667 // 5
6668 t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6669 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6670
6671 // 6
6672 t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6673 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6674
6675 // 7
6676 t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6677 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6678
6679 // 8
6680 t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6681 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6682
6683 // 9
6684 t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6685 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6686
6687 // 10
6688 t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6689 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6690
6691 // 11
6692 t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6693 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6694
6695 // 12
6696 t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6697 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6698
6699 // 13
6700 t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6701 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6702
6703 // 14
6704 t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6705 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6706
6707 // 15
6708 t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6709 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6710
6711 // 16
6712 n = w13 ^ w8 ^ w2 ^ w0;
6713 w16 = (n << 1) | (n >>> 31);
6714 t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6715 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6716
6717 // 17
6718 n = w14 ^ w9 ^ w3 ^ w1;
6719 w17 = (n << 1) | (n >>> 31);
6720 t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6721 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6722
6723 // 18
6724 n = w15 ^ w10 ^ w4 ^ w2;
6725 w18 = (n << 1) | (n >>> 31);
6726 t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6727 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6728
6729 // 19
6730 n = w16 ^ w11 ^ w5 ^ w3;
6731 w19 = (n << 1) | (n >>> 31);
6732 t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6733 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6734
6735 // 20
6736 n = w17 ^ w12 ^ w6 ^ w4;
6737 w20 = (n << 1) | (n >>> 31);
6738 t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6739 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6740
6741 // 21
6742 n = w18 ^ w13 ^ w7 ^ w5;
6743 w21 = (n << 1) | (n >>> 31);
6744 t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6745 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6746
6747 // 22
6748 n = w19 ^ w14 ^ w8 ^ w6;
6749 w22 = (n << 1) | (n >>> 31);
6750 t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6751 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6752
6753 // 23
6754 n = w20 ^ w15 ^ w9 ^ w7;
6755 w23 = (n << 1) | (n >>> 31);
6756 t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6757 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6758
6759 // 24
6760 n = w21 ^ w16 ^ w10 ^ w8;
6761 w24 = (n << 1) | (n >>> 31);
6762 t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6763 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6764
6765 // 25
6766 n = w22 ^ w17 ^ w11 ^ w9;
6767 w25 = (n << 1) | (n >>> 31);
6768 t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6769 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6770
6771 // 26
6772 n = w23 ^ w18 ^ w12 ^ w10;
6773 w26 = (n << 1) | (n >>> 31);
6774 t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6775 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6776
6777 // 27
6778 n = w24 ^ w19 ^ w13 ^ w11;
6779 w27 = (n << 1) | (n >>> 31);
6780 t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6781 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6782
6783 // 28
6784 n = w25 ^ w20 ^ w14 ^ w12;
6785 w28 = (n << 1) | (n >>> 31);
6786 t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6787 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6788
6789 // 29
6790 n = w26 ^ w21 ^ w15 ^ w13;
6791 w29 = (n << 1) | (n >>> 31);
6792 t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6793 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6794
6795 // 30
6796 n = w27 ^ w22 ^ w16 ^ w14;
6797 w30 = (n << 1) | (n >>> 31);
6798 t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6799 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6800
6801 // 31
6802 n = w28 ^ w23 ^ w17 ^ w15;
6803 w31 = (n << 1) | (n >>> 31);
6804 t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6805 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6806
6807 // 32
6808 n = w29 ^ w24 ^ w18 ^ w16;
6809 w32 = (n << 1) | (n >>> 31);
6810 t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6811 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6812
6813 // 33
6814 n = w30 ^ w25 ^ w19 ^ w17;
6815 w33 = (n << 1) | (n >>> 31);
6816 t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6817 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6818
6819 // 34
6820 n = w31 ^ w26 ^ w20 ^ w18;
6821 w34 = (n << 1) | (n >>> 31);
6822 t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6823 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6824
6825 // 35
6826 n = w32 ^ w27 ^ w21 ^ w19;
6827 w35 = (n << 1) | (n >>> 31);
6828 t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6829 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6830
6831 // 36
6832 n = w33 ^ w28 ^ w22 ^ w20;
6833 w36 = (n << 1) | (n >>> 31);
6834 t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6835 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6836
6837 // 37
6838 n = w34 ^ w29 ^ w23 ^ w21;
6839 w37 = (n << 1) | (n >>> 31);
6840 t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6841 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6842
6843 // 38
6844 n = w35 ^ w30 ^ w24 ^ w22;
6845 w38 = (n << 1) | (n >>> 31);
6846 t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6847 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6848
6849 // 39
6850 n = w36 ^ w31 ^ w25 ^ w23;
6851 w39 = (n << 1) | (n >>> 31);
6852 t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6853 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6854
6855 // 40
6856 n = w37 ^ w32 ^ w26 ^ w24;
6857 w40 = (n << 1) | (n >>> 31);
6858 t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6859 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6860
6861 // 41
6862 n = w38 ^ w33 ^ w27 ^ w25;
6863 w41 = (n << 1) | (n >>> 31);
6864 t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6865 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6866
6867 // 42
6868 n = w39 ^ w34 ^ w28 ^ w26;
6869 w42 = (n << 1) | (n >>> 31);
6870 t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6871 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6872
6873 // 43
6874 n = w40 ^ w35 ^ w29 ^ w27;
6875 w43 = (n << 1) | (n >>> 31);
6876 t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6877 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6878
6879 // 44
6880 n = w41 ^ w36 ^ w30 ^ w28;
6881 w44 = (n << 1) | (n >>> 31);
6882 t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6883 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6884
6885 // 45
6886 n = w42 ^ w37 ^ w31 ^ w29;
6887 w45 = (n << 1) | (n >>> 31);
6888 t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6889 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6890
6891 // 46
6892 n = w43 ^ w38 ^ w32 ^ w30;
6893 w46 = (n << 1) | (n >>> 31);
6894 t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6895 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6896
6897 // 47
6898 n = w44 ^ w39 ^ w33 ^ w31;
6899 w47 = (n << 1) | (n >>> 31);
6900 t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6901 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6902
6903 // 48
6904 n = w45 ^ w40 ^ w34 ^ w32;
6905 w48 = (n << 1) | (n >>> 31);
6906 t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6907 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6908
6909 // 49
6910 n = w46 ^ w41 ^ w35 ^ w33;
6911 w49 = (n << 1) | (n >>> 31);
6912 t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6913 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6914
6915 // 50
6916 n = w47 ^ w42 ^ w36 ^ w34;
6917 w50 = (n << 1) | (n >>> 31);
6918 t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6919 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6920
6921 // 51
6922 n = w48 ^ w43 ^ w37 ^ w35;
6923 w51 = (n << 1) | (n >>> 31);
6924 t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6925 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6926
6927 // 52
6928 n = w49 ^ w44 ^ w38 ^ w36;
6929 w52 = (n << 1) | (n >>> 31);
6930 t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6931 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6932
6933 // 53
6934 n = w50 ^ w45 ^ w39 ^ w37;
6935 w53 = (n << 1) | (n >>> 31);
6936 t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6937 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6938
6939 // 54
6940 n = w51 ^ w46 ^ w40 ^ w38;
6941 w54 = (n << 1) | (n >>> 31);
6942 t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6943 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6944
6945 // 55
6946 n = w52 ^ w47 ^ w41 ^ w39;
6947 w55 = (n << 1) | (n >>> 31);
6948 t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6949 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6950
6951 // 56
6952 n = w53 ^ w48 ^ w42 ^ w40;
6953 w56 = (n << 1) | (n >>> 31);
6954 t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6955 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6956
6957 // 57
6958 n = w54 ^ w49 ^ w43 ^ w41;
6959 w57 = (n << 1) | (n >>> 31);
6960 t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6961 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6962
6963 // 58
6964 n = w55 ^ w50 ^ w44 ^ w42;
6965 w58 = (n << 1) | (n >>> 31);
6966 t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6967 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6968
6969 // 59
6970 n = w56 ^ w51 ^ w45 ^ w43;
6971 w59 = (n << 1) | (n >>> 31);
6972 t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6973 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6974
6975 // 60
6976 n = w57 ^ w52 ^ w46 ^ w44;
6977 w60 = (n << 1) | (n >>> 31);
6978 t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6979 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6980
6981 // 61
6982 n = w58 ^ w53 ^ w47 ^ w45;
6983 w61 = (n << 1) | (n >>> 31);
6984 t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6985 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6986
6987 // 62
6988 n = w59 ^ w54 ^ w48 ^ w46;
6989 w62 = (n << 1) | (n >>> 31);
6990 t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6991 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6992
6993 // 63
6994 n = w60 ^ w55 ^ w49 ^ w47;
6995 w63 = (n << 1) | (n >>> 31);
6996 t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6997 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6998
6999 // 64
7000 n = w61 ^ w56 ^ w50 ^ w48;
7001 w64 = (n << 1) | (n >>> 31);
7002 t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7003 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7004
7005 // 65
7006 n = w62 ^ w57 ^ w51 ^ w49;
7007 w65 = (n << 1) | (n >>> 31);
7008 t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7009 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7010
7011 // 66
7012 n = w63 ^ w58 ^ w52 ^ w50;
7013 w66 = (n << 1) | (n >>> 31);
7014 t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7015 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7016
7017 // 67
7018 n = w64 ^ w59 ^ w53 ^ w51;
7019 w67 = (n << 1) | (n >>> 31);
7020 t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7021 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7022
7023 // 68
7024 n = w65 ^ w60 ^ w54 ^ w52;
7025 w68 = (n << 1) | (n >>> 31);
7026 t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7027 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7028
7029 // 69
7030 n = w66 ^ w61 ^ w55 ^ w53;
7031 w69 = (n << 1) | (n >>> 31);
7032 t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7033 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7034
7035 // 70
7036 n = w67 ^ w62 ^ w56 ^ w54;
7037 w70 = (n << 1) | (n >>> 31);
7038 t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7039 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7040
7041 // 71
7042 n = w68 ^ w63 ^ w57 ^ w55;
7043 w71 = (n << 1) | (n >>> 31);
7044 t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7045 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7046
7047 // 72
7048 n = w69 ^ w64 ^ w58 ^ w56;
7049 w72 = (n << 1) | (n >>> 31);
7050 t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7051 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7052
7053 // 73
7054 n = w70 ^ w65 ^ w59 ^ w57;
7055 w73 = (n << 1) | (n >>> 31);
7056 t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7057 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7058
7059 // 74
7060 n = w71 ^ w66 ^ w60 ^ w58;
7061 w74 = (n << 1) | (n >>> 31);
7062 t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7063 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7064
7065 // 75
7066 n = w72 ^ w67 ^ w61 ^ w59;
7067 w75 = (n << 1) | (n >>> 31);
7068 t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7069 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7070
7071 // 76
7072 n = w73 ^ w68 ^ w62 ^ w60;
7073 w76 = (n << 1) | (n >>> 31);
7074 t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7075 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7076
7077 // 77
7078 n = w74 ^ w69 ^ w63 ^ w61;
7079 w77 = (n << 1) | (n >>> 31);
7080 t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7081 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7082
7083 // 78
7084 n = w75 ^ w70 ^ w64 ^ w62;
7085 w78 = (n << 1) | (n >>> 31);
7086 t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7087 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7088
7089 // 79
7090 n = w76 ^ w71 ^ w65 ^ w63;
7091 w79 = (n << 1) | (n >>> 31);
7092 t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
7093 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
7094
7095 H0 = ( H0 + a )|0;
7096 H1 = ( H1 + b )|0;
7097 H2 = ( H2 + c )|0;
7098 H3 = ( H3 + d )|0;
7099 H4 = ( H4 + e )|0;
7100
7101 }
7102
7103 function _core_heap ( offset ) {
7104 offset = offset|0;
7105
7106 _core(
7107 HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],
7108 HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],
7109 HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],
7110 HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],
7111 HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],
7112 HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],
7113 HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],
7114 HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],
7115 HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],
7116 HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],
7117 HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],
7118 HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],
7119 HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],
7120 HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],
7121 HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],
7122 HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]
7123 );
7124 }
7125
7126 // offset — multiple of 32
7127 function _state_to_heap ( output ) {
7128 output = output|0;
7129
7130 HEAP[output|0] = H0>>>24;
7131 HEAP[output|1] = H0>>>16&255;
7132 HEAP[output|2] = H0>>>8&255;
7133 HEAP[output|3] = H0&255;
7134 HEAP[output|4] = H1>>>24;
7135 HEAP[output|5] = H1>>>16&255;
7136 HEAP[output|6] = H1>>>8&255;
7137 HEAP[output|7] = H1&255;
7138 HEAP[output|8] = H2>>>24;
7139 HEAP[output|9] = H2>>>16&255;
7140 HEAP[output|10] = H2>>>8&255;
7141 HEAP[output|11] = H2&255;
7142 HEAP[output|12] = H3>>>24;
7143 HEAP[output|13] = H3>>>16&255;
7144 HEAP[output|14] = H3>>>8&255;
7145 HEAP[output|15] = H3&255;
7146 HEAP[output|16] = H4>>>24;
7147 HEAP[output|17] = H4>>>16&255;
7148 HEAP[output|18] = H4>>>8&255;
7149 HEAP[output|19] = H4&255;
7150 }
7151
7152 function reset () {
7153 H0 = 0x67452301;
7154 H1 = 0xefcdab89;
7155 H2 = 0x98badcfe;
7156 H3 = 0x10325476;
7157 H4 = 0xc3d2e1f0;
7158 TOTAL0 = TOTAL1 = 0;
7159 }
7160
7161 function init ( h0, h1, h2, h3, h4, total0, total1 ) {
7162 h0 = h0|0;
7163 h1 = h1|0;
7164 h2 = h2|0;
7165 h3 = h3|0;
7166 h4 = h4|0;
7167 total0 = total0|0;
7168 total1 = total1|0;
7169
7170 H0 = h0;
7171 H1 = h1;
7172 H2 = h2;
7173 H3 = h3;
7174 H4 = h4;
7175 TOTAL0 = total0;
7176 TOTAL1 = total1;
7177 }
7178
7179 // offset — multiple of 64
7180 function process ( offset, length ) {
7181 offset = offset|0;
7182 length = length|0;
7183
7184 var hashed = 0;
7185
7186 if ( offset & 63 )
7187 return -1;
7188
7189 while ( (length|0) >= 64 ) {
7190 _core_heap(offset);
7191
7192 offset = ( offset + 64 )|0;
7193 length = ( length - 64 )|0;
7194
7195 hashed = ( hashed + 64 )|0;
7196 }
7197
7198 TOTAL0 = ( TOTAL0 + hashed )|0;
7199 if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
7200
7201 return hashed|0;
7202 }
7203
7204 // offset — multiple of 64
7205 // output — multiple of 32
7206 function finish ( offset, length, output ) {
7207 offset = offset|0;
7208 length = length|0;
7209 output = output|0;
7210
7211 var hashed = 0,
7212 i = 0;
7213
7214 if ( offset & 63 )
7215 return -1;
7216
7217 if ( ~output )
7218 if ( output & 31 )
7219 return -1;
7220
7221 if ( (length|0) >= 64 ) {
7222 hashed = process( offset, length )|0;
7223 if ( (hashed|0) == -1 )
7224 return -1;
7225
7226 offset = ( offset + hashed )|0;
7227 length = ( length - hashed )|0;
7228 }
7229
7230 hashed = ( hashed + length )|0;
7231 TOTAL0 = ( TOTAL0 + length )|0;
7232 if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0;
7233
7234 HEAP[offset|length] = 0x80;
7235
7236 if ( (length|0) >= 56 ) {
7237 for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )
7238 HEAP[offset|i] = 0x00;
7239 _core_heap(offset);
7240
7241 length = 0;
7242
7243 HEAP[offset|0] = 0;
7244 }
7245
7246 for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )
7247 HEAP[offset|i] = 0;
7248
7249 HEAP[offset|56] = TOTAL1>>>21&255;
7250 HEAP[offset|57] = TOTAL1>>>13&255;
7251 HEAP[offset|58] = TOTAL1>>>5&255;
7252 HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;
7253 HEAP[offset|60] = TOTAL0>>>21&255;
7254 HEAP[offset|61] = TOTAL0>>>13&255;
7255 HEAP[offset|62] = TOTAL0>>>5&255;
7256 HEAP[offset|63] = TOTAL0<<3&255;
7257 _core_heap(offset);
7258
7259 if ( ~output )
7260 _state_to_heap(output);
7261
7262 return hashed|0;
7263 }
7264
7265 function hmac_reset () {
7266 H0 = I0;
7267 H1 = I1;
7268 H2 = I2;
7269 H3 = I3;
7270 H4 = I4;
7271 TOTAL0 = 64;
7272 TOTAL1 = 0;
7273 }
7274
7275 function _hmac_opad () {
7276 H0 = O0;
7277 H1 = O1;
7278 H2 = O2;
7279 H3 = O3;
7280 H4 = O4;
7281 TOTAL0 = 64;
7282 TOTAL1 = 0;
7283 }
7284
7285 function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {
7286 p0 = p0|0;
7287 p1 = p1|0;
7288 p2 = p2|0;
7289 p3 = p3|0;
7290 p4 = p4|0;
7291 p5 = p5|0;
7292 p6 = p6|0;
7293 p7 = p7|0;
7294 p8 = p8|0;
7295 p9 = p9|0;
7296 p10 = p10|0;
7297 p11 = p11|0;
7298 p12 = p12|0;
7299 p13 = p13|0;
7300 p14 = p14|0;
7301 p15 = p15|0;
7302
7303 // opad
7304 reset();
7305 _core(
7306 p0 ^ 0x5c5c5c5c,
7307 p1 ^ 0x5c5c5c5c,
7308 p2 ^ 0x5c5c5c5c,
7309 p3 ^ 0x5c5c5c5c,
7310 p4 ^ 0x5c5c5c5c,
7311 p5 ^ 0x5c5c5c5c,
7312 p6 ^ 0x5c5c5c5c,
7313 p7 ^ 0x5c5c5c5c,
7314 p8 ^ 0x5c5c5c5c,
7315 p9 ^ 0x5c5c5c5c,
7316 p10 ^ 0x5c5c5c5c,
7317 p11 ^ 0x5c5c5c5c,
7318 p12 ^ 0x5c5c5c5c,
7319 p13 ^ 0x5c5c5c5c,
7320 p14 ^ 0x5c5c5c5c,
7321 p15 ^ 0x5c5c5c5c
7322 );
7323 O0 = H0;
7324 O1 = H1;
7325 O2 = H2;
7326 O3 = H3;
7327 O4 = H4;
7328
7329 // ipad
7330 reset();
7331 _core(
7332 p0 ^ 0x36363636,
7333 p1 ^ 0x36363636,
7334 p2 ^ 0x36363636,
7335 p3 ^ 0x36363636,
7336 p4 ^ 0x36363636,
7337 p5 ^ 0x36363636,
7338 p6 ^ 0x36363636,
7339 p7 ^ 0x36363636,
7340 p8 ^ 0x36363636,
7341 p9 ^ 0x36363636,
7342 p10 ^ 0x36363636,
7343 p11 ^ 0x36363636,
7344 p12 ^ 0x36363636,
7345 p13 ^ 0x36363636,
7346 p14 ^ 0x36363636,
7347 p15 ^ 0x36363636
7348 );
7349 I0 = H0;
7350 I1 = H1;
7351 I2 = H2;
7352 I3 = H3;
7353 I4 = H4;
7354
7355 TOTAL0 = 64;
7356 TOTAL1 = 0;
7357 }
7358
7359 // offset — multiple of 64
7360 // output — multiple of 32
7361 function hmac_finish ( offset, length, output ) {
7362 offset = offset|0;
7363 length = length|0;
7364 output = output|0;
7365
7366 var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0;
7367
7368 if ( offset & 63 )
7369 return -1;
7370
7371 if ( ~output )
7372 if ( output & 31 )
7373 return -1;
7374
7375 hashed = finish( offset, length, -1 )|0;
7376 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
7377
7378 _hmac_opad();
7379 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
7380
7381 if ( ~output )
7382 _state_to_heap(output);
7383
7384 return hashed|0;
7385 }
7386
7387 // salt is assumed to be already processed
7388 // offset — multiple of 64
7389 // output — multiple of 32
7390 function pbkdf2_generate_block ( offset, length, block, count, output ) {
7391 offset = offset|0;
7392 length = length|0;
7393 block = block|0;
7394 count = count|0;
7395 output = output|0;
7396
7397 var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0,
7398 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
7399
7400 if ( offset & 63 )
7401 return -1;
7402
7403 if ( ~output )
7404 if ( output & 31 )
7405 return -1;
7406
7407 // pad block number into heap
7408 // FIXME probable OOB write
7409 HEAP[(offset+length)|0] = block>>>24;
7410 HEAP[(offset+length+1)|0] = block>>>16&255;
7411 HEAP[(offset+length+2)|0] = block>>>8&255;
7412 HEAP[(offset+length+3)|0] = block&255;
7413
7414 // finish first iteration
7415 hmac_finish( offset, (length+4)|0, -1 )|0;
7416 h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4;
7417 count = (count-1)|0;
7418
7419 // perform the rest iterations
7420 while ( (count|0) > 0 ) {
7421 hmac_reset();
7422 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
7423 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
7424
7425 _hmac_opad();
7426 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
7427 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
7428
7429 h0 = h0 ^ H0;
7430 h1 = h1 ^ H1;
7431 h2 = h2 ^ H2;
7432 h3 = h3 ^ H3;
7433 h4 = h4 ^ H4;
7434
7435 count = (count-1)|0;
7436 }
7437
7438 H0 = h0;
7439 H1 = h1;
7440 H2 = h2;
7441 H3 = h3;
7442 H4 = h4;
7443
7444 if ( ~output )
7445 _state_to_heap(output);
7446
7447 return 0;
7448 }
7449
7450 return {
7451 // SHA1
7452 reset: reset,
7453 init: init,
7454 process: process,
7455 finish: finish,
7456
7457 // HMAC-SHA1
7458 hmac_reset: hmac_reset,
7459 hmac_init: hmac_init,
7460 hmac_finish: hmac_finish,
7461
7462 // PBKDF2-HMAC-SHA1
7463 pbkdf2_generate_block: pbkdf2_generate_block
7464 }
7465};
7466
7467class Hash {
7468 constructor() {
7469 this.pos = 0;
7470 this.len = 0;
7471 }
7472 reset() {
7473 const { asm } = this.acquire_asm();
7474 this.result = null;
7475 this.pos = 0;
7476 this.len = 0;
7477 asm.reset();
7478 return this;
7479 }
7480 process(data) {
7481 if (this.result !== null)
7482 throw new IllegalStateError('state must be reset before processing new data');
7483 const { asm, heap } = this.acquire_asm();
7484 let hpos = this.pos;
7485 let hlen = this.len;
7486 let dpos = 0;
7487 let dlen = data.length;
7488 let wlen = 0;
7489 while (dlen > 0) {
7490 wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen);
7491 hlen += wlen;
7492 dpos += wlen;
7493 dlen -= wlen;
7494 wlen = asm.process(hpos, hlen);
7495 hpos += wlen;
7496 hlen -= wlen;
7497 if (!hlen)
7498 hpos = 0;
7499 }
7500 this.pos = hpos;
7501 this.len = hlen;
7502 return this;
7503 }
7504 finish() {
7505 if (this.result !== null)
7506 throw new IllegalStateError('state must be reset before processing new data');
7507 const { asm, heap } = this.acquire_asm();
7508 asm.finish(this.pos, this.len, 0);
7509 this.result = new Uint8Array(this.HASH_SIZE);
7510 this.result.set(heap.subarray(0, this.HASH_SIZE));
7511 this.pos = 0;
7512 this.len = 0;
7513 this.release_asm();
7514 return this;
7515 }
7516}
7517
7518const _sha1_block_size = 64;
7519const _sha1_hash_size = 20;
7520const heap_pool$1 = [];
7521const asm_pool$1 = [];
7522class Sha1 extends Hash {
7523 constructor() {
7524 super();
7525 this.NAME = 'sha1';
7526 this.BLOCK_SIZE = _sha1_block_size;
7527 this.HASH_SIZE = _sha1_hash_size;
7528 this.acquire_asm();
7529 }
7530 acquire_asm() {
7531 if (this.heap === undefined || this.asm === undefined) {
7532 this.heap = heap_pool$1.pop() || _heap_init();
7533 this.asm = asm_pool$1.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);
7534 this.reset();
7535 }
7536 return { heap: this.heap, asm: this.asm };
7537 }
7538 release_asm() {
7539 if (this.heap !== undefined && this.asm !== undefined) {
7540 heap_pool$1.push(this.heap);
7541 asm_pool$1.push(this.asm);
7542 }
7543 this.heap = undefined;
7544 this.asm = undefined;
7545 }
7546 static bytes(data) {
7547 return new Sha1().process(data).finish().result;
7548 }
7549}
7550Sha1.NAME = 'sha1';
7551Sha1.heap_pool = [];
7552Sha1.asm_pool = [];
7553Sha1.asm_function = sha1_asm;
7554
7555var sha256_asm = function ( stdlib, foreign, buffer ) {
7556 "use asm";
7557
7558 // SHA256 state
7559 var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0,
7560 TOTAL0 = 0, TOTAL1 = 0;
7561
7562 // HMAC state
7563 var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0,
7564 O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0;
7565
7566 // I/O buffer
7567 var HEAP = new stdlib.Uint8Array(buffer);
7568
7569 function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {
7570 w0 = w0|0;
7571 w1 = w1|0;
7572 w2 = w2|0;
7573 w3 = w3|0;
7574 w4 = w4|0;
7575 w5 = w5|0;
7576 w6 = w6|0;
7577 w7 = w7|0;
7578 w8 = w8|0;
7579 w9 = w9|0;
7580 w10 = w10|0;
7581 w11 = w11|0;
7582 w12 = w12|0;
7583 w13 = w13|0;
7584 w14 = w14|0;
7585 w15 = w15|0;
7586
7587 var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0;
7588
7589 a = H0;
7590 b = H1;
7591 c = H2;
7592 d = H3;
7593 e = H4;
7594 f = H5;
7595 g = H6;
7596 h = H7;
7597
7598 // 0
7599 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0;
7600 d = ( d + h )|0;
7601 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7602
7603 // 1
7604 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0;
7605 c = ( c + g )|0;
7606 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7607
7608 // 2
7609 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0;
7610 b = ( b + f )|0;
7611 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7612
7613 // 3
7614 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0;
7615 a = ( a + e )|0;
7616 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7617
7618 // 4
7619 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0;
7620 h = ( h + d )|0;
7621 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7622
7623 // 5
7624 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0;
7625 g = ( g + c )|0;
7626 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7627
7628 // 6
7629 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0;
7630 f = ( f + b )|0;
7631 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7632
7633 // 7
7634 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0;
7635 e = ( e + a )|0;
7636 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7637
7638 // 8
7639 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0;
7640 d = ( d + h )|0;
7641 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7642
7643 // 9
7644 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0;
7645 c = ( c + g )|0;
7646 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7647
7648 // 10
7649 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0;
7650 b = ( b + f )|0;
7651 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7652
7653 // 11
7654 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0;
7655 a = ( a + e )|0;
7656 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7657
7658 // 12
7659 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0;
7660 h = ( h + d )|0;
7661 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7662
7663 // 13
7664 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0;
7665 g = ( g + c )|0;
7666 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7667
7668 // 14
7669 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0;
7670 f = ( f + b )|0;
7671 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7672
7673 // 15
7674 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0;
7675 e = ( e + a )|0;
7676 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7677
7678 // 16
7679 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
7680 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0;
7681 d = ( d + h )|0;
7682 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7683
7684 // 17
7685 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
7686 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0;
7687 c = ( c + g )|0;
7688 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7689
7690 // 18
7691 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
7692 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0;
7693 b = ( b + f )|0;
7694 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7695
7696 // 19
7697 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
7698 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0;
7699 a = ( a + e )|0;
7700 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7701
7702 // 20
7703 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
7704 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0;
7705 h = ( h + d )|0;
7706 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7707
7708 // 21
7709 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
7710 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0;
7711 g = ( g + c )|0;
7712 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7713
7714 // 22
7715 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
7716 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0;
7717 f = ( f + b )|0;
7718 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7719
7720 // 23
7721 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
7722 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0;
7723 e = ( e + a )|0;
7724 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7725
7726 // 24
7727 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
7728 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0;
7729 d = ( d + h )|0;
7730 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7731
7732 // 25
7733 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
7734 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0;
7735 c = ( c + g )|0;
7736 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7737
7738 // 26
7739 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
7740 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0;
7741 b = ( b + f )|0;
7742 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7743
7744 // 27
7745 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
7746 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0;
7747 a = ( a + e )|0;
7748 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7749
7750 // 28
7751 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
7752 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0;
7753 h = ( h + d )|0;
7754 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7755
7756 // 29
7757 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
7758 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0;
7759 g = ( g + c )|0;
7760 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7761
7762 // 30
7763 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
7764 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0;
7765 f = ( f + b )|0;
7766 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7767
7768 // 31
7769 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
7770 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0;
7771 e = ( e + a )|0;
7772 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7773
7774 // 32
7775 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
7776 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0;
7777 d = ( d + h )|0;
7778 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7779
7780 // 33
7781 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
7782 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0;
7783 c = ( c + g )|0;
7784 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7785
7786 // 34
7787 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
7788 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0;
7789 b = ( b + f )|0;
7790 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7791
7792 // 35
7793 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
7794 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0;
7795 a = ( a + e )|0;
7796 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7797
7798 // 36
7799 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
7800 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0;
7801 h = ( h + d )|0;
7802 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7803
7804 // 37
7805 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
7806 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0;
7807 g = ( g + c )|0;
7808 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7809
7810 // 38
7811 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
7812 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0;
7813 f = ( f + b )|0;
7814 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7815
7816 // 39
7817 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
7818 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0;
7819 e = ( e + a )|0;
7820 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7821
7822 // 40
7823 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
7824 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0;
7825 d = ( d + h )|0;
7826 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7827
7828 // 41
7829 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
7830 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0;
7831 c = ( c + g )|0;
7832 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7833
7834 // 42
7835 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
7836 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0;
7837 b = ( b + f )|0;
7838 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7839
7840 // 43
7841 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
7842 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0;
7843 a = ( a + e )|0;
7844 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7845
7846 // 44
7847 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
7848 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0;
7849 h = ( h + d )|0;
7850 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7851
7852 // 45
7853 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
7854 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0;
7855 g = ( g + c )|0;
7856 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7857
7858 // 46
7859 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
7860 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0;
7861 f = ( f + b )|0;
7862 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7863
7864 // 47
7865 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
7866 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0;
7867 e = ( e + a )|0;
7868 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7869
7870 // 48
7871 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
7872 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0;
7873 d = ( d + h )|0;
7874 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7875
7876 // 49
7877 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
7878 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0;
7879 c = ( c + g )|0;
7880 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7881
7882 // 50
7883 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
7884 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0;
7885 b = ( b + f )|0;
7886 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7887
7888 // 51
7889 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
7890 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0;
7891 a = ( a + e )|0;
7892 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7893
7894 // 52
7895 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
7896 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0;
7897 h = ( h + d )|0;
7898 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7899
7900 // 53
7901 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
7902 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0;
7903 g = ( g + c )|0;
7904 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7905
7906 // 54
7907 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
7908 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0;
7909 f = ( f + b )|0;
7910 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7911
7912 // 55
7913 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
7914 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0;
7915 e = ( e + a )|0;
7916 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7917
7918 // 56
7919 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
7920 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0;
7921 d = ( d + h )|0;
7922 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7923
7924 // 57
7925 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
7926 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0;
7927 c = ( c + g )|0;
7928 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7929
7930 // 58
7931 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
7932 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0;
7933 b = ( b + f )|0;
7934 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7935
7936 // 59
7937 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
7938 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0;
7939 a = ( a + e )|0;
7940 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7941
7942 // 60
7943 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
7944 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0;
7945 h = ( h + d )|0;
7946 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7947
7948 // 61
7949 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
7950 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0;
7951 g = ( g + c )|0;
7952 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7953
7954 // 62
7955 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
7956 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0;
7957 f = ( f + b )|0;
7958 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7959
7960 // 63
7961 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
7962 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0;
7963 e = ( e + a )|0;
7964 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7965
7966 H0 = ( H0 + a )|0;
7967 H1 = ( H1 + b )|0;
7968 H2 = ( H2 + c )|0;
7969 H3 = ( H3 + d )|0;
7970 H4 = ( H4 + e )|0;
7971 H5 = ( H5 + f )|0;
7972 H6 = ( H6 + g )|0;
7973 H7 = ( H7 + h )|0;
7974 }
7975
7976 function _core_heap ( offset ) {
7977 offset = offset|0;
7978
7979 _core(
7980 HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],
7981 HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],
7982 HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],
7983 HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],
7984 HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],
7985 HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],
7986 HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],
7987 HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],
7988 HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],
7989 HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],
7990 HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],
7991 HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],
7992 HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],
7993 HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],
7994 HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],
7995 HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]
7996 );
7997 }
7998
7999 // offset — multiple of 32
8000 function _state_to_heap ( output ) {
8001 output = output|0;
8002
8003 HEAP[output|0] = H0>>>24;
8004 HEAP[output|1] = H0>>>16&255;
8005 HEAP[output|2] = H0>>>8&255;
8006 HEAP[output|3] = H0&255;
8007 HEAP[output|4] = H1>>>24;
8008 HEAP[output|5] = H1>>>16&255;
8009 HEAP[output|6] = H1>>>8&255;
8010 HEAP[output|7] = H1&255;
8011 HEAP[output|8] = H2>>>24;
8012 HEAP[output|9] = H2>>>16&255;
8013 HEAP[output|10] = H2>>>8&255;
8014 HEAP[output|11] = H2&255;
8015 HEAP[output|12] = H3>>>24;
8016 HEAP[output|13] = H3>>>16&255;
8017 HEAP[output|14] = H3>>>8&255;
8018 HEAP[output|15] = H3&255;
8019 HEAP[output|16] = H4>>>24;
8020 HEAP[output|17] = H4>>>16&255;
8021 HEAP[output|18] = H4>>>8&255;
8022 HEAP[output|19] = H4&255;
8023 HEAP[output|20] = H5>>>24;
8024 HEAP[output|21] = H5>>>16&255;
8025 HEAP[output|22] = H5>>>8&255;
8026 HEAP[output|23] = H5&255;
8027 HEAP[output|24] = H6>>>24;
8028 HEAP[output|25] = H6>>>16&255;
8029 HEAP[output|26] = H6>>>8&255;
8030 HEAP[output|27] = H6&255;
8031 HEAP[output|28] = H7>>>24;
8032 HEAP[output|29] = H7>>>16&255;
8033 HEAP[output|30] = H7>>>8&255;
8034 HEAP[output|31] = H7&255;
8035 }
8036
8037 function reset () {
8038 H0 = 0x6a09e667;
8039 H1 = 0xbb67ae85;
8040 H2 = 0x3c6ef372;
8041 H3 = 0xa54ff53a;
8042 H4 = 0x510e527f;
8043 H5 = 0x9b05688c;
8044 H6 = 0x1f83d9ab;
8045 H7 = 0x5be0cd19;
8046 TOTAL0 = TOTAL1 = 0;
8047 }
8048
8049 function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) {
8050 h0 = h0|0;
8051 h1 = h1|0;
8052 h2 = h2|0;
8053 h3 = h3|0;
8054 h4 = h4|0;
8055 h5 = h5|0;
8056 h6 = h6|0;
8057 h7 = h7|0;
8058 total0 = total0|0;
8059 total1 = total1|0;
8060
8061 H0 = h0;
8062 H1 = h1;
8063 H2 = h2;
8064 H3 = h3;
8065 H4 = h4;
8066 H5 = h5;
8067 H6 = h6;
8068 H7 = h7;
8069 TOTAL0 = total0;
8070 TOTAL1 = total1;
8071 }
8072
8073 // offset — multiple of 64
8074 function process ( offset, length ) {
8075 offset = offset|0;
8076 length = length|0;
8077
8078 var hashed = 0;
8079
8080 if ( offset & 63 )
8081 return -1;
8082
8083 while ( (length|0) >= 64 ) {
8084 _core_heap(offset);
8085
8086 offset = ( offset + 64 )|0;
8087 length = ( length - 64 )|0;
8088
8089 hashed = ( hashed + 64 )|0;
8090 }
8091
8092 TOTAL0 = ( TOTAL0 + hashed )|0;
8093 if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
8094
8095 return hashed|0;
8096 }
8097
8098 // offset — multiple of 64
8099 // output — multiple of 32
8100 function finish ( offset, length, output ) {
8101 offset = offset|0;
8102 length = length|0;
8103 output = output|0;
8104
8105 var hashed = 0,
8106 i = 0;
8107
8108 if ( offset & 63 )
8109 return -1;
8110
8111 if ( ~output )
8112 if ( output & 31 )
8113 return -1;
8114
8115 if ( (length|0) >= 64 ) {
8116 hashed = process( offset, length )|0;
8117 if ( (hashed|0) == -1 )
8118 return -1;
8119
8120 offset = ( offset + hashed )|0;
8121 length = ( length - hashed )|0;
8122 }
8123
8124 hashed = ( hashed + length )|0;
8125 TOTAL0 = ( TOTAL0 + length )|0;
8126 if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
8127
8128 HEAP[offset|length] = 0x80;
8129
8130 if ( (length|0) >= 56 ) {
8131 for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )
8132 HEAP[offset|i] = 0x00;
8133
8134 _core_heap(offset);
8135
8136 length = 0;
8137
8138 HEAP[offset|0] = 0;
8139 }
8140
8141 for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )
8142 HEAP[offset|i] = 0;
8143
8144 HEAP[offset|56] = TOTAL1>>>21&255;
8145 HEAP[offset|57] = TOTAL1>>>13&255;
8146 HEAP[offset|58] = TOTAL1>>>5&255;
8147 HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;
8148 HEAP[offset|60] = TOTAL0>>>21&255;
8149 HEAP[offset|61] = TOTAL0>>>13&255;
8150 HEAP[offset|62] = TOTAL0>>>5&255;
8151 HEAP[offset|63] = TOTAL0<<3&255;
8152 _core_heap(offset);
8153
8154 if ( ~output )
8155 _state_to_heap(output);
8156
8157 return hashed|0;
8158 }
8159
8160 function hmac_reset () {
8161 H0 = I0;
8162 H1 = I1;
8163 H2 = I2;
8164 H3 = I3;
8165 H4 = I4;
8166 H5 = I5;
8167 H6 = I6;
8168 H7 = I7;
8169 TOTAL0 = 64;
8170 TOTAL1 = 0;
8171 }
8172
8173 function _hmac_opad () {
8174 H0 = O0;
8175 H1 = O1;
8176 H2 = O2;
8177 H3 = O3;
8178 H4 = O4;
8179 H5 = O5;
8180 H6 = O6;
8181 H7 = O7;
8182 TOTAL0 = 64;
8183 TOTAL1 = 0;
8184 }
8185
8186 function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {
8187 p0 = p0|0;
8188 p1 = p1|0;
8189 p2 = p2|0;
8190 p3 = p3|0;
8191 p4 = p4|0;
8192 p5 = p5|0;
8193 p6 = p6|0;
8194 p7 = p7|0;
8195 p8 = p8|0;
8196 p9 = p9|0;
8197 p10 = p10|0;
8198 p11 = p11|0;
8199 p12 = p12|0;
8200 p13 = p13|0;
8201 p14 = p14|0;
8202 p15 = p15|0;
8203
8204 // opad
8205 reset();
8206 _core(
8207 p0 ^ 0x5c5c5c5c,
8208 p1 ^ 0x5c5c5c5c,
8209 p2 ^ 0x5c5c5c5c,
8210 p3 ^ 0x5c5c5c5c,
8211 p4 ^ 0x5c5c5c5c,
8212 p5 ^ 0x5c5c5c5c,
8213 p6 ^ 0x5c5c5c5c,
8214 p7 ^ 0x5c5c5c5c,
8215 p8 ^ 0x5c5c5c5c,
8216 p9 ^ 0x5c5c5c5c,
8217 p10 ^ 0x5c5c5c5c,
8218 p11 ^ 0x5c5c5c5c,
8219 p12 ^ 0x5c5c5c5c,
8220 p13 ^ 0x5c5c5c5c,
8221 p14 ^ 0x5c5c5c5c,
8222 p15 ^ 0x5c5c5c5c
8223 );
8224 O0 = H0;
8225 O1 = H1;
8226 O2 = H2;
8227 O3 = H3;
8228 O4 = H4;
8229 O5 = H5;
8230 O6 = H6;
8231 O7 = H7;
8232
8233 // ipad
8234 reset();
8235 _core(
8236 p0 ^ 0x36363636,
8237 p1 ^ 0x36363636,
8238 p2 ^ 0x36363636,
8239 p3 ^ 0x36363636,
8240 p4 ^ 0x36363636,
8241 p5 ^ 0x36363636,
8242 p6 ^ 0x36363636,
8243 p7 ^ 0x36363636,
8244 p8 ^ 0x36363636,
8245 p9 ^ 0x36363636,
8246 p10 ^ 0x36363636,
8247 p11 ^ 0x36363636,
8248 p12 ^ 0x36363636,
8249 p13 ^ 0x36363636,
8250 p14 ^ 0x36363636,
8251 p15 ^ 0x36363636
8252 );
8253 I0 = H0;
8254 I1 = H1;
8255 I2 = H2;
8256 I3 = H3;
8257 I4 = H4;
8258 I5 = H5;
8259 I6 = H6;
8260 I7 = H7;
8261
8262 TOTAL0 = 64;
8263 TOTAL1 = 0;
8264 }
8265
8266 // offset — multiple of 64
8267 // output — multiple of 32
8268 function hmac_finish ( offset, length, output ) {
8269 offset = offset|0;
8270 length = length|0;
8271 output = output|0;
8272
8273 var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
8274 hashed = 0;
8275
8276 if ( offset & 63 )
8277 return -1;
8278
8279 if ( ~output )
8280 if ( output & 31 )
8281 return -1;
8282
8283 hashed = finish( offset, length, -1 )|0;
8284 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
8285
8286 _hmac_opad();
8287 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
8288
8289 if ( ~output )
8290 _state_to_heap(output);
8291
8292 return hashed|0;
8293 }
8294
8295 // salt is assumed to be already processed
8296 // offset — multiple of 64
8297 // output — multiple of 32
8298 function pbkdf2_generate_block ( offset, length, block, count, output ) {
8299 offset = offset|0;
8300 length = length|0;
8301 block = block|0;
8302 count = count|0;
8303 output = output|0;
8304
8305 var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0,
8306 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0;
8307
8308 if ( offset & 63 )
8309 return -1;
8310
8311 if ( ~output )
8312 if ( output & 31 )
8313 return -1;
8314
8315 // pad block number into heap
8316 // FIXME probable OOB write
8317 HEAP[(offset+length)|0] = block>>>24;
8318 HEAP[(offset+length+1)|0] = block>>>16&255;
8319 HEAP[(offset+length+2)|0] = block>>>8&255;
8320 HEAP[(offset+length+3)|0] = block&255;
8321
8322 // finish first iteration
8323 hmac_finish( offset, (length+4)|0, -1 )|0;
8324 h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7;
8325 count = (count-1)|0;
8326
8327 // perform the rest iterations
8328 while ( (count|0) > 0 ) {
8329 hmac_reset();
8330 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
8331 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
8332
8333 _hmac_opad();
8334 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
8335 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
8336
8337 h0 = h0 ^ H0;
8338 h1 = h1 ^ H1;
8339 h2 = h2 ^ H2;
8340 h3 = h3 ^ H3;
8341 h4 = h4 ^ H4;
8342 h5 = h5 ^ H5;
8343 h6 = h6 ^ H6;
8344 h7 = h7 ^ H7;
8345
8346 count = (count-1)|0;
8347 }
8348
8349 H0 = h0;
8350 H1 = h1;
8351 H2 = h2;
8352 H3 = h3;
8353 H4 = h4;
8354 H5 = h5;
8355 H6 = h6;
8356 H7 = h7;
8357
8358 if ( ~output )
8359 _state_to_heap(output);
8360
8361 return 0;
8362 }
8363
8364 return {
8365 // SHA256
8366 reset: reset,
8367 init: init,
8368 process: process,
8369 finish: finish,
8370
8371 // HMAC-SHA256
8372 hmac_reset: hmac_reset,
8373 hmac_init: hmac_init,
8374 hmac_finish: hmac_finish,
8375
8376 // PBKDF2-HMAC-SHA256
8377 pbkdf2_generate_block: pbkdf2_generate_block
8378 }
8379};
8380
8381const _sha256_block_size = 64;
8382const _sha256_hash_size = 32;
8383const heap_pool$2 = [];
8384const asm_pool$2 = [];
8385class Sha256 extends Hash {
8386 constructor() {
8387 super();
8388 this.NAME = 'sha256';
8389 this.BLOCK_SIZE = _sha256_block_size;
8390 this.HASH_SIZE = _sha256_hash_size;
8391 this.acquire_asm();
8392 }
8393 acquire_asm() {
8394 if (this.heap === undefined || this.asm === undefined) {
8395 this.heap = heap_pool$2.pop() || _heap_init();
8396 this.asm = asm_pool$2.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);
8397 this.reset();
8398 }
8399 return { heap: this.heap, asm: this.asm };
8400 }
8401 release_asm() {
8402 if (this.heap !== undefined && this.asm !== undefined) {
8403 heap_pool$2.push(this.heap);
8404 asm_pool$2.push(this.asm);
8405 }
8406 this.heap = undefined;
8407 this.asm = undefined;
8408 }
8409 static bytes(data) {
8410 return new Sha256().process(data).finish().result;
8411 }
8412}
8413Sha256.NAME = 'sha256';
8414
8415var minimalisticAssert = assert;
8416
8417function assert(val, msg) {
8418 if (!val)
8419 throw new Error(msg || 'Assertion failed');
8420}
8421
8422assert.equal = function assertEqual(l, r, msg) {
8423 if (l != r)
8424 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
8425};
8426
8427var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
8428
8429function createCommonjsModule(fn, module) {
8430 return module = { exports: {} }, fn(module, module.exports), module.exports;
8431}
8432
8433function commonjsRequire () {
8434 throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
8435}
8436
8437var inherits_browser = createCommonjsModule(function (module) {
8438if (typeof Object.create === 'function') {
8439 // implementation from standard node.js 'util' module
8440 module.exports = function inherits(ctor, superCtor) {
8441 ctor.super_ = superCtor;
8442 ctor.prototype = Object.create(superCtor.prototype, {
8443 constructor: {
8444 value: ctor,
8445 enumerable: false,
8446 writable: true,
8447 configurable: true
8448 }
8449 });
8450 };
8451} else {
8452 // old school shim for old browsers
8453 module.exports = function inherits(ctor, superCtor) {
8454 ctor.super_ = superCtor;
8455 var TempCtor = function () {};
8456 TempCtor.prototype = superCtor.prototype;
8457 ctor.prototype = new TempCtor();
8458 ctor.prototype.constructor = ctor;
8459 };
8460}
8461});
8462
8463var inherits_1 = inherits_browser;
8464
8465function toArray(msg, enc) {
8466 if (Array.isArray(msg))
8467 return msg.slice();
8468 if (!msg)
8469 return [];
8470 var res = [];
8471 if (typeof msg === 'string') {
8472 if (!enc) {
8473 for (var i = 0; i < msg.length; i++) {
8474 var c = msg.charCodeAt(i);
8475 var hi = c >> 8;
8476 var lo = c & 0xff;
8477 if (hi)
8478 res.push(hi, lo);
8479 else
8480 res.push(lo);
8481 }
8482 } else if (enc === 'hex') {
8483 msg = msg.replace(/[^a-z0-9]+/ig, '');
8484 if (msg.length % 2 !== 0)
8485 msg = '0' + msg;
8486 for (i = 0; i < msg.length; i += 2)
8487 res.push(parseInt(msg[i] + msg[i + 1], 16));
8488 }
8489 } else {
8490 for (i = 0; i < msg.length; i++)
8491 res[i] = msg[i] | 0;
8492 }
8493 return res;
8494}
8495var toArray_1 = toArray;
8496
8497function toHex(msg) {
8498 var res = '';
8499 for (var i = 0; i < msg.length; i++)
8500 res += zero2(msg[i].toString(16));
8501 return res;
8502}
8503var toHex_1 = toHex;
8504
8505function htonl(w) {
8506 var res = (w >>> 24) |
8507 ((w >>> 8) & 0xff00) |
8508 ((w << 8) & 0xff0000) |
8509 ((w & 0xff) << 24);
8510 return res >>> 0;
8511}
8512var htonl_1 = htonl;
8513
8514function toHex32(msg, endian) {
8515 var res = '';
8516 for (var i = 0; i < msg.length; i++) {
8517 var w = msg[i];
8518 if (endian === 'little')
8519 w = htonl(w);
8520 res += zero8(w.toString(16));
8521 }
8522 return res;
8523}
8524var toHex32_1 = toHex32;
8525
8526function zero2(word) {
8527 if (word.length === 1)
8528 return '0' + word;
8529 else
8530 return word;
8531}
8532var zero2_1 = zero2;
8533
8534function zero8(word) {
8535 if (word.length === 7)
8536 return '0' + word;
8537 else if (word.length === 6)
8538 return '00' + word;
8539 else if (word.length === 5)
8540 return '000' + word;
8541 else if (word.length === 4)
8542 return '0000' + word;
8543 else if (word.length === 3)
8544 return '00000' + word;
8545 else if (word.length === 2)
8546 return '000000' + word;
8547 else if (word.length === 1)
8548 return '0000000' + word;
8549 else
8550 return word;
8551}
8552var zero8_1 = zero8;
8553
8554function join32(msg, start, end, endian) {
8555 var len = end - start;
8556 minimalisticAssert(len % 4 === 0);
8557 var res = new Array(len / 4);
8558 for (var i = 0, k = start; i < res.length; i++, k += 4) {
8559 var w;
8560 if (endian === 'big')
8561 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
8562 else
8563 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
8564 res[i] = w >>> 0;
8565 }
8566 return res;
8567}
8568var join32_1 = join32;
8569
8570function split32(msg, endian) {
8571 var res = new Array(msg.length * 4);
8572 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
8573 var m = msg[i];
8574 if (endian === 'big') {
8575 res[k] = m >>> 24;
8576 res[k + 1] = (m >>> 16) & 0xff;
8577 res[k + 2] = (m >>> 8) & 0xff;
8578 res[k + 3] = m & 0xff;
8579 } else {
8580 res[k + 3] = m >>> 24;
8581 res[k + 2] = (m >>> 16) & 0xff;
8582 res[k + 1] = (m >>> 8) & 0xff;
8583 res[k] = m & 0xff;
8584 }
8585 }
8586 return res;
8587}
8588var split32_1 = split32;
8589
8590function rotr32(w, b) {
8591 return (w >>> b) | (w << (32 - b));
8592}
8593var rotr32_1 = rotr32;
8594
8595function rotl32(w, b) {
8596 return (w << b) | (w >>> (32 - b));
8597}
8598var rotl32_1 = rotl32;
8599
8600function sum32(a, b) {
8601 return (a + b) >>> 0;
8602}
8603var sum32_1 = sum32;
8604
8605function sum32_3(a, b, c) {
8606 return (a + b + c) >>> 0;
8607}
8608var sum32_3_1 = sum32_3;
8609
8610function sum32_4(a, b, c, d) {
8611 return (a + b + c + d) >>> 0;
8612}
8613var sum32_4_1 = sum32_4;
8614
8615function sum32_5(a, b, c, d, e) {
8616 return (a + b + c + d + e) >>> 0;
8617}
8618var sum32_5_1 = sum32_5;
8619
8620function sum64(buf, pos, ah, al) {
8621 var bh = buf[pos];
8622 var bl = buf[pos + 1];
8623
8624 var lo = (al + bl) >>> 0;
8625 var hi = (lo < al ? 1 : 0) + ah + bh;
8626 buf[pos] = hi >>> 0;
8627 buf[pos + 1] = lo;
8628}
8629var sum64_1 = sum64;
8630
8631function sum64_hi(ah, al, bh, bl) {
8632 var lo = (al + bl) >>> 0;
8633 var hi = (lo < al ? 1 : 0) + ah + bh;
8634 return hi >>> 0;
8635}
8636var sum64_hi_1 = sum64_hi;
8637
8638function sum64_lo(ah, al, bh, bl) {
8639 var lo = al + bl;
8640 return lo >>> 0;
8641}
8642var sum64_lo_1 = sum64_lo;
8643
8644function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
8645 var carry = 0;
8646 var lo = al;
8647 lo = (lo + bl) >>> 0;
8648 carry += lo < al ? 1 : 0;
8649 lo = (lo + cl) >>> 0;
8650 carry += lo < cl ? 1 : 0;
8651 lo = (lo + dl) >>> 0;
8652 carry += lo < dl ? 1 : 0;
8653
8654 var hi = ah + bh + ch + dh + carry;
8655 return hi >>> 0;
8656}
8657var sum64_4_hi_1 = sum64_4_hi;
8658
8659function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
8660 var lo = al + bl + cl + dl;
8661 return lo >>> 0;
8662}
8663var sum64_4_lo_1 = sum64_4_lo;
8664
8665function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
8666 var carry = 0;
8667 var lo = al;
8668 lo = (lo + bl) >>> 0;
8669 carry += lo < al ? 1 : 0;
8670 lo = (lo + cl) >>> 0;
8671 carry += lo < cl ? 1 : 0;
8672 lo = (lo + dl) >>> 0;
8673 carry += lo < dl ? 1 : 0;
8674 lo = (lo + el) >>> 0;
8675 carry += lo < el ? 1 : 0;
8676
8677 var hi = ah + bh + ch + dh + eh + carry;
8678 return hi >>> 0;
8679}
8680var sum64_5_hi_1 = sum64_5_hi;
8681
8682function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
8683 var lo = al + bl + cl + dl + el;
8684
8685 return lo >>> 0;
8686}
8687var sum64_5_lo_1 = sum64_5_lo;
8688
8689function rotr64_hi(ah, al, num) {
8690 var r = (al << (32 - num)) | (ah >>> num);
8691 return r >>> 0;
8692}
8693var rotr64_hi_1 = rotr64_hi;
8694
8695function rotr64_lo(ah, al, num) {
8696 var r = (ah << (32 - num)) | (al >>> num);
8697 return r >>> 0;
8698}
8699var rotr64_lo_1 = rotr64_lo;
8700
8701function shr64_hi(ah, al, num) {
8702 return ah >>> num;
8703}
8704var shr64_hi_1 = shr64_hi;
8705
8706function shr64_lo(ah, al, num) {
8707 var r = (ah << (32 - num)) | (al >>> num);
8708 return r >>> 0;
8709}
8710var shr64_lo_1 = shr64_lo;
8711
8712var utils = {
8713 inherits: inherits_1,
8714 toArray: toArray_1,
8715 toHex: toHex_1,
8716 htonl: htonl_1,
8717 toHex32: toHex32_1,
8718 zero2: zero2_1,
8719 zero8: zero8_1,
8720 join32: join32_1,
8721 split32: split32_1,
8722 rotr32: rotr32_1,
8723 rotl32: rotl32_1,
8724 sum32: sum32_1,
8725 sum32_3: sum32_3_1,
8726 sum32_4: sum32_4_1,
8727 sum32_5: sum32_5_1,
8728 sum64: sum64_1,
8729 sum64_hi: sum64_hi_1,
8730 sum64_lo: sum64_lo_1,
8731 sum64_4_hi: sum64_4_hi_1,
8732 sum64_4_lo: sum64_4_lo_1,
8733 sum64_5_hi: sum64_5_hi_1,
8734 sum64_5_lo: sum64_5_lo_1,
8735 rotr64_hi: rotr64_hi_1,
8736 rotr64_lo: rotr64_lo_1,
8737 shr64_hi: shr64_hi_1,
8738 shr64_lo: shr64_lo_1
8739};
8740
8741function BlockHash() {
8742 this.pending = null;
8743 this.pendingTotal = 0;
8744 this.blockSize = this.constructor.blockSize;
8745 this.outSize = this.constructor.outSize;
8746 this.hmacStrength = this.constructor.hmacStrength;
8747 this.padLength = this.constructor.padLength / 8;
8748 this.endian = 'big';
8749
8750 this._delta8 = this.blockSize / 8;
8751 this._delta32 = this.blockSize / 32;
8752}
8753var BlockHash_1 = BlockHash;
8754
8755BlockHash.prototype.update = function update(msg, enc) {
8756 // Convert message to array, pad it, and join into 32bit blocks
8757 msg = utils.toArray(msg, enc);
8758 if (!this.pending)
8759 this.pending = msg;
8760 else
8761 this.pending = this.pending.concat(msg);
8762 this.pendingTotal += msg.length;
8763
8764 // Enough data, try updating
8765 if (this.pending.length >= this._delta8) {
8766 msg = this.pending;
8767
8768 // Process pending data in blocks
8769 var r = msg.length % this._delta8;
8770 this.pending = msg.slice(msg.length - r, msg.length);
8771 if (this.pending.length === 0)
8772 this.pending = null;
8773
8774 msg = utils.join32(msg, 0, msg.length - r, this.endian);
8775 for (var i = 0; i < msg.length; i += this._delta32)
8776 this._update(msg, i, i + this._delta32);
8777 }
8778
8779 return this;
8780};
8781
8782BlockHash.prototype.digest = function digest(enc) {
8783 this.update(this._pad());
8784 minimalisticAssert(this.pending === null);
8785
8786 return this._digest(enc);
8787};
8788
8789BlockHash.prototype._pad = function pad() {
8790 var len = this.pendingTotal;
8791 var bytes = this._delta8;
8792 var k = bytes - ((len + this.padLength) % bytes);
8793 var res = new Array(k + this.padLength);
8794 res[0] = 0x80;
8795 for (var i = 1; i < k; i++)
8796 res[i] = 0;
8797
8798 // Append length
8799 len <<= 3;
8800 if (this.endian === 'big') {
8801 for (var t = 8; t < this.padLength; t++)
8802 res[i++] = 0;
8803
8804 res[i++] = 0;
8805 res[i++] = 0;
8806 res[i++] = 0;
8807 res[i++] = 0;
8808 res[i++] = (len >>> 24) & 0xff;
8809 res[i++] = (len >>> 16) & 0xff;
8810 res[i++] = (len >>> 8) & 0xff;
8811 res[i++] = len & 0xff;
8812 } else {
8813 res[i++] = len & 0xff;
8814 res[i++] = (len >>> 8) & 0xff;
8815 res[i++] = (len >>> 16) & 0xff;
8816 res[i++] = (len >>> 24) & 0xff;
8817 res[i++] = 0;
8818 res[i++] = 0;
8819 res[i++] = 0;
8820 res[i++] = 0;
8821
8822 for (t = 8; t < this.padLength; t++)
8823 res[i++] = 0;
8824 }
8825
8826 return res;
8827};
8828
8829var common = {
8830 BlockHash: BlockHash_1
8831};
8832
8833var rotr32$1 = utils.rotr32;
8834
8835function ft_1(s, x, y, z) {
8836 if (s === 0)
8837 return ch32(x, y, z);
8838 if (s === 1 || s === 3)
8839 return p32(x, y, z);
8840 if (s === 2)
8841 return maj32(x, y, z);
8842}
8843var ft_1_1 = ft_1;
8844
8845function ch32(x, y, z) {
8846 return (x & y) ^ ((~x) & z);
8847}
8848var ch32_1 = ch32;
8849
8850function maj32(x, y, z) {
8851 return (x & y) ^ (x & z) ^ (y & z);
8852}
8853var maj32_1 = maj32;
8854
8855function p32(x, y, z) {
8856 return x ^ y ^ z;
8857}
8858var p32_1 = p32;
8859
8860function s0_256(x) {
8861 return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22);
8862}
8863var s0_256_1 = s0_256;
8864
8865function s1_256(x) {
8866 return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25);
8867}
8868var s1_256_1 = s1_256;
8869
8870function g0_256(x) {
8871 return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3);
8872}
8873var g0_256_1 = g0_256;
8874
8875function g1_256(x) {
8876 return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10);
8877}
8878var g1_256_1 = g1_256;
8879
8880var common$1 = {
8881 ft_1: ft_1_1,
8882 ch32: ch32_1,
8883 maj32: maj32_1,
8884 p32: p32_1,
8885 s0_256: s0_256_1,
8886 s1_256: s1_256_1,
8887 g0_256: g0_256_1,
8888 g1_256: g1_256_1
8889};
8890
8891var sum32$1 = utils.sum32;
8892var sum32_4$1 = utils.sum32_4;
8893var sum32_5$1 = utils.sum32_5;
8894var ch32$1 = common$1.ch32;
8895var maj32$1 = common$1.maj32;
8896var s0_256$1 = common$1.s0_256;
8897var s1_256$1 = common$1.s1_256;
8898var g0_256$1 = common$1.g0_256;
8899var g1_256$1 = common$1.g1_256;
8900
8901var BlockHash$1 = common.BlockHash;
8902
8903var sha256_K = [
8904 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
8905 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
8906 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
8907 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
8908 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
8909 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
8910 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
8911 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
8912 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
8913 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
8914 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
8915 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
8916 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
8917 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
8918 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
8919 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
8920];
8921
8922function SHA256() {
8923 if (!(this instanceof SHA256))
8924 return new SHA256();
8925
8926 BlockHash$1.call(this);
8927 this.h = [
8928 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
8929 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
8930 ];
8931 this.k = sha256_K;
8932 this.W = new Array(64);
8933}
8934utils.inherits(SHA256, BlockHash$1);
8935var _256 = SHA256;
8936
8937SHA256.blockSize = 512;
8938SHA256.outSize = 256;
8939SHA256.hmacStrength = 192;
8940SHA256.padLength = 64;
8941
8942SHA256.prototype._update = function _update(msg, start) {
8943 var W = this.W;
8944
8945 for (var i = 0; i < 16; i++)
8946 W[i] = msg[start + i];
8947 for (; i < W.length; i++)
8948 W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]);
8949
8950 var a = this.h[0];
8951 var b = this.h[1];
8952 var c = this.h[2];
8953 var d = this.h[3];
8954 var e = this.h[4];
8955 var f = this.h[5];
8956 var g = this.h[6];
8957 var h = this.h[7];
8958
8959 minimalisticAssert(this.k.length === W.length);
8960 for (i = 0; i < W.length; i++) {
8961 var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]);
8962 var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c));
8963 h = g;
8964 g = f;
8965 f = e;
8966 e = sum32$1(d, T1);
8967 d = c;
8968 c = b;
8969 b = a;
8970 a = sum32$1(T1, T2);
8971 }
8972
8973 this.h[0] = sum32$1(this.h[0], a);
8974 this.h[1] = sum32$1(this.h[1], b);
8975 this.h[2] = sum32$1(this.h[2], c);
8976 this.h[3] = sum32$1(this.h[3], d);
8977 this.h[4] = sum32$1(this.h[4], e);
8978 this.h[5] = sum32$1(this.h[5], f);
8979 this.h[6] = sum32$1(this.h[6], g);
8980 this.h[7] = sum32$1(this.h[7], h);
8981};
8982
8983SHA256.prototype._digest = function digest(enc) {
8984 if (enc === 'hex')
8985 return utils.toHex32(this.h, 'big');
8986 else
8987 return utils.split32(this.h, 'big');
8988};
8989
8990function SHA224() {
8991 if (!(this instanceof SHA224))
8992 return new SHA224();
8993
8994 _256.call(this);
8995 this.h = [
8996 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
8997 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
8998}
8999utils.inherits(SHA224, _256);
9000var _224 = SHA224;
9001
9002SHA224.blockSize = 512;
9003SHA224.outSize = 224;
9004SHA224.hmacStrength = 192;
9005SHA224.padLength = 64;
9006
9007SHA224.prototype._digest = function digest(enc) {
9008 // Just truncate output
9009 if (enc === 'hex')
9010 return utils.toHex32(this.h.slice(0, 7), 'big');
9011 else
9012 return utils.split32(this.h.slice(0, 7), 'big');
9013};
9014
9015var rotr64_hi$1 = utils.rotr64_hi;
9016var rotr64_lo$1 = utils.rotr64_lo;
9017var shr64_hi$1 = utils.shr64_hi;
9018var shr64_lo$1 = utils.shr64_lo;
9019var sum64$1 = utils.sum64;
9020var sum64_hi$1 = utils.sum64_hi;
9021var sum64_lo$1 = utils.sum64_lo;
9022var sum64_4_hi$1 = utils.sum64_4_hi;
9023var sum64_4_lo$1 = utils.sum64_4_lo;
9024var sum64_5_hi$1 = utils.sum64_5_hi;
9025var sum64_5_lo$1 = utils.sum64_5_lo;
9026
9027var BlockHash$2 = common.BlockHash;
9028
9029var sha512_K = [
9030 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
9031 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
9032 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
9033 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
9034 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
9035 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
9036 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
9037 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
9038 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
9039 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
9040 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
9041 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
9042 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
9043 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
9044 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
9045 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
9046 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
9047 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
9048 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
9049 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
9050 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
9051 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
9052 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
9053 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
9054 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
9055 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
9056 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
9057 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
9058 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
9059 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
9060 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
9061 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
9062 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
9063 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
9064 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
9065 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
9066 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
9067 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
9068 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
9069 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
9070];
9071
9072function SHA512() {
9073 if (!(this instanceof SHA512))
9074 return new SHA512();
9075
9076 BlockHash$2.call(this);
9077 this.h = [
9078 0x6a09e667, 0xf3bcc908,
9079 0xbb67ae85, 0x84caa73b,
9080 0x3c6ef372, 0xfe94f82b,
9081 0xa54ff53a, 0x5f1d36f1,
9082 0x510e527f, 0xade682d1,
9083 0x9b05688c, 0x2b3e6c1f,
9084 0x1f83d9ab, 0xfb41bd6b,
9085 0x5be0cd19, 0x137e2179 ];
9086 this.k = sha512_K;
9087 this.W = new Array(160);
9088}
9089utils.inherits(SHA512, BlockHash$2);
9090var _512 = SHA512;
9091
9092SHA512.blockSize = 1024;
9093SHA512.outSize = 512;
9094SHA512.hmacStrength = 192;
9095SHA512.padLength = 128;
9096
9097SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
9098 var W = this.W;
9099
9100 // 32 x 32bit words
9101 for (var i = 0; i < 32; i++)
9102 W[i] = msg[start + i];
9103 for (; i < W.length; i += 2) {
9104 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
9105 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
9106 var c1_hi = W[i - 14]; // i - 7
9107 var c1_lo = W[i - 13];
9108 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
9109 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
9110 var c3_hi = W[i - 32]; // i - 16
9111 var c3_lo = W[i - 31];
9112
9113 W[i] = sum64_4_hi$1(
9114 c0_hi, c0_lo,
9115 c1_hi, c1_lo,
9116 c2_hi, c2_lo,
9117 c3_hi, c3_lo);
9118 W[i + 1] = sum64_4_lo$1(
9119 c0_hi, c0_lo,
9120 c1_hi, c1_lo,
9121 c2_hi, c2_lo,
9122 c3_hi, c3_lo);
9123 }
9124};
9125
9126SHA512.prototype._update = function _update(msg, start) {
9127 this._prepareBlock(msg, start);
9128
9129 var W = this.W;
9130
9131 var ah = this.h[0];
9132 var al = this.h[1];
9133 var bh = this.h[2];
9134 var bl = this.h[3];
9135 var ch = this.h[4];
9136 var cl = this.h[5];
9137 var dh = this.h[6];
9138 var dl = this.h[7];
9139 var eh = this.h[8];
9140 var el = this.h[9];
9141 var fh = this.h[10];
9142 var fl = this.h[11];
9143 var gh = this.h[12];
9144 var gl = this.h[13];
9145 var hh = this.h[14];
9146 var hl = this.h[15];
9147
9148 minimalisticAssert(this.k.length === W.length);
9149 for (var i = 0; i < W.length; i += 2) {
9150 var c0_hi = hh;
9151 var c0_lo = hl;
9152 var c1_hi = s1_512_hi(eh, el);
9153 var c1_lo = s1_512_lo(eh, el);
9154 var c2_hi = ch64_hi(eh, el, fh, fl, gh);
9155 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
9156 var c3_hi = this.k[i];
9157 var c3_lo = this.k[i + 1];
9158 var c4_hi = W[i];
9159 var c4_lo = W[i + 1];
9160
9161 var T1_hi = sum64_5_hi$1(
9162 c0_hi, c0_lo,
9163 c1_hi, c1_lo,
9164 c2_hi, c2_lo,
9165 c3_hi, c3_lo,
9166 c4_hi, c4_lo);
9167 var T1_lo = sum64_5_lo$1(
9168 c0_hi, c0_lo,
9169 c1_hi, c1_lo,
9170 c2_hi, c2_lo,
9171 c3_hi, c3_lo,
9172 c4_hi, c4_lo);
9173
9174 c0_hi = s0_512_hi(ah, al);
9175 c0_lo = s0_512_lo(ah, al);
9176 c1_hi = maj64_hi(ah, al, bh, bl, ch);
9177 c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
9178
9179 var T2_hi = sum64_hi$1(c0_hi, c0_lo, c1_hi, c1_lo);
9180 var T2_lo = sum64_lo$1(c0_hi, c0_lo, c1_hi, c1_lo);
9181
9182 hh = gh;
9183 hl = gl;
9184
9185 gh = fh;
9186 gl = fl;
9187
9188 fh = eh;
9189 fl = el;
9190
9191 eh = sum64_hi$1(dh, dl, T1_hi, T1_lo);
9192 el = sum64_lo$1(dl, dl, T1_hi, T1_lo);
9193
9194 dh = ch;
9195 dl = cl;
9196
9197 ch = bh;
9198 cl = bl;
9199
9200 bh = ah;
9201 bl = al;
9202
9203 ah = sum64_hi$1(T1_hi, T1_lo, T2_hi, T2_lo);
9204 al = sum64_lo$1(T1_hi, T1_lo, T2_hi, T2_lo);
9205 }
9206
9207 sum64$1(this.h, 0, ah, al);
9208 sum64$1(this.h, 2, bh, bl);
9209 sum64$1(this.h, 4, ch, cl);
9210 sum64$1(this.h, 6, dh, dl);
9211 sum64$1(this.h, 8, eh, el);
9212 sum64$1(this.h, 10, fh, fl);
9213 sum64$1(this.h, 12, gh, gl);
9214 sum64$1(this.h, 14, hh, hl);
9215};
9216
9217SHA512.prototype._digest = function digest(enc) {
9218 if (enc === 'hex')
9219 return utils.toHex32(this.h, 'big');
9220 else
9221 return utils.split32(this.h, 'big');
9222};
9223
9224function ch64_hi(xh, xl, yh, yl, zh) {
9225 var r = (xh & yh) ^ ((~xh) & zh);
9226 if (r < 0)
9227 r += 0x100000000;
9228 return r;
9229}
9230
9231function ch64_lo(xh, xl, yh, yl, zh, zl) {
9232 var r = (xl & yl) ^ ((~xl) & zl);
9233 if (r < 0)
9234 r += 0x100000000;
9235 return r;
9236}
9237
9238function maj64_hi(xh, xl, yh, yl, zh) {
9239 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
9240 if (r < 0)
9241 r += 0x100000000;
9242 return r;
9243}
9244
9245function maj64_lo(xh, xl, yh, yl, zh, zl) {
9246 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
9247 if (r < 0)
9248 r += 0x100000000;
9249 return r;
9250}
9251
9252function s0_512_hi(xh, xl) {
9253 var c0_hi = rotr64_hi$1(xh, xl, 28);
9254 var c1_hi = rotr64_hi$1(xl, xh, 2); // 34
9255 var c2_hi = rotr64_hi$1(xl, xh, 7); // 39
9256
9257 var r = c0_hi ^ c1_hi ^ c2_hi;
9258 if (r < 0)
9259 r += 0x100000000;
9260 return r;
9261}
9262
9263function s0_512_lo(xh, xl) {
9264 var c0_lo = rotr64_lo$1(xh, xl, 28);
9265 var c1_lo = rotr64_lo$1(xl, xh, 2); // 34
9266 var c2_lo = rotr64_lo$1(xl, xh, 7); // 39
9267
9268 var r = c0_lo ^ c1_lo ^ c2_lo;
9269 if (r < 0)
9270 r += 0x100000000;
9271 return r;
9272}
9273
9274function s1_512_hi(xh, xl) {
9275 var c0_hi = rotr64_hi$1(xh, xl, 14);
9276 var c1_hi = rotr64_hi$1(xh, xl, 18);
9277 var c2_hi = rotr64_hi$1(xl, xh, 9); // 41
9278
9279 var r = c0_hi ^ c1_hi ^ c2_hi;
9280 if (r < 0)
9281 r += 0x100000000;
9282 return r;
9283}
9284
9285function s1_512_lo(xh, xl) {
9286 var c0_lo = rotr64_lo$1(xh, xl, 14);
9287 var c1_lo = rotr64_lo$1(xh, xl, 18);
9288 var c2_lo = rotr64_lo$1(xl, xh, 9); // 41
9289
9290 var r = c0_lo ^ c1_lo ^ c2_lo;
9291 if (r < 0)
9292 r += 0x100000000;
9293 return r;
9294}
9295
9296function g0_512_hi(xh, xl) {
9297 var c0_hi = rotr64_hi$1(xh, xl, 1);
9298 var c1_hi = rotr64_hi$1(xh, xl, 8);
9299 var c2_hi = shr64_hi$1(xh, xl, 7);
9300
9301 var r = c0_hi ^ c1_hi ^ c2_hi;
9302 if (r < 0)
9303 r += 0x100000000;
9304 return r;
9305}
9306
9307function g0_512_lo(xh, xl) {
9308 var c0_lo = rotr64_lo$1(xh, xl, 1);
9309 var c1_lo = rotr64_lo$1(xh, xl, 8);
9310 var c2_lo = shr64_lo$1(xh, xl, 7);
9311
9312 var r = c0_lo ^ c1_lo ^ c2_lo;
9313 if (r < 0)
9314 r += 0x100000000;
9315 return r;
9316}
9317
9318function g1_512_hi(xh, xl) {
9319 var c0_hi = rotr64_hi$1(xh, xl, 19);
9320 var c1_hi = rotr64_hi$1(xl, xh, 29); // 61
9321 var c2_hi = shr64_hi$1(xh, xl, 6);
9322
9323 var r = c0_hi ^ c1_hi ^ c2_hi;
9324 if (r < 0)
9325 r += 0x100000000;
9326 return r;
9327}
9328
9329function g1_512_lo(xh, xl) {
9330 var c0_lo = rotr64_lo$1(xh, xl, 19);
9331 var c1_lo = rotr64_lo$1(xl, xh, 29); // 61
9332 var c2_lo = shr64_lo$1(xh, xl, 6);
9333
9334 var r = c0_lo ^ c1_lo ^ c2_lo;
9335 if (r < 0)
9336 r += 0x100000000;
9337 return r;
9338}
9339
9340function SHA384() {
9341 if (!(this instanceof SHA384))
9342 return new SHA384();
9343
9344 _512.call(this);
9345 this.h = [
9346 0xcbbb9d5d, 0xc1059ed8,
9347 0x629a292a, 0x367cd507,
9348 0x9159015a, 0x3070dd17,
9349 0x152fecd8, 0xf70e5939,
9350 0x67332667, 0xffc00b31,
9351 0x8eb44a87, 0x68581511,
9352 0xdb0c2e0d, 0x64f98fa7,
9353 0x47b5481d, 0xbefa4fa4 ];
9354}
9355utils.inherits(SHA384, _512);
9356var _384 = SHA384;
9357
9358SHA384.blockSize = 1024;
9359SHA384.outSize = 384;
9360SHA384.hmacStrength = 192;
9361SHA384.padLength = 128;
9362
9363SHA384.prototype._digest = function digest(enc) {
9364 if (enc === 'hex')
9365 return utils.toHex32(this.h.slice(0, 12), 'big');
9366 else
9367 return utils.split32(this.h.slice(0, 12), 'big');
9368};
9369
9370var rotl32$1 = utils.rotl32;
9371var sum32$2 = utils.sum32;
9372var sum32_3$1 = utils.sum32_3;
9373var sum32_4$2 = utils.sum32_4;
9374var BlockHash$3 = common.BlockHash;
9375
9376function RIPEMD160() {
9377 if (!(this instanceof RIPEMD160))
9378 return new RIPEMD160();
9379
9380 BlockHash$3.call(this);
9381
9382 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
9383 this.endian = 'little';
9384}
9385utils.inherits(RIPEMD160, BlockHash$3);
9386var ripemd160 = RIPEMD160;
9387
9388RIPEMD160.blockSize = 512;
9389RIPEMD160.outSize = 160;
9390RIPEMD160.hmacStrength = 192;
9391RIPEMD160.padLength = 64;
9392
9393RIPEMD160.prototype._update = function update(msg, start) {
9394 var A = this.h[0];
9395 var B = this.h[1];
9396 var C = this.h[2];
9397 var D = this.h[3];
9398 var E = this.h[4];
9399 var Ah = A;
9400 var Bh = B;
9401 var Ch = C;
9402 var Dh = D;
9403 var Eh = E;
9404 for (var j = 0; j < 80; j++) {
9405 var T = sum32$2(
9406 rotl32$1(
9407 sum32_4$2(A, f(j, B, C, D), msg[r[j] + start], K(j)),
9408 s[j]),
9409 E);
9410 A = E;
9411 E = D;
9412 D = rotl32$1(C, 10);
9413 C = B;
9414 B = T;
9415 T = sum32$2(
9416 rotl32$1(
9417 sum32_4$2(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
9418 sh[j]),
9419 Eh);
9420 Ah = Eh;
9421 Eh = Dh;
9422 Dh = rotl32$1(Ch, 10);
9423 Ch = Bh;
9424 Bh = T;
9425 }
9426 T = sum32_3$1(this.h[1], C, Dh);
9427 this.h[1] = sum32_3$1(this.h[2], D, Eh);
9428 this.h[2] = sum32_3$1(this.h[3], E, Ah);
9429 this.h[3] = sum32_3$1(this.h[4], A, Bh);
9430 this.h[4] = sum32_3$1(this.h[0], B, Ch);
9431 this.h[0] = T;
9432};
9433
9434RIPEMD160.prototype._digest = function digest(enc) {
9435 if (enc === 'hex')
9436 return utils.toHex32(this.h, 'little');
9437 else
9438 return utils.split32(this.h, 'little');
9439};
9440
9441function f(j, x, y, z) {
9442 if (j <= 15)
9443 return x ^ y ^ z;
9444 else if (j <= 31)
9445 return (x & y) | ((~x) & z);
9446 else if (j <= 47)
9447 return (x | (~y)) ^ z;
9448 else if (j <= 63)
9449 return (x & z) | (y & (~z));
9450 else
9451 return x ^ (y | (~z));
9452}
9453
9454function K(j) {
9455 if (j <= 15)
9456 return 0x00000000;
9457 else if (j <= 31)
9458 return 0x5a827999;
9459 else if (j <= 47)
9460 return 0x6ed9eba1;
9461 else if (j <= 63)
9462 return 0x8f1bbcdc;
9463 else
9464 return 0xa953fd4e;
9465}
9466
9467function Kh(j) {
9468 if (j <= 15)
9469 return 0x50a28be6;
9470 else if (j <= 31)
9471 return 0x5c4dd124;
9472 else if (j <= 47)
9473 return 0x6d703ef3;
9474 else if (j <= 63)
9475 return 0x7a6d76e9;
9476 else
9477 return 0x00000000;
9478}
9479
9480var r = [
9481 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
9482 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
9483 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
9484 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
9485 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
9486];
9487
9488var rh = [
9489 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
9490 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
9491 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
9492 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
9493 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
9494];
9495
9496var s = [
9497 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
9498 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
9499 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
9500 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9501 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
9502];
9503
9504var sh = [
9505 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9506 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9507 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
9508 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
9509 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
9510];
9511
9512var ripemd = {
9513 ripemd160: ripemd160
9514};
9515
9516/**
9517 * A fast MD5 JavaScript implementation
9518 * Copyright (c) 2012 Joseph Myers
9519 * http://www.myersdaily.org/joseph/javascript/md5-text.html
9520 *
9521 * Permission to use, copy, modify, and distribute this software
9522 * and its documentation for any purposes and without
9523 * fee is hereby granted provided that this copyright notice
9524 * appears in all copies.
9525 *
9526 * Of course, this soft is provided "as is" without express or implied
9527 * warranty of any kind.
9528 */
9529
9530// MD5 Digest
9531async function md5(entree) {
9532 const digest = md51(util.uint8ArrayToString(entree));
9533 return util.hexToUint8Array(hex(digest));
9534}
9535
9536function md5cycle(x, k) {
9537 let a = x[0];
9538 let b = x[1];
9539 let c = x[2];
9540 let d = x[3];
9541
9542 a = ff(a, b, c, d, k[0], 7, -680876936);
9543 d = ff(d, a, b, c, k[1], 12, -389564586);
9544 c = ff(c, d, a, b, k[2], 17, 606105819);
9545 b = ff(b, c, d, a, k[3], 22, -1044525330);
9546 a = ff(a, b, c, d, k[4], 7, -176418897);
9547 d = ff(d, a, b, c, k[5], 12, 1200080426);
9548 c = ff(c, d, a, b, k[6], 17, -1473231341);
9549 b = ff(b, c, d, a, k[7], 22, -45705983);
9550 a = ff(a, b, c, d, k[8], 7, 1770035416);
9551 d = ff(d, a, b, c, k[9], 12, -1958414417);
9552 c = ff(c, d, a, b, k[10], 17, -42063);
9553 b = ff(b, c, d, a, k[11], 22, -1990404162);
9554 a = ff(a, b, c, d, k[12], 7, 1804603682);
9555 d = ff(d, a, b, c, k[13], 12, -40341101);
9556 c = ff(c, d, a, b, k[14], 17, -1502002290);
9557 b = ff(b, c, d, a, k[15], 22, 1236535329);
9558
9559 a = gg(a, b, c, d, k[1], 5, -165796510);
9560 d = gg(d, a, b, c, k[6], 9, -1069501632);
9561 c = gg(c, d, a, b, k[11], 14, 643717713);
9562 b = gg(b, c, d, a, k[0], 20, -373897302);
9563 a = gg(a, b, c, d, k[5], 5, -701558691);
9564 d = gg(d, a, b, c, k[10], 9, 38016083);
9565 c = gg(c, d, a, b, k[15], 14, -660478335);
9566 b = gg(b, c, d, a, k[4], 20, -405537848);
9567 a = gg(a, b, c, d, k[9], 5, 568446438);
9568 d = gg(d, a, b, c, k[14], 9, -1019803690);
9569 c = gg(c, d, a, b, k[3], 14, -187363961);
9570 b = gg(b, c, d, a, k[8], 20, 1163531501);
9571 a = gg(a, b, c, d, k[13], 5, -1444681467);
9572 d = gg(d, a, b, c, k[2], 9, -51403784);
9573 c = gg(c, d, a, b, k[7], 14, 1735328473);
9574 b = gg(b, c, d, a, k[12], 20, -1926607734);
9575
9576 a = hh(a, b, c, d, k[5], 4, -378558);
9577 d = hh(d, a, b, c, k[8], 11, -2022574463);
9578 c = hh(c, d, a, b, k[11], 16, 1839030562);
9579 b = hh(b, c, d, a, k[14], 23, -35309556);
9580 a = hh(a, b, c, d, k[1], 4, -1530992060);
9581 d = hh(d, a, b, c, k[4], 11, 1272893353);
9582 c = hh(c, d, a, b, k[7], 16, -155497632);
9583 b = hh(b, c, d, a, k[10], 23, -1094730640);
9584 a = hh(a, b, c, d, k[13], 4, 681279174);
9585 d = hh(d, a, b, c, k[0], 11, -358537222);
9586 c = hh(c, d, a, b, k[3], 16, -722521979);
9587 b = hh(b, c, d, a, k[6], 23, 76029189);
9588 a = hh(a, b, c, d, k[9], 4, -640364487);
9589 d = hh(d, a, b, c, k[12], 11, -421815835);
9590 c = hh(c, d, a, b, k[15], 16, 530742520);
9591 b = hh(b, c, d, a, k[2], 23, -995338651);
9592
9593 a = ii(a, b, c, d, k[0], 6, -198630844);
9594 d = ii(d, a, b, c, k[7], 10, 1126891415);
9595 c = ii(c, d, a, b, k[14], 15, -1416354905);
9596 b = ii(b, c, d, a, k[5], 21, -57434055);
9597 a = ii(a, b, c, d, k[12], 6, 1700485571);
9598 d = ii(d, a, b, c, k[3], 10, -1894986606);
9599 c = ii(c, d, a, b, k[10], 15, -1051523);
9600 b = ii(b, c, d, a, k[1], 21, -2054922799);
9601 a = ii(a, b, c, d, k[8], 6, 1873313359);
9602 d = ii(d, a, b, c, k[15], 10, -30611744);
9603 c = ii(c, d, a, b, k[6], 15, -1560198380);
9604 b = ii(b, c, d, a, k[13], 21, 1309151649);
9605 a = ii(a, b, c, d, k[4], 6, -145523070);
9606 d = ii(d, a, b, c, k[11], 10, -1120210379);
9607 c = ii(c, d, a, b, k[2], 15, 718787259);
9608 b = ii(b, c, d, a, k[9], 21, -343485551);
9609
9610 x[0] = add32(a, x[0]);
9611 x[1] = add32(b, x[1]);
9612 x[2] = add32(c, x[2]);
9613 x[3] = add32(d, x[3]);
9614}
9615
9616function cmn(q, a, b, x, s, t) {
9617 a = add32(add32(a, q), add32(x, t));
9618 return add32((a << s) | (a >>> (32 - s)), b);
9619}
9620
9621function ff(a, b, c, d, x, s, t) {
9622 return cmn((b & c) | ((~b) & d), a, b, x, s, t);
9623}
9624
9625function gg(a, b, c, d, x, s, t) {
9626 return cmn((b & d) | (c & (~d)), a, b, x, s, t);
9627}
9628
9629function hh(a, b, c, d, x, s, t) {
9630 return cmn(b ^ c ^ d, a, b, x, s, t);
9631}
9632
9633function ii(a, b, c, d, x, s, t) {
9634 return cmn(c ^ (b | (~d)), a, b, x, s, t);
9635}
9636
9637function md51(s) {
9638 const n = s.length;
9639 const state = [1732584193, -271733879, -1732584194, 271733878];
9640 let i;
9641 for (i = 64; i <= s.length; i += 64) {
9642 md5cycle(state, md5blk(s.substring(i - 64, i)));
9643 }
9644 s = s.substring(i - 64);
9645 const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
9646 for (i = 0; i < s.length; i++) {
9647 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
9648 }
9649 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
9650 if (i > 55) {
9651 md5cycle(state, tail);
9652 for (i = 0; i < 16; i++) {
9653 tail[i] = 0;
9654 }
9655 }
9656 tail[14] = n * 8;
9657 md5cycle(state, tail);
9658 return state;
9659}
9660
9661/* there needs to be support for Unicode here,
9662 * unless we pretend that we can redefine the MD-5
9663 * algorithm for multi-byte characters (perhaps
9664 * by adding every four 16-bit characters and
9665 * shortening the sum to 32 bits). Otherwise
9666 * I suggest performing MD-5 as if every character
9667 * was two bytes--e.g., 0040 0025 = @%--but then
9668 * how will an ordinary MD-5 sum be matched?
9669 * There is no way to standardize text to something
9670 * like UTF-8 before transformation; speed cost is
9671 * utterly prohibitive. The JavaScript standard
9672 * itself needs to look at this: it should start
9673 * providing access to strings as preformed UTF-8
9674 * 8-bit unsigned value arrays.
9675 */
9676function md5blk(s) { /* I figured global was faster. */
9677 const md5blks = [];
9678 let i; /* Andy King said do it this way. */
9679 for (i = 0; i < 64; i += 4) {
9680 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<
9681 24);
9682 }
9683 return md5blks;
9684}
9685
9686const hex_chr = '0123456789abcdef'.split('');
9687
9688function rhex(n) {
9689 let s = '';
9690 let j = 0;
9691 for (; j < 4; j++) {
9692 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
9693 }
9694 return s;
9695}
9696
9697function hex(x) {
9698 for (let i = 0; i < x.length; i++) {
9699 x[i] = rhex(x[i]);
9700 }
9701 return x.join('');
9702}
9703
9704/* this function is much faster,
9705so if possible we use it. Some IEs
9706are the only ones I know of that
9707need the idiotic second function,
9708generated by an if clause. */
9709
9710function add32(a, b) {
9711 return (a + b) & 0xFFFFFFFF;
9712}
9713
9714/**
9715 * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.
9716 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
9717 * @see {@link https://github.com/indutny/hash.js|hash.js}
9718 * @module crypto/hash
9719 * @private
9720 */
9721
9722const webCrypto = util.getWebCrypto();
9723const nodeCrypto = util.getNodeCrypto();
9724const nodeCryptoHashes = nodeCrypto && nodeCrypto.getHashes();
9725
9726function nodeHash(type) {
9727 if (!nodeCrypto || !nodeCryptoHashes.includes(type)) {
9728 return;
9729 }
9730 return async function (data) {
9731 const shasum = nodeCrypto.createHash(type);
9732 return transform(data, value => {
9733 shasum.update(value);
9734 }, () => new Uint8Array(shasum.digest()));
9735 };
9736}
9737
9738function hashjsHash(hash, webCryptoHash) {
9739 return async function(data, config$1 = config) {
9740 if (isArrayStream(data)) {
9741 data = await readToEnd(data);
9742 }
9743 if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config$1.minBytesForWebCrypto) {
9744 return new Uint8Array(await webCrypto.digest(webCryptoHash, data));
9745 }
9746 const hashInstance = hash();
9747 return transform(data, value => {
9748 hashInstance.update(value);
9749 }, () => new Uint8Array(hashInstance.digest()));
9750 };
9751}
9752
9753function asmcryptoHash(hash, webCryptoHash) {
9754 return async function(data, config$1 = config) {
9755 if (isArrayStream(data)) {
9756 data = await readToEnd(data);
9757 }
9758 if (util.isStream(data)) {
9759 const hashInstance = new hash();
9760 return transform(data, value => {
9761 hashInstance.process(value);
9762 }, () => hashInstance.finish().result);
9763 } else if (webCrypto && webCryptoHash && data.length >= config$1.minBytesForWebCrypto) {
9764 return new Uint8Array(await webCrypto.digest(webCryptoHash, data));
9765 } else {
9766 return hash.bytes(data);
9767 }
9768 };
9769}
9770
9771const hashFunctions = {
9772 md5: nodeHash('md5') || md5,
9773 sha1: nodeHash('sha1') || asmcryptoHash(Sha1, 'SHA-1'),
9774 sha224: nodeHash('sha224') || hashjsHash(_224),
9775 sha256: nodeHash('sha256') || asmcryptoHash(Sha256, 'SHA-256'),
9776 sha384: nodeHash('sha384') || hashjsHash(_384, 'SHA-384'),
9777 sha512: nodeHash('sha512') || hashjsHash(_512, 'SHA-512'), // asmcrypto sha512 is huge.
9778 ripemd: nodeHash('ripemd160') || hashjsHash(ripemd160)
9779};
9780
9781var hash = {
9782
9783 /** @see module:md5 */
9784 md5: hashFunctions.md5,
9785 /** @see asmCrypto */
9786 sha1: hashFunctions.sha1,
9787 /** @see hash.js */
9788 sha224: hashFunctions.sha224,
9789 /** @see asmCrypto */
9790 sha256: hashFunctions.sha256,
9791 /** @see hash.js */
9792 sha384: hashFunctions.sha384,
9793 /** @see asmCrypto */
9794 sha512: hashFunctions.sha512,
9795 /** @see hash.js */
9796 ripemd: hashFunctions.ripemd,
9797
9798 /**
9799 * Create a hash on the specified data using the specified algorithm
9800 * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
9801 * @param {Uint8Array} data - Data to be hashed
9802 * @returns {Promise<Uint8Array>} Hash value.
9803 */
9804 digest: function(algo, data) {
9805 switch (algo) {
9806 case enums.hash.md5:
9807 return this.md5(data);
9808 case enums.hash.sha1:
9809 return this.sha1(data);
9810 case enums.hash.ripemd:
9811 return this.ripemd(data);
9812 case enums.hash.sha256:
9813 return this.sha256(data);
9814 case enums.hash.sha384:
9815 return this.sha384(data);
9816 case enums.hash.sha512:
9817 return this.sha512(data);
9818 case enums.hash.sha224:
9819 return this.sha224(data);
9820 default:
9821 throw new Error('Invalid hash function.');
9822 }
9823 },
9824
9825 /**
9826 * Returns the hash size in bytes of the specified hash algorithm type
9827 * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
9828 * @returns {Integer} Size in bytes of the resulting hash.
9829 */
9830 getHashByteLength: function(algo) {
9831 switch (algo) {
9832 case enums.hash.md5:
9833 return 16;
9834 case enums.hash.sha1:
9835 case enums.hash.ripemd:
9836 return 20;
9837 case enums.hash.sha256:
9838 return 32;
9839 case enums.hash.sha384:
9840 return 48;
9841 case enums.hash.sha512:
9842 return 64;
9843 case enums.hash.sha224:
9844 return 28;
9845 default:
9846 throw new Error('Invalid hash algorithm.');
9847 }
9848 }
9849};
9850
9851class AES_CFB {
9852 static encrypt(data, key, iv) {
9853 return new AES_CFB(key, iv).encrypt(data);
9854 }
9855 static decrypt(data, key, iv) {
9856 return new AES_CFB(key, iv).decrypt(data);
9857 }
9858 constructor(key, iv, aes) {
9859 this.aes = aes ? aes : new AES(key, iv, true, 'CFB');
9860 delete this.aes.padding;
9861 }
9862 encrypt(data) {
9863 const r1 = this.aes.AES_Encrypt_process(data);
9864 const r2 = this.aes.AES_Encrypt_finish();
9865 return joinBytes(r1, r2);
9866 }
9867 decrypt(data) {
9868 const r1 = this.aes.AES_Decrypt_process(data);
9869 const r2 = this.aes.AES_Decrypt_finish();
9870 return joinBytes(r1, r2);
9871 }
9872}
9873
9874/**
9875 * Get implementation of the given cipher
9876 * @param {enums.symmetric} algo
9877 * @returns {Object}
9878 * @throws {Error} on invalid algo
9879 */
9880function getCipher(algo) {
9881 const algoName = enums.read(enums.symmetric, algo);
9882 return cipher[algoName];
9883}
9884
9885// Modified by ProtonTech AG
9886
9887const webCrypto$1 = util.getWebCrypto();
9888const nodeCrypto$1 = util.getNodeCrypto();
9889
9890const knownAlgos = nodeCrypto$1 ? nodeCrypto$1.getCiphers() : [];
9891const nodeAlgos = {
9892 idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */
9893 tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,
9894 cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,
9895 blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,
9896 aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,
9897 aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,
9898 aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined
9899 /* twofish is not implemented in OpenSSL */
9900};
9901
9902/**
9903 * CFB encryption
9904 * @param {enums.symmetric} algo - block cipher algorithm
9905 * @param {Uint8Array} key
9906 * @param {MaybeStream<Uint8Array>} plaintext
9907 * @param {Uint8Array} iv
9908 * @param {Object} config - full configuration, defaults to openpgp.config
9909 * @returns MaybeStream<Uint8Array>
9910 */
9911async function encrypt(algo, key, plaintext, iv, config) {
9912 const algoName = enums.read(enums.symmetric, algo);
9913 if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.
9914 return nodeEncrypt(algo, key, plaintext, iv);
9915 }
9916 if (util.isAES(algo)) {
9917 return aesEncrypt(algo, key, plaintext, iv, config);
9918 }
9919
9920 const Cipher = getCipher(algo);
9921 const cipherfn = new Cipher(key);
9922 const block_size = cipherfn.blockSize;
9923
9924 const blockc = iv.slice();
9925 let pt = new Uint8Array();
9926 const process = chunk => {
9927 if (chunk) {
9928 pt = util.concatUint8Array([pt, chunk]);
9929 }
9930 const ciphertext = new Uint8Array(pt.length);
9931 let i;
9932 let j = 0;
9933 while (chunk ? pt.length >= block_size : pt.length) {
9934 const encblock = cipherfn.encrypt(blockc);
9935 for (i = 0; i < block_size; i++) {
9936 blockc[i] = pt[i] ^ encblock[i];
9937 ciphertext[j++] = blockc[i];
9938 }
9939 pt = pt.subarray(block_size);
9940 }
9941 return ciphertext.subarray(0, j);
9942 };
9943 return transform(plaintext, process, process);
9944}
9945
9946/**
9947 * CFB decryption
9948 * @param {enums.symmetric} algo - block cipher algorithm
9949 * @param {Uint8Array} key
9950 * @param {MaybeStream<Uint8Array>} ciphertext
9951 * @param {Uint8Array} iv
9952 * @returns MaybeStream<Uint8Array>
9953 */
9954async function decrypt(algo, key, ciphertext, iv) {
9955 const algoName = enums.read(enums.symmetric, algo);
9956 if (util.getNodeCrypto() && nodeAlgos[algoName]) { // Node crypto library.
9957 return nodeDecrypt(algo, key, ciphertext, iv);
9958 }
9959 if (util.isAES(algo)) {
9960 return aesDecrypt(algo, key, ciphertext, iv);
9961 }
9962
9963 const Cipher = getCipher(algo);
9964 const cipherfn = new Cipher(key);
9965 const block_size = cipherfn.blockSize;
9966
9967 let blockp = iv;
9968 let ct = new Uint8Array();
9969 const process = chunk => {
9970 if (chunk) {
9971 ct = util.concatUint8Array([ct, chunk]);
9972 }
9973 const plaintext = new Uint8Array(ct.length);
9974 let i;
9975 let j = 0;
9976 while (chunk ? ct.length >= block_size : ct.length) {
9977 const decblock = cipherfn.encrypt(blockp);
9978 blockp = ct.subarray(0, block_size);
9979 for (i = 0; i < block_size; i++) {
9980 plaintext[j++] = blockp[i] ^ decblock[i];
9981 }
9982 ct = ct.subarray(block_size);
9983 }
9984 return plaintext.subarray(0, j);
9985 };
9986 return transform(ciphertext, process, process);
9987}
9988
9989function aesEncrypt(algo, key, pt, iv, config) {
9990 if (
9991 util.getWebCrypto() &&
9992 key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support
9993 !util.isStream(pt) &&
9994 pt.length >= 3000 * config.minBytesForWebCrypto // Default to a 3MB minimum. Chrome is pretty slow for small messages, see: https://bugs.chromium.org/p/chromium/issues/detail?id=701188#c2
9995 ) { // Web Crypto
9996 return webEncrypt(algo, key, pt, iv);
9997 }
9998 // asm.js fallback
9999 const cfb = new AES_CFB(key, iv);
10000 return transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish());
10001}
10002
10003function aesDecrypt(algo, key, ct, iv) {
10004 if (util.isStream(ct)) {
10005 const cfb = new AES_CFB(key, iv);
10006 return transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish());
10007 }
10008 return AES_CFB.decrypt(ct, key, iv);
10009}
10010
10011function xorMut(a, b) {
10012 for (let i = 0; i < a.length; i++) {
10013 a[i] = a[i] ^ b[i];
10014 }
10015}
10016
10017async function webEncrypt(algo, key, pt, iv) {
10018 const ALGO = 'AES-CBC';
10019 const _key = await webCrypto$1.importKey('raw', key, { name: ALGO }, false, ['encrypt']);
10020 const { blockSize } = getCipher(algo);
10021 const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]);
10022 const ct = new Uint8Array(await webCrypto$1.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length);
10023 xorMut(ct, pt);
10024 return ct;
10025}
10026
10027function nodeEncrypt(algo, key, pt, iv) {
10028 const algoName = enums.read(enums.symmetric, algo);
10029 const cipherObj = new nodeCrypto$1.createCipheriv(nodeAlgos[algoName], key, iv);
10030 return transform(pt, value => new Uint8Array(cipherObj.update(value)));
10031}
10032
10033function nodeDecrypt(algo, key, ct, iv) {
10034 const algoName = enums.read(enums.symmetric, algo);
10035 const decipherObj = new nodeCrypto$1.createDecipheriv(nodeAlgos[algoName], key, iv);
10036 return transform(ct, value => new Uint8Array(decipherObj.update(value)));
10037}
10038
10039var cfb = /*#__PURE__*/Object.freeze({
10040 __proto__: null,
10041 encrypt: encrypt,
10042 decrypt: decrypt
10043});
10044
10045class AES_CTR {
10046 static encrypt(data, key, nonce) {
10047 return new AES_CTR(key, nonce).encrypt(data);
10048 }
10049 static decrypt(data, key, nonce) {
10050 return new AES_CTR(key, nonce).encrypt(data);
10051 }
10052 constructor(key, nonce, aes) {
10053 this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');
10054 delete this.aes.padding;
10055 this.AES_CTR_set_options(nonce);
10056 }
10057 encrypt(data) {
10058 const r1 = this.aes.AES_Encrypt_process(data);
10059 const r2 = this.aes.AES_Encrypt_finish();
10060 return joinBytes(r1, r2);
10061 }
10062 decrypt(data) {
10063 const r1 = this.aes.AES_Encrypt_process(data);
10064 const r2 = this.aes.AES_Encrypt_finish();
10065 return joinBytes(r1, r2);
10066 }
10067 AES_CTR_set_options(nonce, counter, size) {
10068 let { asm } = this.aes.acquire_asm();
10069 if (size !== undefined) {
10070 if (size < 8 || size > 48)
10071 throw new IllegalArgumentError('illegal counter size');
10072 let mask = Math.pow(2, size) - 1;
10073 asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0);
10074 }
10075 else {
10076 size = 48;
10077 asm.set_mask(0, 0, 0xffff, 0xffffffff);
10078 }
10079 if (nonce !== undefined) {
10080 let len = nonce.length;
10081 if (!len || len > 16)
10082 throw new IllegalArgumentError('illegal nonce size');
10083 let view = new DataView(new ArrayBuffer(16));
10084 new Uint8Array(view.buffer).set(nonce);
10085 asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12));
10086 }
10087 else {
10088 throw new Error('nonce is required');
10089 }
10090 if (counter !== undefined) {
10091 if (counter < 0 || counter >= Math.pow(2, size))
10092 throw new IllegalArgumentError('illegal counter value');
10093 asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0);
10094 }
10095 }
10096}
10097
10098class AES_CBC {
10099 static encrypt(data, key, padding = true, iv) {
10100 return new AES_CBC(key, iv, padding).encrypt(data);
10101 }
10102 static decrypt(data, key, padding = true, iv) {
10103 return new AES_CBC(key, iv, padding).decrypt(data);
10104 }
10105 constructor(key, iv, padding = true, aes) {
10106 this.aes = aes ? aes : new AES(key, iv, padding, 'CBC');
10107 }
10108 encrypt(data) {
10109 const r1 = this.aes.AES_Encrypt_process(data);
10110 const r2 = this.aes.AES_Encrypt_finish();
10111 return joinBytes(r1, r2);
10112 }
10113 decrypt(data) {
10114 const r1 = this.aes.AES_Decrypt_process(data);
10115 const r2 = this.aes.AES_Decrypt_finish();
10116 return joinBytes(r1, r2);
10117 }
10118}
10119
10120/**
10121 * @fileoverview This module implements AES-CMAC on top of
10122 * native AES-CBC using either the WebCrypto API or Node.js' crypto API.
10123 * @module crypto/cmac
10124 * @private
10125 */
10126
10127const webCrypto$2 = util.getWebCrypto();
10128const nodeCrypto$2 = util.getNodeCrypto();
10129
10130
10131/**
10132 * This implementation of CMAC is based on the description of OMAC in
10133 * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that
10134 * document:
10135 *
10136 * We have made a small modification to the OMAC algorithm as it was
10137 * originally presented, changing one of its two constants.
10138 * Specifically, the constant 4 at line 85 was the constant 1/2 (the
10139 * multiplicative inverse of 2) in the original definition of OMAC [14].
10140 * The OMAC authors indicate that they will promulgate this modification
10141 * [15], which slightly simplifies implementations.
10142 */
10143
10144const blockLength = 16;
10145
10146
10147/**
10148 * xor `padding` into the end of `data`. This function implements "the
10149 * operation xor→ [which] xors the shorter string into the end of longer
10150 * one". Since data is always as least as long as padding, we can
10151 * simplify the implementation.
10152 * @param {Uint8Array} data
10153 * @param {Uint8Array} padding
10154 */
10155function rightXORMut(data, padding) {
10156 const offset = data.length - blockLength;
10157 for (let i = 0; i < blockLength; i++) {
10158 data[i + offset] ^= padding[i];
10159 }
10160 return data;
10161}
10162
10163function pad(data, padding, padding2) {
10164 // if |M| in {n, 2n, 3n, ...}
10165 if (data.length && data.length % blockLength === 0) {
10166 // then return M xor→ B,
10167 return rightXORMut(data, padding);
10168 }
10169 // else return (M || 10^(n−1−(|M| mod n))) xor→ P
10170 const padded = new Uint8Array(data.length + (blockLength - (data.length % blockLength)));
10171 padded.set(data);
10172 padded[data.length] = 0b10000000;
10173 return rightXORMut(padded, padding2);
10174}
10175
10176const zeroBlock = new Uint8Array(blockLength);
10177
10178async function CMAC(key) {
10179 const cbc = await CBC(key);
10180
10181 // L ← E_K(0^n); B ← 2L; P ← 4L
10182 const padding = util.double(await cbc(zeroBlock));
10183 const padding2 = util.double(padding);
10184
10185 return async function(data) {
10186 // return CBC_K(pad(M; B, P))
10187 return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);
10188 };
10189}
10190
10191async function CBC(key) {
10192 if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
10193 key = await webCrypto$2.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);
10194 return async function(pt) {
10195 const ct = await webCrypto$2.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);
10196 return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);
10197 };
10198 }
10199 if (util.getNodeCrypto()) { // Node crypto library
10200 return async function(pt) {
10201 const en = new nodeCrypto$2.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);
10202 const ct = en.update(pt);
10203 return new Uint8Array(ct);
10204 };
10205 }
10206 // asm.js fallback
10207 return async function(pt) {
10208 return AES_CBC.encrypt(pt, key, false, zeroBlock);
10209 };
10210}
10211
10212// OpenPGP.js - An OpenPGP implementation in javascript
10213
10214const webCrypto$3 = util.getWebCrypto();
10215const nodeCrypto$3 = util.getNodeCrypto();
10216const Buffer$1 = util.getNodeBuffer();
10217
10218
10219const blockLength$1 = 16;
10220const ivLength = blockLength$1;
10221const tagLength = blockLength$1;
10222
10223const zero = new Uint8Array(blockLength$1);
10224const one = new Uint8Array(blockLength$1); one[blockLength$1 - 1] = 1;
10225const two = new Uint8Array(blockLength$1); two[blockLength$1 - 1] = 2;
10226
10227async function OMAC(key) {
10228 const cmac = await CMAC(key);
10229 return function(t, message) {
10230 return cmac(util.concatUint8Array([t, message]));
10231 };
10232}
10233
10234async function CTR(key) {
10235 if (
10236 util.getWebCrypto() &&
10237 key.length !== 24 // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
10238 ) {
10239 key = await webCrypto$3.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);
10240 return async function(pt, iv) {
10241 const ct = await webCrypto$3.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$1 * 8 }, key, pt);
10242 return new Uint8Array(ct);
10243 };
10244 }
10245 if (util.getNodeCrypto()) { // Node crypto library
10246 return async function(pt, iv) {
10247 const en = new nodeCrypto$3.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);
10248 const ct = Buffer$1.concat([en.update(pt), en.final()]);
10249 return new Uint8Array(ct);
10250 };
10251 }
10252 // asm.js fallback
10253 return async function(pt, iv) {
10254 return AES_CTR.encrypt(pt, key, iv);
10255 };
10256}
10257
10258
10259/**
10260 * Class to en/decrypt using EAX mode.
10261 * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use
10262 * @param {Uint8Array} key - The encryption key
10263 */
10264async function EAX(cipher, key) {
10265 if (cipher !== enums.symmetric.aes128 &&
10266 cipher !== enums.symmetric.aes192 &&
10267 cipher !== enums.symmetric.aes256) {
10268 throw new Error('EAX mode supports only AES cipher');
10269 }
10270
10271 const [
10272 omac,
10273 ctr
10274 ] = await Promise.all([
10275 OMAC(key),
10276 CTR(key)
10277 ]);
10278
10279 return {
10280 /**
10281 * Encrypt plaintext input.
10282 * @param {Uint8Array} plaintext - The cleartext input to be encrypted
10283 * @param {Uint8Array} nonce - The nonce (16 bytes)
10284 * @param {Uint8Array} adata - Associated data to sign
10285 * @returns {Promise<Uint8Array>} The ciphertext output.
10286 */
10287 encrypt: async function(plaintext, nonce, adata) {
10288 const [
10289 omacNonce,
10290 omacAdata
10291 ] = await Promise.all([
10292 omac(zero, nonce),
10293 omac(one, adata)
10294 ]);
10295 const ciphered = await ctr(plaintext, omacNonce);
10296 const omacCiphered = await omac(two, ciphered);
10297 const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
10298 for (let i = 0; i < tagLength; i++) {
10299 tag[i] ^= omacAdata[i] ^ omacNonce[i];
10300 }
10301 return util.concatUint8Array([ciphered, tag]);
10302 },
10303
10304 /**
10305 * Decrypt ciphertext input.
10306 * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted
10307 * @param {Uint8Array} nonce - The nonce (16 bytes)
10308 * @param {Uint8Array} adata - Associated data to verify
10309 * @returns {Promise<Uint8Array>} The plaintext output.
10310 */
10311 decrypt: async function(ciphertext, nonce, adata) {
10312 if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');
10313 const ciphered = ciphertext.subarray(0, -tagLength);
10314 const ctTag = ciphertext.subarray(-tagLength);
10315 const [
10316 omacNonce,
10317 omacAdata,
10318 omacCiphered
10319 ] = await Promise.all([
10320 omac(zero, nonce),
10321 omac(one, adata),
10322 omac(two, ciphered)
10323 ]);
10324 const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
10325 for (let i = 0; i < tagLength; i++) {
10326 tag[i] ^= omacAdata[i] ^ omacNonce[i];
10327 }
10328 if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');
10329 const plaintext = await ctr(ciphered, omacNonce);
10330 return plaintext;
10331 }
10332 };
10333}
10334
10335
10336/**
10337 * 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}.
10338 * @param {Uint8Array} iv - The initialization vector (16 bytes)
10339 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
10340 */
10341EAX.getNonce = function(iv, chunkIndex) {
10342 const nonce = iv.slice();
10343 for (let i = 0; i < chunkIndex.length; i++) {
10344 nonce[8 + i] ^= chunkIndex[i];
10345 }
10346 return nonce;
10347};
10348
10349EAX.blockLength = blockLength$1;
10350EAX.ivLength = ivLength;
10351EAX.tagLength = tagLength;
10352
10353// OpenPGP.js - An OpenPGP implementation in javascript
10354
10355const blockLength$2 = 16;
10356const ivLength$1 = 15;
10357
10358// https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:
10359// While OCB [RFC7253] allows the authentication tag length to be of any
10360// number up to 128 bits long, this document requires a fixed
10361// authentication tag length of 128 bits (16 octets) for simplicity.
10362const tagLength$1 = 16;
10363
10364
10365function ntz(n) {
10366 let ntz = 0;
10367 for (let i = 1; (n & i) === 0; i <<= 1) {
10368 ntz++;
10369 }
10370 return ntz;
10371}
10372
10373function xorMut$1(S, T) {
10374 for (let i = 0; i < S.length; i++) {
10375 S[i] ^= T[i];
10376 }
10377 return S;
10378}
10379
10380function xor(S, T) {
10381 return xorMut$1(S.slice(), T);
10382}
10383
10384const zeroBlock$1 = new Uint8Array(blockLength$2);
10385const one$1 = new Uint8Array([1]);
10386
10387/**
10388 * Class to en/decrypt using OCB mode.
10389 * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use
10390 * @param {Uint8Array} key - The encryption key
10391 */
10392async function OCB(cipher$1, key) {
10393
10394 let maxNtz = 0;
10395 let encipher;
10396 let decipher;
10397 let mask;
10398
10399 constructKeyVariables(cipher$1, key);
10400
10401 function constructKeyVariables(cipher$1, key) {
10402 const cipherName = enums.read(enums.symmetric, cipher$1);
10403 const aes = new cipher[cipherName](key);
10404 encipher = aes.encrypt.bind(aes);
10405 decipher = aes.decrypt.bind(aes);
10406
10407 const mask_x = encipher(zeroBlock$1);
10408 const mask_$ = util.double(mask_x);
10409 mask = [];
10410 mask[0] = util.double(mask_$);
10411
10412
10413 mask.x = mask_x;
10414 mask.$ = mask_$;
10415 }
10416
10417 function extendKeyVariables(text, adata) {
10418 const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$2 | 0) - 1;
10419 for (let i = maxNtz + 1; i <= newMaxNtz; i++) {
10420 mask[i] = util.double(mask[i - 1]);
10421 }
10422 maxNtz = newMaxNtz;
10423 }
10424
10425 function hash(adata) {
10426 if (!adata.length) {
10427 // Fast path
10428 return zeroBlock$1;
10429 }
10430
10431 //
10432 // Consider A as a sequence of 128-bit blocks
10433 //
10434 const m = adata.length / blockLength$2 | 0;
10435
10436 const offset = new Uint8Array(blockLength$2);
10437 const sum = new Uint8Array(blockLength$2);
10438 for (let i = 0; i < m; i++) {
10439 xorMut$1(offset, mask[ntz(i + 1)]);
10440 xorMut$1(sum, encipher(xor(offset, adata)));
10441 adata = adata.subarray(blockLength$2);
10442 }
10443
10444 //
10445 // Process any final partial block; compute final hash value
10446 //
10447 if (adata.length) {
10448 xorMut$1(offset, mask.x);
10449
10450 const cipherInput = new Uint8Array(blockLength$2);
10451 cipherInput.set(adata, 0);
10452 cipherInput[adata.length] = 0b10000000;
10453 xorMut$1(cipherInput, offset);
10454
10455 xorMut$1(sum, encipher(cipherInput));
10456 }
10457
10458 return sum;
10459 }
10460
10461 /**
10462 * Encrypt/decrypt data.
10463 * @param {encipher|decipher} fn - Encryption/decryption block cipher function
10464 * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input
10465 * @param {Uint8Array} nonce - The nonce (15 bytes)
10466 * @param {Uint8Array} adata - Associated data to sign
10467 * @returns {Promise<Uint8Array>} The ciphertext or plaintext output, with tag appended in both cases.
10468 */
10469 function crypt(fn, text, nonce, adata) {
10470 //
10471 // Consider P as a sequence of 128-bit blocks
10472 //
10473 const m = text.length / blockLength$2 | 0;
10474
10475 //
10476 // Key-dependent variables
10477 //
10478 extendKeyVariables(text, adata);
10479
10480 //
10481 // Nonce-dependent and per-encryption variables
10482 //
10483 // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N
10484 // Note: We assume here that tagLength mod 16 == 0.
10485 const paddedNonce = util.concatUint8Array([zeroBlock$1.subarray(0, ivLength$1 - nonce.length), one$1, nonce]);
10486 // bottom = str2num(Nonce[123..128])
10487 const bottom = paddedNonce[blockLength$2 - 1] & 0b111111;
10488 // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))
10489 paddedNonce[blockLength$2 - 1] &= 0b11000000;
10490 const kTop = encipher(paddedNonce);
10491 // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])
10492 const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);
10493 // Offset_0 = Stretch[1+bottom..128+bottom]
10494 const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);
10495 // Checksum_0 = zeros(128)
10496 const checksum = new Uint8Array(blockLength$2);
10497
10498 const ct = new Uint8Array(text.length + tagLength$1);
10499
10500 //
10501 // Process any whole blocks
10502 //
10503 let i;
10504 let pos = 0;
10505 for (i = 0; i < m; i++) {
10506 // Offset_i = Offset_{i-1} xor L_{ntz(i)}
10507 xorMut$1(offset, mask[ntz(i + 1)]);
10508 // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)
10509 // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)
10510 ct.set(xorMut$1(fn(xor(offset, text)), offset), pos);
10511 // Checksum_i = Checksum_{i-1} xor P_i
10512 xorMut$1(checksum, fn === encipher ? text : ct.subarray(pos));
10513
10514 text = text.subarray(blockLength$2);
10515 pos += blockLength$2;
10516 }
10517
10518 //
10519 // Process any final partial block and compute raw tag
10520 //
10521 if (text.length) {
10522 // Offset_* = Offset_m xor L_*
10523 xorMut$1(offset, mask.x);
10524 // Pad = ENCIPHER(K, Offset_*)
10525 const padding = encipher(offset);
10526 // C_* = P_* xor Pad[1..bitlen(P_*)]
10527 ct.set(xor(text, padding), pos);
10528
10529 // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))
10530 const xorInput = new Uint8Array(blockLength$2);
10531 xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0);
10532 xorInput[text.length] = 0b10000000;
10533 xorMut$1(checksum, xorInput);
10534 pos += text.length;
10535 }
10536 // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)
10537 const tag = xorMut$1(encipher(xorMut$1(xorMut$1(checksum, offset), mask.$)), hash(adata));
10538
10539 //
10540 // Assemble ciphertext
10541 //
10542 // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]
10543 ct.set(tag, pos);
10544 return ct;
10545 }
10546
10547
10548 return {
10549 /**
10550 * Encrypt plaintext input.
10551 * @param {Uint8Array} plaintext - The cleartext input to be encrypted
10552 * @param {Uint8Array} nonce - The nonce (15 bytes)
10553 * @param {Uint8Array} adata - Associated data to sign
10554 * @returns {Promise<Uint8Array>} The ciphertext output.
10555 */
10556 encrypt: async function(plaintext, nonce, adata) {
10557 return crypt(encipher, plaintext, nonce, adata);
10558 },
10559
10560 /**
10561 * Decrypt ciphertext input.
10562 * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted
10563 * @param {Uint8Array} nonce - The nonce (15 bytes)
10564 * @param {Uint8Array} adata - Associated data to sign
10565 * @returns {Promise<Uint8Array>} The ciphertext output.
10566 */
10567 decrypt: async function(ciphertext, nonce, adata) {
10568 if (ciphertext.length < tagLength$1) throw new Error('Invalid OCB ciphertext');
10569
10570 const tag = ciphertext.subarray(-tagLength$1);
10571 ciphertext = ciphertext.subarray(0, -tagLength$1);
10572
10573 const crypted = crypt(decipher, ciphertext, nonce, adata);
10574 // if (Tag[1..TAGLEN] == T)
10575 if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$1))) {
10576 return crypted.subarray(0, -tagLength$1);
10577 }
10578 throw new Error('Authentication tag mismatch');
10579 }
10580 };
10581}
10582
10583
10584/**
10585 * 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}.
10586 * @param {Uint8Array} iv - The initialization vector (15 bytes)
10587 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
10588 */
10589OCB.getNonce = function(iv, chunkIndex) {
10590 const nonce = iv.slice();
10591 for (let i = 0; i < chunkIndex.length; i++) {
10592 nonce[7 + i] ^= chunkIndex[i];
10593 }
10594 return nonce;
10595};
10596
10597OCB.blockLength = blockLength$2;
10598OCB.ivLength = ivLength$1;
10599OCB.tagLength = tagLength$1;
10600
10601const _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5
10602class AES_GCM {
10603 constructor(key, nonce, adata, tagSize = 16, aes) {
10604 this.tagSize = tagSize;
10605 this.gamma0 = 0;
10606 this.counter = 1;
10607 this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');
10608 let { asm, heap } = this.aes.acquire_asm();
10609 // Init GCM
10610 asm.gcm_init();
10611 // Tag size
10612 if (this.tagSize < 4 || this.tagSize > 16)
10613 throw new IllegalArgumentError('illegal tagSize value');
10614 // Nonce
10615 const noncelen = nonce.length || 0;
10616 const noncebuf = new Uint8Array(16);
10617 if (noncelen !== 12) {
10618 this._gcm_mac_process(nonce);
10619 heap[0] = 0;
10620 heap[1] = 0;
10621 heap[2] = 0;
10622 heap[3] = 0;
10623 heap[4] = 0;
10624 heap[5] = 0;
10625 heap[6] = 0;
10626 heap[7] = 0;
10627 heap[8] = 0;
10628 heap[9] = 0;
10629 heap[10] = 0;
10630 heap[11] = noncelen >>> 29;
10631 heap[12] = (noncelen >>> 21) & 255;
10632 heap[13] = (noncelen >>> 13) & 255;
10633 heap[14] = (noncelen >>> 5) & 255;
10634 heap[15] = (noncelen << 3) & 255;
10635 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
10636 asm.get_iv(AES_asm.HEAP_DATA);
10637 asm.set_iv(0, 0, 0, 0);
10638 noncebuf.set(heap.subarray(0, 16));
10639 }
10640 else {
10641 noncebuf.set(nonce);
10642 noncebuf[15] = 1;
10643 }
10644 const nonceview = new DataView(noncebuf.buffer);
10645 this.gamma0 = nonceview.getUint32(12);
10646 asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0);
10647 asm.set_mask(0, 0, 0, 0xffffffff);
10648 // Associated data
10649 if (adata !== undefined) {
10650 if (adata.length > _AES_GCM_data_maxLength)
10651 throw new IllegalArgumentError('illegal adata length');
10652 if (adata.length) {
10653 this.adata = adata;
10654 this._gcm_mac_process(adata);
10655 }
10656 else {
10657 this.adata = undefined;
10658 }
10659 }
10660 else {
10661 this.adata = undefined;
10662 }
10663 // Counter
10664 if (this.counter < 1 || this.counter > 0xffffffff)
10665 throw new RangeError('counter must be a positive 32-bit integer');
10666 asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0);
10667 }
10668 static encrypt(cleartext, key, nonce, adata, tagsize) {
10669 return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext);
10670 }
10671 static decrypt(ciphertext, key, nonce, adata, tagsize) {
10672 return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext);
10673 }
10674 encrypt(data) {
10675 return this.AES_GCM_encrypt(data);
10676 }
10677 decrypt(data) {
10678 return this.AES_GCM_decrypt(data);
10679 }
10680 AES_GCM_Encrypt_process(data) {
10681 let dpos = 0;
10682 let dlen = data.length || 0;
10683 let { asm, heap } = this.aes.acquire_asm();
10684 let counter = this.counter;
10685 let pos = this.aes.pos;
10686 let len = this.aes.len;
10687 let rpos = 0;
10688 let rlen = (len + dlen) & -16;
10689 let wlen = 0;
10690 if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)
10691 throw new RangeError('counter overflow');
10692 const result = new Uint8Array(rlen);
10693 while (dlen > 0) {
10694 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
10695 len += wlen;
10696 dpos += wlen;
10697 dlen -= wlen;
10698 wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len);
10699 wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);
10700 if (wlen)
10701 result.set(heap.subarray(pos, pos + wlen), rpos);
10702 counter += wlen >>> 4;
10703 rpos += wlen;
10704 if (wlen < len) {
10705 pos += wlen;
10706 len -= wlen;
10707 }
10708 else {
10709 pos = 0;
10710 len = 0;
10711 }
10712 }
10713 this.counter = counter;
10714 this.aes.pos = pos;
10715 this.aes.len = len;
10716 return result;
10717 }
10718 AES_GCM_Encrypt_finish() {
10719 let { asm, heap } = this.aes.acquire_asm();
10720 let counter = this.counter;
10721 let tagSize = this.tagSize;
10722 let adata = this.adata;
10723 let pos = this.aes.pos;
10724 let len = this.aes.len;
10725 const result = new Uint8Array(len + tagSize);
10726 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16);
10727 if (len)
10728 result.set(heap.subarray(pos, pos + len));
10729 let i = len;
10730 for (; i & 15; i++)
10731 heap[pos + i] = 0;
10732 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);
10733 const alen = adata !== undefined ? adata.length : 0;
10734 const clen = ((counter - 1) << 4) + len;
10735 heap[0] = 0;
10736 heap[1] = 0;
10737 heap[2] = 0;
10738 heap[3] = alen >>> 29;
10739 heap[4] = alen >>> 21;
10740 heap[5] = (alen >>> 13) & 255;
10741 heap[6] = (alen >>> 5) & 255;
10742 heap[7] = (alen << 3) & 255;
10743 heap[8] = heap[9] = heap[10] = 0;
10744 heap[11] = clen >>> 29;
10745 heap[12] = (clen >>> 21) & 255;
10746 heap[13] = (clen >>> 13) & 255;
10747 heap[14] = (clen >>> 5) & 255;
10748 heap[15] = (clen << 3) & 255;
10749 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
10750 asm.get_iv(AES_asm.HEAP_DATA);
10751 asm.set_counter(0, 0, 0, this.gamma0);
10752 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);
10753 result.set(heap.subarray(0, tagSize), len);
10754 this.counter = 1;
10755 this.aes.pos = 0;
10756 this.aes.len = 0;
10757 return result;
10758 }
10759 AES_GCM_Decrypt_process(data) {
10760 let dpos = 0;
10761 let dlen = data.length || 0;
10762 let { asm, heap } = this.aes.acquire_asm();
10763 let counter = this.counter;
10764 let tagSize = this.tagSize;
10765 let pos = this.aes.pos;
10766 let len = this.aes.len;
10767 let rpos = 0;
10768 let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0;
10769 let tlen = len + dlen - rlen;
10770 let wlen = 0;
10771 if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)
10772 throw new RangeError('counter overflow');
10773 const result = new Uint8Array(rlen);
10774 while (dlen > tlen) {
10775 wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen);
10776 len += wlen;
10777 dpos += wlen;
10778 dlen -= wlen;
10779 wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);
10780 wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen);
10781 if (wlen)
10782 result.set(heap.subarray(pos, pos + wlen), rpos);
10783 counter += wlen >>> 4;
10784 rpos += wlen;
10785 pos = 0;
10786 len = 0;
10787 }
10788 if (dlen > 0) {
10789 len += _heap_write(heap, 0, data, dpos, dlen);
10790 }
10791 this.counter = counter;
10792 this.aes.pos = pos;
10793 this.aes.len = len;
10794 return result;
10795 }
10796 AES_GCM_Decrypt_finish() {
10797 let { asm, heap } = this.aes.acquire_asm();
10798 let tagSize = this.tagSize;
10799 let adata = this.adata;
10800 let counter = this.counter;
10801 let pos = this.aes.pos;
10802 let len = this.aes.len;
10803 let rlen = len - tagSize;
10804 if (len < tagSize)
10805 throw new IllegalStateError('authentication tag not found');
10806 const result = new Uint8Array(rlen);
10807 const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len));
10808 let i = rlen;
10809 for (; i & 15; i++)
10810 heap[pos + i] = 0;
10811 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);
10812 asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i);
10813 if (rlen)
10814 result.set(heap.subarray(pos, pos + rlen));
10815 const alen = adata !== undefined ? adata.length : 0;
10816 const clen = ((counter - 1) << 4) + len - tagSize;
10817 heap[0] = 0;
10818 heap[1] = 0;
10819 heap[2] = 0;
10820 heap[3] = alen >>> 29;
10821 heap[4] = alen >>> 21;
10822 heap[5] = (alen >>> 13) & 255;
10823 heap[6] = (alen >>> 5) & 255;
10824 heap[7] = (alen << 3) & 255;
10825 heap[8] = heap[9] = heap[10] = 0;
10826 heap[11] = clen >>> 29;
10827 heap[12] = (clen >>> 21) & 255;
10828 heap[13] = (clen >>> 13) & 255;
10829 heap[14] = (clen >>> 5) & 255;
10830 heap[15] = (clen << 3) & 255;
10831 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
10832 asm.get_iv(AES_asm.HEAP_DATA);
10833 asm.set_counter(0, 0, 0, this.gamma0);
10834 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);
10835 let acheck = 0;
10836 for (let i = 0; i < tagSize; ++i)
10837 acheck |= atag[i] ^ heap[i];
10838 if (acheck)
10839 throw new SecurityError('data integrity check failed');
10840 this.counter = 1;
10841 this.aes.pos = 0;
10842 this.aes.len = 0;
10843 return result;
10844 }
10845 AES_GCM_decrypt(data) {
10846 const result1 = this.AES_GCM_Decrypt_process(data);
10847 const result2 = this.AES_GCM_Decrypt_finish();
10848 const result = new Uint8Array(result1.length + result2.length);
10849 if (result1.length)
10850 result.set(result1);
10851 if (result2.length)
10852 result.set(result2, result1.length);
10853 return result;
10854 }
10855 AES_GCM_encrypt(data) {
10856 const result1 = this.AES_GCM_Encrypt_process(data);
10857 const result2 = this.AES_GCM_Encrypt_finish();
10858 const result = new Uint8Array(result1.length + result2.length);
10859 if (result1.length)
10860 result.set(result1);
10861 if (result2.length)
10862 result.set(result2, result1.length);
10863 return result;
10864 }
10865 _gcm_mac_process(data) {
10866 let { asm, heap } = this.aes.acquire_asm();
10867 let dpos = 0;
10868 let dlen = data.length || 0;
10869 let wlen = 0;
10870 while (dlen > 0) {
10871 wlen = _heap_write(heap, 0, data, dpos, dlen);
10872 dpos += wlen;
10873 dlen -= wlen;
10874 while (wlen & 15)
10875 heap[wlen++] = 0;
10876 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen);
10877 }
10878 }
10879}
10880
10881// OpenPGP.js - An OpenPGP implementation in javascript
10882
10883const webCrypto$4 = util.getWebCrypto();
10884const nodeCrypto$4 = util.getNodeCrypto();
10885const Buffer$2 = util.getNodeBuffer();
10886
10887const blockLength$3 = 16;
10888const ivLength$2 = 12; // size of the IV in bytes
10889const tagLength$2 = 16; // size of the tag in bytes
10890const ALGO = 'AES-GCM';
10891
10892/**
10893 * Class to en/decrypt using GCM mode.
10894 * @param {enums.symmetric} cipher - The symmetric cipher algorithm to use
10895 * @param {Uint8Array} key - The encryption key
10896 */
10897async function GCM(cipher, key) {
10898 if (cipher !== enums.symmetric.aes128 &&
10899 cipher !== enums.symmetric.aes192 &&
10900 cipher !== enums.symmetric.aes256) {
10901 throw new Error('GCM mode supports only AES cipher');
10902 }
10903
10904 if (util.getNodeCrypto()) { // Node crypto library
10905 return {
10906 encrypt: async function(pt, iv, adata = new Uint8Array()) {
10907 const en = new nodeCrypto$4.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);
10908 en.setAAD(adata);
10909 const ct = Buffer$2.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext
10910 return new Uint8Array(ct);
10911 },
10912
10913 decrypt: async function(ct, iv, adata = new Uint8Array()) {
10914 const de = new nodeCrypto$4.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);
10915 de.setAAD(adata);
10916 de.setAuthTag(ct.slice(ct.length - tagLength$2, ct.length)); // read auth tag at end of ciphertext
10917 const pt = Buffer$2.concat([de.update(ct.slice(0, ct.length - tagLength$2)), de.final()]);
10918 return new Uint8Array(pt);
10919 }
10920 };
10921 }
10922
10923 if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
10924 const _key = await webCrypto$4.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);
10925
10926 return {
10927 encrypt: async function(pt, iv, adata = new Uint8Array()) {
10928 if (!pt.length) { // iOS does not support GCM-en/decrypting empty messages
10929 return AES_GCM.encrypt(pt, key, iv, adata);
10930 }
10931 const ct = await webCrypto$4.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, pt);
10932 return new Uint8Array(ct);
10933 },
10934
10935 decrypt: async function(ct, iv, adata = new Uint8Array()) {
10936 if (ct.length === tagLength$2) { // iOS does not support GCM-en/decrypting empty messages
10937 return AES_GCM.decrypt(ct, key, iv, adata);
10938 }
10939 const pt = await webCrypto$4.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, ct);
10940 return new Uint8Array(pt);
10941 }
10942 };
10943 }
10944
10945 return {
10946 encrypt: async function(pt, iv, adata) {
10947 return AES_GCM.encrypt(pt, key, iv, adata);
10948 },
10949
10950 decrypt: async function(ct, iv, adata) {
10951 return AES_GCM.decrypt(ct, key, iv, adata);
10952 }
10953 };
10954}
10955
10956
10957/**
10958 * Get GCM nonce. Note: this operation is not defined by the standard.
10959 * A future version of the standard may define GCM mode differently,
10960 * hopefully under a different ID (we use Private/Experimental algorithm
10961 * ID 100) so that we can maintain backwards compatibility.
10962 * @param {Uint8Array} iv - The initialization vector (12 bytes)
10963 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
10964 */
10965GCM.getNonce = function(iv, chunkIndex) {
10966 const nonce = iv.slice();
10967 for (let i = 0; i < chunkIndex.length; i++) {
10968 nonce[4 + i] ^= chunkIndex[i];
10969 }
10970 return nonce;
10971};
10972
10973GCM.blockLength = blockLength$3;
10974GCM.ivLength = ivLength$2;
10975GCM.tagLength = tagLength$2;
10976
10977/**
10978 * @fileoverview Cipher modes
10979 * @module crypto/mode
10980 * @private
10981 */
10982
10983var mode = {
10984 /** @see module:crypto/mode/cfb */
10985 cfb: cfb,
10986 /** @see module:crypto/mode/gcm */
10987 gcm: GCM,
10988 experimentalGCM: GCM,
10989 /** @see module:crypto/mode/eax */
10990 eax: EAX,
10991 /** @see module:crypto/mode/ocb */
10992 ocb: OCB
10993};
10994
10995var naclFastLight = createCommonjsModule(function (module) {
10996/*jshint bitwise: false*/
10997
10998(function(nacl) {
10999
11000// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
11001// Public domain.
11002//
11003// Implementation derived from TweetNaCl version 20140427.
11004// See for details: http://tweetnacl.cr.yp.to/
11005
11006var gf = function(init) {
11007 var i, r = new Float64Array(16);
11008 if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
11009 return r;
11010};
11011
11012// Pluggable, initialized in high-level API below.
11013var randombytes = function(/* x, n */) { throw new Error('no PRNG'); };
11014
11015var _9 = new Uint8Array(32); _9[0] = 9;
11016
11017var gf0 = gf(),
11018 gf1 = gf([1]),
11019 _121665 = gf([0xdb41, 1]),
11020 D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
11021 D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
11022 X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
11023 Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
11024 I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
11025
11026function vn(x, xi, y, yi, n) {
11027 var i,d = 0;
11028 for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];
11029 return (1 & ((d - 1) >>> 8)) - 1;
11030}
11031
11032function crypto_verify_32(x, xi, y, yi) {
11033 return vn(x,xi,y,yi,32);
11034}
11035
11036function set25519(r, a) {
11037 var i;
11038 for (i = 0; i < 16; i++) r[i] = a[i]|0;
11039}
11040
11041function car25519(o) {
11042 var i, v, c = 1;
11043 for (i = 0; i < 16; i++) {
11044 v = o[i] + c + 65535;
11045 c = Math.floor(v / 65536);
11046 o[i] = v - c * 65536;
11047 }
11048 o[0] += c-1 + 37 * (c-1);
11049}
11050
11051function sel25519(p, q, b) {
11052 var t, c = ~(b-1);
11053 for (var i = 0; i < 16; i++) {
11054 t = c & (p[i] ^ q[i]);
11055 p[i] ^= t;
11056 q[i] ^= t;
11057 }
11058}
11059
11060function pack25519(o, n) {
11061 var i, j, b;
11062 var m = gf(), t = gf();
11063 for (i = 0; i < 16; i++) t[i] = n[i];
11064 car25519(t);
11065 car25519(t);
11066 car25519(t);
11067 for (j = 0; j < 2; j++) {
11068 m[0] = t[0] - 0xffed;
11069 for (i = 1; i < 15; i++) {
11070 m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
11071 m[i-1] &= 0xffff;
11072 }
11073 m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
11074 b = (m[15]>>16) & 1;
11075 m[14] &= 0xffff;
11076 sel25519(t, m, 1-b);
11077 }
11078 for (i = 0; i < 16; i++) {
11079 o[2*i] = t[i] & 0xff;
11080 o[2*i+1] = t[i]>>8;
11081 }
11082}
11083
11084function neq25519(a, b) {
11085 var c = new Uint8Array(32), d = new Uint8Array(32);
11086 pack25519(c, a);
11087 pack25519(d, b);
11088 return crypto_verify_32(c, 0, d, 0);
11089}
11090
11091function par25519(a) {
11092 var d = new Uint8Array(32);
11093 pack25519(d, a);
11094 return d[0] & 1;
11095}
11096
11097function unpack25519(o, n) {
11098 var i;
11099 for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);
11100 o[15] &= 0x7fff;
11101}
11102
11103function A(o, a, b) {
11104 for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
11105}
11106
11107function Z(o, a, b) {
11108 for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
11109}
11110
11111function M(o, a, b) {
11112 var v, c,
11113 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
11114 t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
11115 t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
11116 t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
11117 b0 = b[0],
11118 b1 = b[1],
11119 b2 = b[2],
11120 b3 = b[3],
11121 b4 = b[4],
11122 b5 = b[5],
11123 b6 = b[6],
11124 b7 = b[7],
11125 b8 = b[8],
11126 b9 = b[9],
11127 b10 = b[10],
11128 b11 = b[11],
11129 b12 = b[12],
11130 b13 = b[13],
11131 b14 = b[14],
11132 b15 = b[15];
11133
11134 v = a[0];
11135 t0 += v * b0;
11136 t1 += v * b1;
11137 t2 += v * b2;
11138 t3 += v * b3;
11139 t4 += v * b4;
11140 t5 += v * b5;
11141 t6 += v * b6;
11142 t7 += v * b7;
11143 t8 += v * b8;
11144 t9 += v * b9;
11145 t10 += v * b10;
11146 t11 += v * b11;
11147 t12 += v * b12;
11148 t13 += v * b13;
11149 t14 += v * b14;
11150 t15 += v * b15;
11151 v = a[1];
11152 t1 += v * b0;
11153 t2 += v * b1;
11154 t3 += v * b2;
11155 t4 += v * b3;
11156 t5 += v * b4;
11157 t6 += v * b5;
11158 t7 += v * b6;
11159 t8 += v * b7;
11160 t9 += v * b8;
11161 t10 += v * b9;
11162 t11 += v * b10;
11163 t12 += v * b11;
11164 t13 += v * b12;
11165 t14 += v * b13;
11166 t15 += v * b14;
11167 t16 += v * b15;
11168 v = a[2];
11169 t2 += v * b0;
11170 t3 += v * b1;
11171 t4 += v * b2;
11172 t5 += v * b3;
11173 t6 += v * b4;
11174 t7 += v * b5;
11175 t8 += v * b6;
11176 t9 += v * b7;
11177 t10 += v * b8;
11178 t11 += v * b9;
11179 t12 += v * b10;
11180 t13 += v * b11;
11181 t14 += v * b12;
11182 t15 += v * b13;
11183 t16 += v * b14;
11184 t17 += v * b15;
11185 v = a[3];
11186 t3 += v * b0;
11187 t4 += v * b1;
11188 t5 += v * b2;
11189 t6 += v * b3;
11190 t7 += v * b4;
11191 t8 += v * b5;
11192 t9 += v * b6;
11193 t10 += v * b7;
11194 t11 += v * b8;
11195 t12 += v * b9;
11196 t13 += v * b10;
11197 t14 += v * b11;
11198 t15 += v * b12;
11199 t16 += v * b13;
11200 t17 += v * b14;
11201 t18 += v * b15;
11202 v = a[4];
11203 t4 += v * b0;
11204 t5 += v * b1;
11205 t6 += v * b2;
11206 t7 += v * b3;
11207 t8 += v * b4;
11208 t9 += v * b5;
11209 t10 += v * b6;
11210 t11 += v * b7;
11211 t12 += v * b8;
11212 t13 += v * b9;
11213 t14 += v * b10;
11214 t15 += v * b11;
11215 t16 += v * b12;
11216 t17 += v * b13;
11217 t18 += v * b14;
11218 t19 += v * b15;
11219 v = a[5];
11220 t5 += v * b0;
11221 t6 += v * b1;
11222 t7 += v * b2;
11223 t8 += v * b3;
11224 t9 += v * b4;
11225 t10 += v * b5;
11226 t11 += v * b6;
11227 t12 += v * b7;
11228 t13 += v * b8;
11229 t14 += v * b9;
11230 t15 += v * b10;
11231 t16 += v * b11;
11232 t17 += v * b12;
11233 t18 += v * b13;
11234 t19 += v * b14;
11235 t20 += v * b15;
11236 v = a[6];
11237 t6 += v * b0;
11238 t7 += v * b1;
11239 t8 += v * b2;
11240 t9 += v * b3;
11241 t10 += v * b4;
11242 t11 += v * b5;
11243 t12 += v * b6;
11244 t13 += v * b7;
11245 t14 += v * b8;
11246 t15 += v * b9;
11247 t16 += v * b10;
11248 t17 += v * b11;
11249 t18 += v * b12;
11250 t19 += v * b13;
11251 t20 += v * b14;
11252 t21 += v * b15;
11253 v = a[7];
11254 t7 += v * b0;
11255 t8 += v * b1;
11256 t9 += v * b2;
11257 t10 += v * b3;
11258 t11 += v * b4;
11259 t12 += v * b5;
11260 t13 += v * b6;
11261 t14 += v * b7;
11262 t15 += v * b8;
11263 t16 += v * b9;
11264 t17 += v * b10;
11265 t18 += v * b11;
11266 t19 += v * b12;
11267 t20 += v * b13;
11268 t21 += v * b14;
11269 t22 += v * b15;
11270 v = a[8];
11271 t8 += v * b0;
11272 t9 += v * b1;
11273 t10 += v * b2;
11274 t11 += v * b3;
11275 t12 += v * b4;
11276 t13 += v * b5;
11277 t14 += v * b6;
11278 t15 += v * b7;
11279 t16 += v * b8;
11280 t17 += v * b9;
11281 t18 += v * b10;
11282 t19 += v * b11;
11283 t20 += v * b12;
11284 t21 += v * b13;
11285 t22 += v * b14;
11286 t23 += v * b15;
11287 v = a[9];
11288 t9 += v * b0;
11289 t10 += v * b1;
11290 t11 += v * b2;
11291 t12 += v * b3;
11292 t13 += v * b4;
11293 t14 += v * b5;
11294 t15 += v * b6;
11295 t16 += v * b7;
11296 t17 += v * b8;
11297 t18 += v * b9;
11298 t19 += v * b10;
11299 t20 += v * b11;
11300 t21 += v * b12;
11301 t22 += v * b13;
11302 t23 += v * b14;
11303 t24 += v * b15;
11304 v = a[10];
11305 t10 += v * b0;
11306 t11 += v * b1;
11307 t12 += v * b2;
11308 t13 += v * b3;
11309 t14 += v * b4;
11310 t15 += v * b5;
11311 t16 += v * b6;
11312 t17 += v * b7;
11313 t18 += v * b8;
11314 t19 += v * b9;
11315 t20 += v * b10;
11316 t21 += v * b11;
11317 t22 += v * b12;
11318 t23 += v * b13;
11319 t24 += v * b14;
11320 t25 += v * b15;
11321 v = a[11];
11322 t11 += v * b0;
11323 t12 += v * b1;
11324 t13 += v * b2;
11325 t14 += v * b3;
11326 t15 += v * b4;
11327 t16 += v * b5;
11328 t17 += v * b6;
11329 t18 += v * b7;
11330 t19 += v * b8;
11331 t20 += v * b9;
11332 t21 += v * b10;
11333 t22 += v * b11;
11334 t23 += v * b12;
11335 t24 += v * b13;
11336 t25 += v * b14;
11337 t26 += v * b15;
11338 v = a[12];
11339 t12 += v * b0;
11340 t13 += v * b1;
11341 t14 += v * b2;
11342 t15 += v * b3;
11343 t16 += v * b4;
11344 t17 += v * b5;
11345 t18 += v * b6;
11346 t19 += v * b7;
11347 t20 += v * b8;
11348 t21 += v * b9;
11349 t22 += v * b10;
11350 t23 += v * b11;
11351 t24 += v * b12;
11352 t25 += v * b13;
11353 t26 += v * b14;
11354 t27 += v * b15;
11355 v = a[13];
11356 t13 += v * b0;
11357 t14 += v * b1;
11358 t15 += v * b2;
11359 t16 += v * b3;
11360 t17 += v * b4;
11361 t18 += v * b5;
11362 t19 += v * b6;
11363 t20 += v * b7;
11364 t21 += v * b8;
11365 t22 += v * b9;
11366 t23 += v * b10;
11367 t24 += v * b11;
11368 t25 += v * b12;
11369 t26 += v * b13;
11370 t27 += v * b14;
11371 t28 += v * b15;
11372 v = a[14];
11373 t14 += v * b0;
11374 t15 += v * b1;
11375 t16 += v * b2;
11376 t17 += v * b3;
11377 t18 += v * b4;
11378 t19 += v * b5;
11379 t20 += v * b6;
11380 t21 += v * b7;
11381 t22 += v * b8;
11382 t23 += v * b9;
11383 t24 += v * b10;
11384 t25 += v * b11;
11385 t26 += v * b12;
11386 t27 += v * b13;
11387 t28 += v * b14;
11388 t29 += v * b15;
11389 v = a[15];
11390 t15 += v * b0;
11391 t16 += v * b1;
11392 t17 += v * b2;
11393 t18 += v * b3;
11394 t19 += v * b4;
11395 t20 += v * b5;
11396 t21 += v * b6;
11397 t22 += v * b7;
11398 t23 += v * b8;
11399 t24 += v * b9;
11400 t25 += v * b10;
11401 t26 += v * b11;
11402 t27 += v * b12;
11403 t28 += v * b13;
11404 t29 += v * b14;
11405 t30 += v * b15;
11406
11407 t0 += 38 * t16;
11408 t1 += 38 * t17;
11409 t2 += 38 * t18;
11410 t3 += 38 * t19;
11411 t4 += 38 * t20;
11412 t5 += 38 * t21;
11413 t6 += 38 * t22;
11414 t7 += 38 * t23;
11415 t8 += 38 * t24;
11416 t9 += 38 * t25;
11417 t10 += 38 * t26;
11418 t11 += 38 * t27;
11419 t12 += 38 * t28;
11420 t13 += 38 * t29;
11421 t14 += 38 * t30;
11422 // t15 left as is
11423
11424 // first car
11425 c = 1;
11426 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
11427 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
11428 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
11429 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
11430 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
11431 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
11432 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
11433 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
11434 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
11435 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
11436 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
11437 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
11438 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
11439 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
11440 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
11441 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
11442 t0 += c-1 + 37 * (c-1);
11443
11444 // second car
11445 c = 1;
11446 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
11447 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
11448 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
11449 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
11450 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
11451 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
11452 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
11453 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
11454 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
11455 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
11456 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
11457 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
11458 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
11459 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
11460 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
11461 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
11462 t0 += c-1 + 37 * (c-1);
11463
11464 o[ 0] = t0;
11465 o[ 1] = t1;
11466 o[ 2] = t2;
11467 o[ 3] = t3;
11468 o[ 4] = t4;
11469 o[ 5] = t5;
11470 o[ 6] = t6;
11471 o[ 7] = t7;
11472 o[ 8] = t8;
11473 o[ 9] = t9;
11474 o[10] = t10;
11475 o[11] = t11;
11476 o[12] = t12;
11477 o[13] = t13;
11478 o[14] = t14;
11479 o[15] = t15;
11480}
11481
11482function S(o, a) {
11483 M(o, a, a);
11484}
11485
11486function inv25519(o, i) {
11487 var c = gf();
11488 var a;
11489 for (a = 0; a < 16; a++) c[a] = i[a];
11490 for (a = 253; a >= 0; a--) {
11491 S(c, c);
11492 if(a !== 2 && a !== 4) M(c, c, i);
11493 }
11494 for (a = 0; a < 16; a++) o[a] = c[a];
11495}
11496
11497function pow2523(o, i) {
11498 var c = gf();
11499 var a;
11500 for (a = 0; a < 16; a++) c[a] = i[a];
11501 for (a = 250; a >= 0; a--) {
11502 S(c, c);
11503 if(a !== 1) M(c, c, i);
11504 }
11505 for (a = 0; a < 16; a++) o[a] = c[a];
11506}
11507
11508function crypto_scalarmult(q, n, p) {
11509 var z = new Uint8Array(32);
11510 var x = new Float64Array(80), r, i;
11511 var a = gf(), b = gf(), c = gf(),
11512 d = gf(), e = gf(), f = gf();
11513 for (i = 0; i < 31; i++) z[i] = n[i];
11514 z[31]=(n[31]&127)|64;
11515 z[0]&=248;
11516 unpack25519(x,p);
11517 for (i = 0; i < 16; i++) {
11518 b[i]=x[i];
11519 d[i]=a[i]=c[i]=0;
11520 }
11521 a[0]=d[0]=1;
11522 for (i=254; i>=0; --i) {
11523 r=(z[i>>>3]>>>(i&7))&1;
11524 sel25519(a,b,r);
11525 sel25519(c,d,r);
11526 A(e,a,c);
11527 Z(a,a,c);
11528 A(c,b,d);
11529 Z(b,b,d);
11530 S(d,e);
11531 S(f,a);
11532 M(a,c,a);
11533 M(c,b,e);
11534 A(e,a,c);
11535 Z(a,a,c);
11536 S(b,a);
11537 Z(c,d,f);
11538 M(a,c,_121665);
11539 A(a,a,d);
11540 M(c,c,a);
11541 M(a,d,f);
11542 M(d,b,x);
11543 S(b,e);
11544 sel25519(a,b,r);
11545 sel25519(c,d,r);
11546 }
11547 for (i = 0; i < 16; i++) {
11548 x[i+16]=a[i];
11549 x[i+32]=c[i];
11550 x[i+48]=b[i];
11551 x[i+64]=d[i];
11552 }
11553 var x32 = x.subarray(32);
11554 var x16 = x.subarray(16);
11555 inv25519(x32,x32);
11556 M(x16,x16,x32);
11557 pack25519(q,x16);
11558 return 0;
11559}
11560
11561function crypto_scalarmult_base(q, n) {
11562 return crypto_scalarmult(q, n, _9);
11563}
11564
11565function crypto_box_keypair(y, x) {
11566 randombytes(x, 32);
11567 return crypto_scalarmult_base(y, x);
11568}
11569
11570function add(p, q) {
11571 var a = gf(), b = gf(), c = gf(),
11572 d = gf(), e = gf(), f = gf(),
11573 g = gf(), h = gf(), t = gf();
11574
11575 Z(a, p[1], p[0]);
11576 Z(t, q[1], q[0]);
11577 M(a, a, t);
11578 A(b, p[0], p[1]);
11579 A(t, q[0], q[1]);
11580 M(b, b, t);
11581 M(c, p[3], q[3]);
11582 M(c, c, D2);
11583 M(d, p[2], q[2]);
11584 A(d, d, d);
11585 Z(e, b, a);
11586 Z(f, d, c);
11587 A(g, d, c);
11588 A(h, b, a);
11589
11590 M(p[0], e, f);
11591 M(p[1], h, g);
11592 M(p[2], g, f);
11593 M(p[3], e, h);
11594}
11595
11596function cswap(p, q, b) {
11597 var i;
11598 for (i = 0; i < 4; i++) {
11599 sel25519(p[i], q[i], b);
11600 }
11601}
11602
11603function pack(r, p) {
11604 var tx = gf(), ty = gf(), zi = gf();
11605 inv25519(zi, p[2]);
11606 M(tx, p[0], zi);
11607 M(ty, p[1], zi);
11608 pack25519(r, ty);
11609 r[31] ^= par25519(tx) << 7;
11610}
11611
11612function scalarmult(p, q, s) {
11613 var b, i;
11614 set25519(p[0], gf0);
11615 set25519(p[1], gf1);
11616 set25519(p[2], gf1);
11617 set25519(p[3], gf0);
11618 for (i = 255; i >= 0; --i) {
11619 b = (s[(i/8)|0] >> (i&7)) & 1;
11620 cswap(p, q, b);
11621 add(q, p);
11622 add(p, p);
11623 cswap(p, q, b);
11624 }
11625}
11626
11627function scalarbase(p, s) {
11628 var q = [gf(), gf(), gf(), gf()];
11629 set25519(q[0], X);
11630 set25519(q[1], Y);
11631 set25519(q[2], gf1);
11632 M(q[3], X, Y);
11633 scalarmult(p, q, s);
11634}
11635
11636function crypto_sign_keypair(pk, sk, seeded) {
11637 var d;
11638 var p = [gf(), gf(), gf(), gf()];
11639 var i;
11640
11641 if (!seeded) randombytes(sk, 32);
11642 d = nacl.hash(sk.subarray(0, 32));
11643 d[0] &= 248;
11644 d[31] &= 127;
11645 d[31] |= 64;
11646
11647 scalarbase(p, d);
11648 pack(pk, p);
11649
11650 for (i = 0; i < 32; i++) sk[i+32] = pk[i];
11651 return 0;
11652}
11653
11654var 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]);
11655
11656function modL(r, x) {
11657 var carry, i, j, k;
11658 for (i = 63; i >= 32; --i) {
11659 carry = 0;
11660 for (j = i - 32, k = i - 12; j < k; ++j) {
11661 x[j] += carry - 16 * x[i] * L[j - (i - 32)];
11662 carry = Math.floor((x[j] + 128) / 256);
11663 x[j] -= carry * 256;
11664 }
11665 x[j] += carry;
11666 x[i] = 0;
11667 }
11668 carry = 0;
11669 for (j = 0; j < 32; j++) {
11670 x[j] += carry - (x[31] >> 4) * L[j];
11671 carry = x[j] >> 8;
11672 x[j] &= 255;
11673 }
11674 for (j = 0; j < 32; j++) x[j] -= carry * L[j];
11675 for (i = 0; i < 32; i++) {
11676 x[i+1] += x[i] >> 8;
11677 r[i] = x[i] & 255;
11678 }
11679}
11680
11681function reduce(r) {
11682 var x = new Float64Array(64), i;
11683 for (i = 0; i < 64; i++) x[i] = r[i];
11684 for (i = 0; i < 64; i++) r[i] = 0;
11685 modL(r, x);
11686}
11687
11688// Note: difference from C - smlen returned, not passed as argument.
11689function crypto_sign(sm, m, n, sk) {
11690 var d, h, r;
11691 var i, j, x = new Float64Array(64);
11692 var p = [gf(), gf(), gf(), gf()];
11693
11694 d = nacl.hash(sk.subarray(0, 32));
11695 d[0] &= 248;
11696 d[31] &= 127;
11697 d[31] |= 64;
11698
11699 var smlen = n + 64;
11700 for (i = 0; i < n; i++) sm[64 + i] = m[i];
11701 for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
11702
11703 r = nacl.hash(sm.subarray(32, smlen));
11704 reduce(r);
11705 scalarbase(p, r);
11706 pack(sm, p);
11707
11708 for (i = 32; i < 64; i++) sm[i] = sk[i];
11709 h = nacl.hash(sm.subarray(0, smlen));
11710 reduce(h);
11711
11712 for (i = 0; i < 64; i++) x[i] = 0;
11713 for (i = 0; i < 32; i++) x[i] = r[i];
11714 for (i = 0; i < 32; i++) {
11715 for (j = 0; j < 32; j++) {
11716 x[i+j] += h[i] * d[j];
11717 }
11718 }
11719
11720 modL(sm.subarray(32), x);
11721 return smlen;
11722}
11723
11724function unpackneg(r, p) {
11725 var t = gf(), chk = gf(), num = gf(),
11726 den = gf(), den2 = gf(), den4 = gf(),
11727 den6 = gf();
11728
11729 set25519(r[2], gf1);
11730 unpack25519(r[1], p);
11731 S(num, r[1]);
11732 M(den, num, D);
11733 Z(num, num, r[2]);
11734 A(den, r[2], den);
11735
11736 S(den2, den);
11737 S(den4, den2);
11738 M(den6, den4, den2);
11739 M(t, den6, num);
11740 M(t, t, den);
11741
11742 pow2523(t, t);
11743 M(t, t, num);
11744 M(t, t, den);
11745 M(t, t, den);
11746 M(r[0], t, den);
11747
11748 S(chk, r[0]);
11749 M(chk, chk, den);
11750 if (neq25519(chk, num)) M(r[0], r[0], I);
11751
11752 S(chk, r[0]);
11753 M(chk, chk, den);
11754 if (neq25519(chk, num)) return -1;
11755
11756 if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);
11757
11758 M(r[3], r[0], r[1]);
11759 return 0;
11760}
11761
11762function crypto_sign_open(m, sm, n, pk) {
11763 var i;
11764 var t = new Uint8Array(32), h;
11765 var p = [gf(), gf(), gf(), gf()],
11766 q = [gf(), gf(), gf(), gf()];
11767
11768 if (n < 64) return -1;
11769
11770 if (unpackneg(q, pk)) return -1;
11771
11772 for (i = 0; i < n; i++) m[i] = sm[i];
11773 for (i = 0; i < 32; i++) m[i+32] = pk[i];
11774 h = nacl.hash(m.subarray(0, n));
11775 reduce(h);
11776 scalarmult(p, q, h);
11777
11778 scalarbase(q, sm.subarray(32));
11779 add(p, q);
11780 pack(t, p);
11781
11782 n -= 64;
11783 if (crypto_verify_32(sm, 0, t, 0)) {
11784 for (i = 0; i < n; i++) m[i] = 0;
11785 return -1;
11786 }
11787
11788 for (i = 0; i < n; i++) m[i] = sm[i + 64];
11789 return n;
11790}
11791
11792var crypto_scalarmult_BYTES = 32,
11793 crypto_scalarmult_SCALARBYTES = 32,
11794 crypto_box_PUBLICKEYBYTES = 32,
11795 crypto_box_SECRETKEYBYTES = 32,
11796 crypto_sign_BYTES = 64,
11797 crypto_sign_PUBLICKEYBYTES = 32,
11798 crypto_sign_SECRETKEYBYTES = 64,
11799 crypto_sign_SEEDBYTES = 32;
11800
11801function checkArrayTypes() {
11802 for (var i = 0; i < arguments.length; i++) {
11803 if (!(arguments[i] instanceof Uint8Array))
11804 throw new TypeError('unexpected type, use Uint8Array');
11805 }
11806}
11807
11808function cleanup(arr) {
11809 for (var i = 0; i < arr.length; i++) arr[i] = 0;
11810}
11811
11812nacl.scalarMult = function(n, p) {
11813 checkArrayTypes(n, p);
11814 if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
11815 if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
11816 var q = new Uint8Array(crypto_scalarmult_BYTES);
11817 crypto_scalarmult(q, n, p);
11818 return q;
11819};
11820
11821nacl.box = {};
11822
11823nacl.box.keyPair = function() {
11824 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
11825 var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
11826 crypto_box_keypair(pk, sk);
11827 return {publicKey: pk, secretKey: sk};
11828};
11829
11830nacl.box.keyPair.fromSecretKey = function(secretKey) {
11831 checkArrayTypes(secretKey);
11832 if (secretKey.length !== crypto_box_SECRETKEYBYTES)
11833 throw new Error('bad secret key size');
11834 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
11835 crypto_scalarmult_base(pk, secretKey);
11836 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
11837};
11838
11839nacl.sign = function(msg, secretKey) {
11840 checkArrayTypes(msg, secretKey);
11841 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
11842 throw new Error('bad secret key size');
11843 var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
11844 crypto_sign(signedMsg, msg, msg.length, secretKey);
11845 return signedMsg;
11846};
11847
11848nacl.sign.detached = function(msg, secretKey) {
11849 var signedMsg = nacl.sign(msg, secretKey);
11850 var sig = new Uint8Array(crypto_sign_BYTES);
11851 for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
11852 return sig;
11853};
11854
11855nacl.sign.detached.verify = function(msg, sig, publicKey) {
11856 checkArrayTypes(msg, sig, publicKey);
11857 if (sig.length !== crypto_sign_BYTES)
11858 throw new Error('bad signature size');
11859 if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
11860 throw new Error('bad public key size');
11861 var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
11862 var m = new Uint8Array(crypto_sign_BYTES + msg.length);
11863 var i;
11864 for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
11865 for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
11866 return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
11867};
11868
11869nacl.sign.keyPair = function() {
11870 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
11871 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
11872 crypto_sign_keypair(pk, sk);
11873 return {publicKey: pk, secretKey: sk};
11874};
11875
11876nacl.sign.keyPair.fromSecretKey = function(secretKey) {
11877 checkArrayTypes(secretKey);
11878 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
11879 throw new Error('bad secret key size');
11880 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
11881 for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
11882 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
11883};
11884
11885nacl.sign.keyPair.fromSeed = function(seed) {
11886 checkArrayTypes(seed);
11887 if (seed.length !== crypto_sign_SEEDBYTES)
11888 throw new Error('bad seed size');
11889 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
11890 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
11891 for (var i = 0; i < 32; i++) sk[i] = seed[i];
11892 crypto_sign_keypair(pk, sk, true);
11893 return {publicKey: pk, secretKey: sk};
11894};
11895
11896nacl.setPRNG = function(fn) {
11897 randombytes = fn;
11898};
11899
11900(function() {
11901 // Initialize PRNG if environment provides CSPRNG.
11902 // If not, methods calling randombytes will throw.
11903 var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
11904 if (crypto && crypto.getRandomValues) {
11905 // Browsers.
11906 var QUOTA = 65536;
11907 nacl.setPRNG(function(x, n) {
11908 var i, v = new Uint8Array(n);
11909 for (i = 0; i < n; i += QUOTA) {
11910 crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
11911 }
11912 for (i = 0; i < n; i++) x[i] = v[i];
11913 cleanup(v);
11914 });
11915 } else if (typeof commonjsRequire !== 'undefined') {
11916 // Node.js.
11917 crypto = void('crypto');
11918 if (crypto && crypto.randomBytes) {
11919 nacl.setPRNG(function(x, n) {
11920 var i, v = crypto.randomBytes(n);
11921 for (i = 0; i < n; i++) x[i] = v[i];
11922 cleanup(v);
11923 });
11924 }
11925 }
11926})();
11927
11928})(module.exports ? module.exports : (self.nacl = self.nacl || {}));
11929});
11930
11931// GPG4Browsers - An OpenPGP implementation in javascript
11932
11933const nodeCrypto$5 = util.getNodeCrypto();
11934
11935/**
11936 * Retrieve secure random byte array of the specified length
11937 * @param {Integer} length - Length in bytes to generate
11938 * @returns {Uint8Array} Random byte array.
11939 */
11940function getRandomBytes(length) {
11941 const buf = new Uint8Array(length);
11942 if (nodeCrypto$5) {
11943 const bytes = nodeCrypto$5.randomBytes(buf.length);
11944 buf.set(bytes);
11945 } else if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
11946 crypto.getRandomValues(buf);
11947 } else {
11948 throw new Error('No secure random number generator available.');
11949 }
11950 return buf;
11951}
11952
11953/**
11954 * Create a secure random BigInteger that is greater than or equal to min and less than max.
11955 * @param {module:BigInteger} min - Lower bound, included
11956 * @param {module:BigInteger} max - Upper bound, excluded
11957 * @returns {Promise<module:BigInteger>} Random BigInteger.
11958 * @async
11959 */
11960async function getRandomBigInteger(min, max) {
11961 const BigInteger = await util.getBigInteger();
11962
11963 if (max.lt(min)) {
11964 throw new Error('Illegal parameter value: max <= min');
11965 }
11966
11967 const modulus = max.sub(min);
11968 const bytes = modulus.byteLength();
11969
11970 // Using a while loop is necessary to avoid bias introduced by the mod operation.
11971 // However, we request 64 extra random bits so that the bias is negligible.
11972 // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
11973 const r = new BigInteger(await getRandomBytes(bytes + 8));
11974 return r.mod(modulus).add(min);
11975}
11976
11977var random = /*#__PURE__*/Object.freeze({
11978 __proto__: null,
11979 getRandomBytes: getRandomBytes,
11980 getRandomBigInteger: getRandomBigInteger
11981});
11982
11983// OpenPGP.js - An OpenPGP implementation in javascript
11984
11985/**
11986 * Generate a probably prime random number
11987 * @param {Integer} bits - Bit length of the prime
11988 * @param {BigInteger} e - Optional RSA exponent to check against the prime
11989 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
11990 * @returns BigInteger
11991 * @async
11992 */
11993async function randomProbablePrime(bits, e, k) {
11994 const BigInteger = await util.getBigInteger();
11995 const one = new BigInteger(1);
11996 const min = one.leftShift(new BigInteger(bits - 1));
11997 const thirty = new BigInteger(30);
11998 /*
11999 * We can avoid any multiples of 3 and 5 by looking at n mod 30
12000 * 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
12001 * the next possible prime is mod 30:
12002 * 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
12003 */
12004 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];
12005
12006 const n = await getRandomBigInteger(min, min.leftShift(one));
12007 let i = n.mod(thirty).toNumber();
12008
12009 do {
12010 n.iadd(new BigInteger(adds[i]));
12011 i = (i + adds[i]) % adds.length;
12012 // If reached the maximum, go back to the minimum.
12013 if (n.bitLength() > bits) {
12014 n.imod(min.leftShift(one)).iadd(min);
12015 i = n.mod(thirty).toNumber();
12016 }
12017 } while (!await isProbablePrime(n, e, k));
12018 return n;
12019}
12020
12021/**
12022 * Probabilistic primality testing
12023 * @param {BigInteger} n - Number to test
12024 * @param {BigInteger} e - Optional RSA exponent to check against the prime
12025 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
12026 * @returns {boolean}
12027 * @async
12028 */
12029async function isProbablePrime(n, e, k) {
12030 if (e && !n.dec().gcd(e).isOne()) {
12031 return false;
12032 }
12033 if (!await divisionTest(n)) {
12034 return false;
12035 }
12036 if (!await fermat(n)) {
12037 return false;
12038 }
12039 if (!await millerRabin(n, k)) {
12040 return false;
12041 }
12042 // TODO implement the Lucas test
12043 // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
12044 return true;
12045}
12046
12047/**
12048 * Tests whether n is probably prime or not using Fermat's test with b = 2.
12049 * Fails if b^(n-1) mod n != 1.
12050 * @param {BigInteger} n - Number to test
12051 * @param {BigInteger} b - Optional Fermat test base
12052 * @returns {boolean}
12053 */
12054async function fermat(n, b) {
12055 const BigInteger = await util.getBigInteger();
12056 b = b || new BigInteger(2);
12057 return b.modExp(n.dec(), n).isOne();
12058}
12059
12060async function divisionTest(n) {
12061 const BigInteger = await util.getBigInteger();
12062 return smallPrimes.every(m => {
12063 return n.mod(new BigInteger(m)) !== 0;
12064 });
12065}
12066
12067// https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c
12068const smallPrimes = [
12069 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
12070 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
12071 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
12072 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
12073 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,
12074 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
12075 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,
12076 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,
12077 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
12078 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,
12079 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
12080 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
12081 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,
12082 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,
12083 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
12084 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,
12085 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,
12086 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,
12087 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
12088 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,
12089 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,
12090 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,
12091 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,
12092 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
12093 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,
12094 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,
12095 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,
12096 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,
12097 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
12098 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,
12099 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,
12100 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,
12101 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,
12102 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
12103 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,
12104 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,
12105 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,
12106 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,
12107 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
12108 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,
12109 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,
12110 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,
12111 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,
12112 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
12113 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,
12114 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,
12115 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,
12116 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,
12117 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
12118 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,
12119 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,
12120 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,
12121 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,
12122 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
12123 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,
12124 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,
12125 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,
12126 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,
12127 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
12128 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,
12129 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,
12130 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,
12131 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,
12132 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
12133 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,
12134 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,
12135 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,
12136 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,
12137 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
12138 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,
12139 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,
12140 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,
12141 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,
12142 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,
12143 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,
12144 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,
12145 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,
12146 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,
12147 4957, 4967, 4969, 4973, 4987, 4993, 4999
12148];
12149
12150
12151// Miller-Rabin - Miller Rabin algorithm for primality test
12152// Copyright Fedor Indutny, 2014.
12153//
12154// This software is licensed under the MIT License.
12155//
12156// Permission is hereby granted, free of charge, to any person obtaining a
12157// copy of this software and associated documentation files (the
12158// "Software"), to deal in the Software without restriction, including
12159// without limitation the rights to use, copy, modify, merge, publish,
12160// distribute, sublicense, and/or sell copies of the Software, and to permit
12161// persons to whom the Software is furnished to do so, subject to the
12162// following conditions:
12163//
12164// The above copyright notice and this permission notice shall be included
12165// in all copies or substantial portions of the Software.
12166//
12167// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12168// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12169// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12170// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12171// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12172// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12173// USE OR OTHER DEALINGS IN THE SOFTWARE.
12174
12175// Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin
12176
12177// Sample syntax for Fixed-Base Miller-Rabin:
12178// millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))
12179
12180/**
12181 * Tests whether n is probably prime or not using the Miller-Rabin test.
12182 * See HAC Remark 4.28.
12183 * @param {BigInteger} n - Number to test
12184 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
12185 * @param {Function} rand - Optional function to generate potential witnesses
12186 * @returns {boolean}
12187 * @async
12188 */
12189async function millerRabin(n, k, rand) {
12190 const BigInteger = await util.getBigInteger();
12191 const len = n.bitLength();
12192
12193 if (!k) {
12194 k = Math.max(1, (len / 48) | 0);
12195 }
12196
12197 const n1 = n.dec(); // n - 1
12198
12199 // Find d and s, (n - 1) = (2 ^ s) * d;
12200 let s = 0;
12201 while (!n1.getBit(s)) { s++; }
12202 const d = n.rightShift(new BigInteger(s));
12203
12204 for (; k > 0; k--) {
12205 const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1);
12206
12207 let x = a.modExp(d, n);
12208 if (x.isOne() || x.equal(n1)) {
12209 continue;
12210 }
12211
12212 let i;
12213 for (i = 1; i < s; i++) {
12214 x = x.mul(x).mod(n);
12215
12216 if (x.isOne()) {
12217 return false;
12218 }
12219 if (x.equal(n1)) {
12220 break;
12221 }
12222 }
12223
12224 if (i === s) {
12225 return false;
12226 }
12227 }
12228
12229 return true;
12230}
12231
12232// GPG4Browsers - An OpenPGP implementation in javascript
12233
12234/**
12235 * ASN1 object identifiers for hashes
12236 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}
12237 */
12238const hash_headers = [];
12239hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,
12240 0x10];
12241hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];
12242hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];
12243hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,
12244 0x04, 0x20];
12245hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,
12246 0x04, 0x30];
12247hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
12248 0x00, 0x04, 0x40];
12249hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,
12250 0x00, 0x04, 0x1C];
12251
12252/**
12253 * Create padding with secure random data
12254 * @private
12255 * @param {Integer} length - Length of the padding in bytes
12256 * @returns {Uint8Array} Random padding.
12257 */
12258function getPKCS1Padding(length) {
12259 const result = new Uint8Array(length);
12260 let count = 0;
12261 while (count < length) {
12262 const randomBytes = getRandomBytes(length - count);
12263 for (let i = 0; i < randomBytes.length; i++) {
12264 if (randomBytes[i] !== 0) {
12265 result[count++] = randomBytes[i];
12266 }
12267 }
12268 }
12269 return result;
12270}
12271
12272/**
12273 * Create a EME-PKCS1-v1_5 padded message
12274 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}
12275 * @param {Uint8Array} message - Message to be encoded
12276 * @param {Integer} keyLength - The length in octets of the key modulus
12277 * @returns {Uint8Array} EME-PKCS1 padded message.
12278 */
12279function emeEncode(message, keyLength) {
12280 const mLength = message.length;
12281 // length checking
12282 if (mLength > keyLength - 11) {
12283 throw new Error('Message too long');
12284 }
12285 // Generate an octet string PS of length k - mLen - 3 consisting of
12286 // pseudo-randomly generated nonzero octets
12287 const PS = getPKCS1Padding(keyLength - mLength - 3);
12288 // Concatenate PS, the message M, and other padding to form an
12289 // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.
12290 const encoded = new Uint8Array(keyLength);
12291 // 0x00 byte
12292 encoded[1] = 2;
12293 encoded.set(PS, 2);
12294 // 0x00 bytes
12295 encoded.set(message, keyLength - mLength);
12296 return encoded;
12297}
12298
12299/**
12300 * Decode a EME-PKCS1-v1_5 padded message
12301 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}
12302 * @param {Uint8Array} encoded - Encoded message bytes
12303 * @param {Uint8Array} randomPayload - Data to return in case of decoding error (needed for constant-time processing)
12304 * @returns {Uint8Array} decoded data or `randomPayload` (on error, if given)
12305 * @throws {Error} on decoding failure, unless `randomPayload` is provided
12306 */
12307function emeDecode(encoded, randomPayload) {
12308 // encoded format: 0x00 0x02 <PS> 0x00 <payload>
12309 let offset = 2;
12310 let separatorNotFound = 1;
12311 for (let j = offset; j < encoded.length; j++) {
12312 separatorNotFound &= encoded[j] !== 0;
12313 offset += separatorNotFound;
12314 }
12315
12316 const psLen = offset - 2;
12317 const payload = encoded.subarray(offset + 1); // discard the 0x00 separator
12318 const isValidPadding = encoded[0] === 0 & encoded[1] === 2 & psLen >= 8 & !separatorNotFound;
12319
12320 if (randomPayload) {
12321 return util.selectUint8Array(isValidPadding, payload, randomPayload);
12322 }
12323
12324 if (isValidPadding) {
12325 return payload;
12326 }
12327
12328 throw new Error('Decryption error');
12329}
12330
12331/**
12332 * Create a EMSA-PKCS1-v1_5 padded message
12333 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}
12334 * @param {Integer} algo - Hash algorithm type used
12335 * @param {Uint8Array} hashed - Message to be encoded
12336 * @param {Integer} emLen - Intended length in octets of the encoded message
12337 * @returns {Uint8Array} Encoded message.
12338 */
12339async function emsaEncode(algo, hashed, emLen) {
12340 let i;
12341 if (hashed.length !== hash.getHashByteLength(algo)) {
12342 throw new Error('Invalid hash length');
12343 }
12344 // produce an ASN.1 DER value for the hash function used.
12345 // Let T be the full hash prefix
12346 const hashPrefix = new Uint8Array(hash_headers[algo].length);
12347 for (i = 0; i < hash_headers[algo].length; i++) {
12348 hashPrefix[i] = hash_headers[algo][i];
12349 }
12350 // and let tLen be the length in octets prefix and hashed data
12351 const tLen = hashPrefix.length + hashed.length;
12352 if (emLen < tLen + 11) {
12353 throw new Error('Intended encoded message length too short');
12354 }
12355 // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF
12356 // The length of PS will be at least 8 octets
12357 const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);
12358
12359 // Concatenate PS, the hash prefix, hashed data, and other padding to form the
12360 // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed
12361 const EM = new Uint8Array(emLen);
12362 EM[1] = 0x01;
12363 EM.set(PS, 2);
12364 EM.set(hashPrefix, emLen - tLen);
12365 EM.set(hashed, emLen - hashed.length);
12366 return EM;
12367}
12368
12369var pkcs1 = /*#__PURE__*/Object.freeze({
12370 __proto__: null,
12371 emeEncode: emeEncode,
12372 emeDecode: emeDecode,
12373 emsaEncode: emsaEncode
12374});
12375
12376// GPG4Browsers - An OpenPGP implementation in javascript
12377
12378const webCrypto$5 = util.getWebCrypto();
12379const nodeCrypto$6 = util.getNodeCrypto();
12380const asn1 = nodeCrypto$6 ? void('asn1.js') : undefined;
12381
12382/* eslint-disable no-invalid-this */
12383const RSAPrivateKey = nodeCrypto$6 ? asn1.define('RSAPrivateKey', function () {
12384 this.seq().obj( // used for native NodeJS crypto
12385 this.key('version').int(), // 0
12386 this.key('modulus').int(), // n
12387 this.key('publicExponent').int(), // e
12388 this.key('privateExponent').int(), // d
12389 this.key('prime1').int(), // p
12390 this.key('prime2').int(), // q
12391 this.key('exponent1').int(), // dp
12392 this.key('exponent2').int(), // dq
12393 this.key('coefficient').int() // u
12394 );
12395}) : undefined;
12396
12397const RSAPublicKey = nodeCrypto$6 ? asn1.define('RSAPubliceKey', function () {
12398 this.seq().obj( // used for native NodeJS crypto
12399 this.key('modulus').int(), // n
12400 this.key('publicExponent').int() // e
12401 );
12402}) : undefined;
12403/* eslint-enable no-invalid-this */
12404
12405/** Create signature
12406 * @param {module:enums.hash} hashAlgo - Hash algorithm
12407 * @param {Uint8Array} data - Message
12408 * @param {Uint8Array} n - RSA public modulus
12409 * @param {Uint8Array} e - RSA public exponent
12410 * @param {Uint8Array} d - RSA private exponent
12411 * @param {Uint8Array} p - RSA private prime p
12412 * @param {Uint8Array} q - RSA private prime q
12413 * @param {Uint8Array} u - RSA private coefficient
12414 * @param {Uint8Array} hashed - Hashed message
12415 * @returns {Promise<Uint8Array>} RSA Signature.
12416 * @async
12417 */
12418async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) {
12419 if (data && !util.isStream(data)) {
12420 if (util.getWebCrypto()) {
12421 try {
12422 return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);
12423 } catch (err) {
12424 util.printDebugError(err);
12425 }
12426 } else if (util.getNodeCrypto()) {
12427 return nodeSign(hashAlgo, data, n, e, d, p, q, u);
12428 }
12429 }
12430 return bnSign(hashAlgo, n, d, hashed);
12431}
12432
12433/**
12434 * Verify signature
12435 * @param {module:enums.hash} hashAlgo - Hash algorithm
12436 * @param {Uint8Array} data - Message
12437 * @param {Uint8Array} s - Signature
12438 * @param {Uint8Array} n - RSA public modulus
12439 * @param {Uint8Array} e - RSA public exponent
12440 * @param {Uint8Array} hashed - Hashed message
12441 * @returns {Boolean}
12442 * @async
12443 */
12444async function verify(hashAlgo, data, s, n, e, hashed) {
12445 if (data && !util.isStream(data)) {
12446 if (util.getWebCrypto()) {
12447 try {
12448 return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e);
12449 } catch (err) {
12450 util.printDebugError(err);
12451 }
12452 } else if (util.getNodeCrypto()) {
12453 return nodeVerify(hashAlgo, data, s, n, e);
12454 }
12455 }
12456 return bnVerify(hashAlgo, s, n, e, hashed);
12457}
12458
12459/**
12460 * Encrypt message
12461 * @param {Uint8Array} data - Message
12462 * @param {Uint8Array} n - RSA public modulus
12463 * @param {Uint8Array} e - RSA public exponent
12464 * @returns {Promise<Uint8Array>} RSA Ciphertext.
12465 * @async
12466 */
12467async function encrypt$1(data, n, e) {
12468 if (util.getNodeCrypto()) {
12469 return nodeEncrypt$1(data, n, e);
12470 }
12471 return bnEncrypt(data, n, e);
12472}
12473
12474/**
12475 * Decrypt RSA message
12476 * @param {Uint8Array} m - Message
12477 * @param {Uint8Array} n - RSA public modulus
12478 * @param {Uint8Array} e - RSA public exponent
12479 * @param {Uint8Array} d - RSA private exponent
12480 * @param {Uint8Array} p - RSA private prime p
12481 * @param {Uint8Array} q - RSA private prime q
12482 * @param {Uint8Array} u - RSA private coefficient
12483 * @param {Uint8Array} randomPayload - Data to return on decryption error, instead of throwing
12484 * (needed for constant-time processing)
12485 * @returns {Promise<String>} RSA Plaintext.
12486 * @throws {Error} on decryption error, unless `randomPayload` is given
12487 * @async
12488 */
12489async function decrypt$1(data, n, e, d, p, q, u, randomPayload) {
12490 if (util.getNodeCrypto()) {
12491 return nodeDecrypt$1(data, n, e, d, p, q, u, randomPayload);
12492 }
12493 return bnDecrypt(data, n, e, d, p, q, u, randomPayload);
12494}
12495
12496/**
12497 * Generate a new random private key B bits long with public exponent E.
12498 *
12499 * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using
12500 * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.
12501 * @see module:crypto/public_key/prime
12502 * @param {Integer} bits - RSA bit length
12503 * @param {Integer} e - RSA public exponent
12504 * @returns {{n, e, d,
12505 * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,
12506 * RSA private prime p, RSA private prime q, u = p ** -1 mod q
12507 * @async
12508 */
12509async function generate(bits, e) {
12510 const BigInteger = await util.getBigInteger();
12511
12512 e = new BigInteger(e);
12513
12514 // Native RSA keygen using Web Crypto
12515 if (util.getWebCrypto()) {
12516 const keyGenOpt = {
12517 name: 'RSASSA-PKCS1-v1_5',
12518 modulusLength: bits, // the specified keysize in bits
12519 publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent
12520 hash: {
12521 name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'
12522 }
12523 };
12524 const keyPair = await webCrypto$5.generateKey(keyGenOpt, true, ['sign', 'verify']);
12525
12526 // export the generated keys as JsonWebKey (JWK)
12527 // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33
12528 const jwk = await webCrypto$5.exportKey('jwk', keyPair.privateKey);
12529 // map JWK parameters to corresponding OpenPGP names
12530 return {
12531 n: b64ToUint8Array(jwk.n),
12532 e: e.toUint8Array(),
12533 d: b64ToUint8Array(jwk.d),
12534 // switch p and q
12535 p: b64ToUint8Array(jwk.q),
12536 q: b64ToUint8Array(jwk.p),
12537 // Since p and q are switched in places, u is the inverse of jwk.q
12538 u: b64ToUint8Array(jwk.qi)
12539 };
12540 } else if (util.getNodeCrypto() && nodeCrypto$6.generateKeyPair && RSAPrivateKey) {
12541 const opts = {
12542 modulusLength: bits,
12543 publicExponent: e.toNumber(),
12544 publicKeyEncoding: { type: 'pkcs1', format: 'der' },
12545 privateKeyEncoding: { type: 'pkcs1', format: 'der' }
12546 };
12547 const prv = await new Promise((resolve, reject) => {
12548 nodeCrypto$6.generateKeyPair('rsa', opts, (err, _, der) => {
12549 if (err) {
12550 reject(err);
12551 } else {
12552 resolve(RSAPrivateKey.decode(der, 'der'));
12553 }
12554 });
12555 });
12556 /**
12557 * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`.
12558 * @link https://tools.ietf.org/html/rfc3447#section-3.2
12559 * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1
12560 */
12561 return {
12562 n: prv.modulus.toArrayLike(Uint8Array),
12563 e: prv.publicExponent.toArrayLike(Uint8Array),
12564 d: prv.privateExponent.toArrayLike(Uint8Array),
12565 // switch p and q
12566 p: prv.prime2.toArrayLike(Uint8Array),
12567 q: prv.prime1.toArrayLike(Uint8Array),
12568 // Since p and q are switched in places, we can keep u as defined by DER
12569 u: prv.coefficient.toArrayLike(Uint8Array)
12570 };
12571 }
12572
12573 // RSA keygen fallback using 40 iterations of the Miller-Rabin test
12574 // See https://stackoverflow.com/a/6330138 for justification
12575 // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST
12576 let p;
12577 let q;
12578 let n;
12579 do {
12580 q = await randomProbablePrime(bits - (bits >> 1), e, 40);
12581 p = await randomProbablePrime(bits >> 1, e, 40);
12582 n = p.mul(q);
12583 } while (n.bitLength() !== bits);
12584
12585 const phi = p.dec().imul(q.dec());
12586
12587 if (q.lt(p)) {
12588 [p, q] = [q, p];
12589 }
12590
12591 return {
12592 n: n.toUint8Array(),
12593 e: e.toUint8Array(),
12594 d: e.modInv(phi).toUint8Array(),
12595 p: p.toUint8Array(),
12596 q: q.toUint8Array(),
12597 // dp: d.mod(p.subn(1)),
12598 // dq: d.mod(q.subn(1)),
12599 u: p.modInv(q).toUint8Array()
12600 };
12601}
12602
12603/**
12604 * Validate RSA parameters
12605 * @param {Uint8Array} n - RSA public modulus
12606 * @param {Uint8Array} e - RSA public exponent
12607 * @param {Uint8Array} d - RSA private exponent
12608 * @param {Uint8Array} p - RSA private prime p
12609 * @param {Uint8Array} q - RSA private prime q
12610 * @param {Uint8Array} u - RSA inverse of p w.r.t. q
12611 * @returns {Promise<Boolean>} Whether params are valid.
12612 * @async
12613 */
12614async function validateParams(n, e, d, p, q, u) {
12615 const BigInteger = await util.getBigInteger();
12616 n = new BigInteger(n);
12617 p = new BigInteger(p);
12618 q = new BigInteger(q);
12619
12620 // expect pq = n
12621 if (!p.mul(q).equal(n)) {
12622 return false;
12623 }
12624
12625 const two = new BigInteger(2);
12626 // expect p*u = 1 mod q
12627 u = new BigInteger(u);
12628 if (!p.mul(u).mod(q).isOne()) {
12629 return false;
12630 }
12631
12632 e = new BigInteger(e);
12633 d = new BigInteger(d);
12634 /**
12635 * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)
12636 * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]
12637 * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]
12638 *
12639 * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)
12640 */
12641 const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3));
12642 const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q
12643 const rde = r.mul(d).mul(e);
12644
12645 const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r);
12646 if (!areInverses) {
12647 return false;
12648 }
12649
12650 return true;
12651}
12652
12653async function bnSign(hashAlgo, n, d, hashed) {
12654 const BigInteger = await util.getBigInteger();
12655 n = new BigInteger(n);
12656 const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength()));
12657 d = new BigInteger(d);
12658 if (m.gte(n)) {
12659 throw new Error('Message size cannot exceed modulus size');
12660 }
12661 return m.modExp(d, n).toUint8Array('be', n.byteLength());
12662}
12663
12664async function webSign(hashName, data, n, e, d, p, q, u) {
12665 /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.
12666 * We swap them in privateToJWK, so it usually works out, but nevertheless,
12667 * not all OpenPGP keys are compatible with this requirement.
12668 * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still
12669 * does if the underlying Web Crypto does so (though the tested implementations
12670 * don't do so).
12671 */
12672 const jwk = await privateToJWK(n, e, d, p, q, u);
12673 const algo = {
12674 name: 'RSASSA-PKCS1-v1_5',
12675 hash: { name: hashName }
12676 };
12677 const key = await webCrypto$5.importKey('jwk', jwk, algo, false, ['sign']);
12678 return new Uint8Array(await webCrypto$5.sign('RSASSA-PKCS1-v1_5', key, data));
12679}
12680
12681async function nodeSign(hashAlgo, data, n, e, d, p, q, u) {
12682 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
12683 const pBNum = new BN(p);
12684 const qBNum = new BN(q);
12685 const dBNum = new BN(d);
12686 const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)
12687 const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)
12688 const sign = nodeCrypto$6.createSign(enums.read(enums.hash, hashAlgo));
12689 sign.write(data);
12690 sign.end();
12691 const keyObject = {
12692 version: 0,
12693 modulus: new BN(n),
12694 publicExponent: new BN(e),
12695 privateExponent: new BN(d),
12696 // switch p and q
12697 prime1: new BN(q),
12698 prime2: new BN(p),
12699 // switch dp and dq
12700 exponent1: dq,
12701 exponent2: dp,
12702 coefficient: new BN(u)
12703 };
12704 if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects
12705 const der = RSAPrivateKey.encode(keyObject, 'der');
12706 return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' }));
12707 }
12708 const pem = RSAPrivateKey.encode(keyObject, 'pem', {
12709 label: 'RSA PRIVATE KEY'
12710 });
12711 return new Uint8Array(sign.sign(pem));
12712}
12713
12714async function bnVerify(hashAlgo, s, n, e, hashed) {
12715 const BigInteger = await util.getBigInteger();
12716 n = new BigInteger(n);
12717 s = new BigInteger(s);
12718 e = new BigInteger(e);
12719 if (s.gte(n)) {
12720 throw new Error('Signature size cannot exceed modulus size');
12721 }
12722 const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength());
12723 const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength());
12724 return util.equalsUint8Array(EM1, EM2);
12725}
12726
12727async function webVerify(hashName, data, s, n, e) {
12728 const jwk = publicToJWK(n, e);
12729 const key = await webCrypto$5.importKey('jwk', jwk, {
12730 name: 'RSASSA-PKCS1-v1_5',
12731 hash: { name: hashName }
12732 }, false, ['verify']);
12733 return webCrypto$5.verify('RSASSA-PKCS1-v1_5', key, s, data);
12734}
12735
12736async function nodeVerify(hashAlgo, data, s, n, e) {
12737 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
12738
12739 const verify = nodeCrypto$6.createVerify(enums.read(enums.hash, hashAlgo));
12740 verify.write(data);
12741 verify.end();
12742 const keyObject = {
12743 modulus: new BN(n),
12744 publicExponent: new BN(e)
12745 };
12746 let key;
12747 if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects
12748 const der = RSAPublicKey.encode(keyObject, 'der');
12749 key = { key: der, format: 'der', type: 'pkcs1' };
12750 } else {
12751 key = RSAPublicKey.encode(keyObject, 'pem', {
12752 label: 'RSA PUBLIC KEY'
12753 });
12754 }
12755 try {
12756 return await verify.verify(key, s);
12757 } catch (err) {
12758 return false;
12759 }
12760}
12761
12762async function nodeEncrypt$1(data, n, e) {
12763 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
12764
12765 const keyObject = {
12766 modulus: new BN(n),
12767 publicExponent: new BN(e)
12768 };
12769 let key;
12770 if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') {
12771 const der = RSAPublicKey.encode(keyObject, 'der');
12772 key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING };
12773 } else {
12774 const pem = RSAPublicKey.encode(keyObject, 'pem', {
12775 label: 'RSA PUBLIC KEY'
12776 });
12777 key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING };
12778 }
12779 return new Uint8Array(nodeCrypto$6.publicEncrypt(key, data));
12780}
12781
12782async function bnEncrypt(data, n, e) {
12783 const BigInteger = await util.getBigInteger();
12784 n = new BigInteger(n);
12785 data = new BigInteger(emeEncode(data, n.byteLength()));
12786 e = new BigInteger(e);
12787 if (data.gte(n)) {
12788 throw new Error('Message size cannot exceed modulus size');
12789 }
12790 return data.modExp(e, n).toUint8Array('be', n.byteLength());
12791}
12792
12793async function nodeDecrypt$1(data, n, e, d, p, q, u, randomPayload) {
12794 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
12795
12796 const pBNum = new BN(p);
12797 const qBNum = new BN(q);
12798 const dBNum = new BN(d);
12799 const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)
12800 const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)
12801 const keyObject = {
12802 version: 0,
12803 modulus: new BN(n),
12804 publicExponent: new BN(e),
12805 privateExponent: new BN(d),
12806 // switch p and q
12807 prime1: new BN(q),
12808 prime2: new BN(p),
12809 // switch dp and dq
12810 exponent1: dq,
12811 exponent2: dp,
12812 coefficient: new BN(u)
12813 };
12814 let key;
12815 if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') {
12816 const der = RSAPrivateKey.encode(keyObject, 'der');
12817 key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING };
12818 } else {
12819 const pem = RSAPrivateKey.encode(keyObject, 'pem', {
12820 label: 'RSA PRIVATE KEY'
12821 });
12822 key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING };
12823 }
12824 try {
12825 return new Uint8Array(nodeCrypto$6.privateDecrypt(key, data));
12826 } catch (err) {
12827 if (randomPayload) {
12828 return randomPayload;
12829 }
12830 throw new Error('Decryption error');
12831 }
12832}
12833
12834async function bnDecrypt(data, n, e, d, p, q, u, randomPayload) {
12835 const BigInteger = await util.getBigInteger();
12836 data = new BigInteger(data);
12837 n = new BigInteger(n);
12838 e = new BigInteger(e);
12839 d = new BigInteger(d);
12840 p = new BigInteger(p);
12841 q = new BigInteger(q);
12842 u = new BigInteger(u);
12843 if (data.gte(n)) {
12844 throw new Error('Data too large.');
12845 }
12846 const dq = d.mod(q.dec()); // d mod (q-1)
12847 const dp = d.mod(p.dec()); // d mod (p-1)
12848
12849 const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n);
12850 const blinder = unblinder.modInv(n).modExp(e, n);
12851 data = data.mul(blinder).mod(n);
12852
12853
12854 const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p
12855 const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q
12856 const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q)
12857
12858 let result = h.mul(p).add(mp); // result < n due to relations above
12859
12860 result = result.mul(unblinder).mod(n);
12861
12862
12863 return emeDecode(result.toUint8Array('be', n.byteLength()), randomPayload);
12864}
12865
12866/** Convert Openpgp private key params to jwk key according to
12867 * @link https://tools.ietf.org/html/rfc7517
12868 * @param {String} hashAlgo
12869 * @param {Uint8Array} n
12870 * @param {Uint8Array} e
12871 * @param {Uint8Array} d
12872 * @param {Uint8Array} p
12873 * @param {Uint8Array} q
12874 * @param {Uint8Array} u
12875 */
12876async function privateToJWK(n, e, d, p, q, u) {
12877 const BigInteger = await util.getBigInteger();
12878 const pNum = new BigInteger(p);
12879 const qNum = new BigInteger(q);
12880 const dNum = new BigInteger(d);
12881
12882 let dq = dNum.mod(qNum.dec()); // d mod (q-1)
12883 let dp = dNum.mod(pNum.dec()); // d mod (p-1)
12884 dp = dp.toUint8Array();
12885 dq = dq.toUint8Array();
12886 return {
12887 kty: 'RSA',
12888 n: uint8ArrayToB64(n, true),
12889 e: uint8ArrayToB64(e, true),
12890 d: uint8ArrayToB64(d, true),
12891 // switch p and q
12892 p: uint8ArrayToB64(q, true),
12893 q: uint8ArrayToB64(p, true),
12894 // switch dp and dq
12895 dp: uint8ArrayToB64(dq, true),
12896 dq: uint8ArrayToB64(dp, true),
12897 qi: uint8ArrayToB64(u, true),
12898 ext: true
12899 };
12900}
12901
12902/** Convert Openpgp key public params to jwk key according to
12903 * @link https://tools.ietf.org/html/rfc7517
12904 * @param {String} hashAlgo
12905 * @param {Uint8Array} n
12906 * @param {Uint8Array} e
12907 */
12908function publicToJWK(n, e) {
12909 return {
12910 kty: 'RSA',
12911 n: uint8ArrayToB64(n, true),
12912 e: uint8ArrayToB64(e, true),
12913 ext: true
12914 };
12915}
12916
12917var rsa = /*#__PURE__*/Object.freeze({
12918 __proto__: null,
12919 sign: sign,
12920 verify: verify,
12921 encrypt: encrypt$1,
12922 decrypt: decrypt$1,
12923 generate: generate,
12924 validateParams: validateParams
12925});
12926
12927// GPG4Browsers - An OpenPGP implementation in javascript
12928
12929/**
12930 * ElGamal Encryption function
12931 * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)
12932 * @param {Uint8Array} data - To be padded and encrypted
12933 * @param {Uint8Array} p
12934 * @param {Uint8Array} g
12935 * @param {Uint8Array} y
12936 * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}
12937 * @async
12938 */
12939async function encrypt$2(data, p, g, y) {
12940 const BigInteger = await util.getBigInteger();
12941 p = new BigInteger(p);
12942 g = new BigInteger(g);
12943 y = new BigInteger(y);
12944
12945 const padded = emeEncode(data, p.byteLength());
12946 const m = new BigInteger(padded);
12947
12948 // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ*
12949 // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]
12950 const k = await getRandomBigInteger(new BigInteger(1), p.dec());
12951 return {
12952 c1: g.modExp(k, p).toUint8Array(),
12953 c2: y.modExp(k, p).imul(m).imod(p).toUint8Array()
12954 };
12955}
12956
12957/**
12958 * ElGamal Encryption function
12959 * @param {Uint8Array} c1
12960 * @param {Uint8Array} c2
12961 * @param {Uint8Array} p
12962 * @param {Uint8Array} x
12963 * @param {Uint8Array} randomPayload - Data to return on unpadding error, instead of throwing
12964 * (needed for constant-time processing)
12965 * @returns {Promise<Uint8Array>} Unpadded message.
12966 * @throws {Error} on decryption error, unless `randomPayload` is given
12967 * @async
12968 */
12969async function decrypt$2(c1, c2, p, x, randomPayload) {
12970 const BigInteger = await util.getBigInteger();
12971 c1 = new BigInteger(c1);
12972 c2 = new BigInteger(c2);
12973 p = new BigInteger(p);
12974 x = new BigInteger(x);
12975
12976 const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p);
12977 return emeDecode(padded.toUint8Array('be', p.byteLength()), randomPayload);
12978}
12979
12980/**
12981 * Validate ElGamal parameters
12982 * @param {Uint8Array} p - ElGamal prime
12983 * @param {Uint8Array} g - ElGamal group generator
12984 * @param {Uint8Array} y - ElGamal public key
12985 * @param {Uint8Array} x - ElGamal private exponent
12986 * @returns {Promise<Boolean>} Whether params are valid.
12987 * @async
12988 */
12989async function validateParams$1(p, g, y, x) {
12990 const BigInteger = await util.getBigInteger();
12991 p = new BigInteger(p);
12992 g = new BigInteger(g);
12993 y = new BigInteger(y);
12994
12995 const one = new BigInteger(1);
12996 // Check that 1 < g < p
12997 if (g.lte(one) || g.gte(p)) {
12998 return false;
12999 }
13000
13001 // Expect p-1 to be large
13002 const pSize = new BigInteger(p.bitLength());
13003 const n1023 = new BigInteger(1023);
13004 if (pSize.lt(n1023)) {
13005 return false;
13006 }
13007
13008 /**
13009 * g should have order p-1
13010 * Check that g ** (p-1) = 1 mod p
13011 */
13012 if (!g.modExp(p.dec(), p).isOne()) {
13013 return false;
13014 }
13015
13016 /**
13017 * Since p-1 is not prime, g might have a smaller order that divides p-1
13018 * We want to make sure that the order is large enough to hinder a small subgroup attack
13019 *
13020 * We just check g**i != 1 for all i up to a threshold
13021 */
13022 let res = g;
13023 const i = new BigInteger(1);
13024 const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold
13025 while (i.lt(threshold)) {
13026 res = res.mul(g).imod(p);
13027 if (res.isOne()) {
13028 return false;
13029 }
13030 i.iinc();
13031 }
13032
13033 /**
13034 * Re-derive public key y' = g ** x mod p
13035 * Expect y == y'
13036 *
13037 * Blinded exponentiation computes g**{r(p-1) + x} to compare to y
13038 */
13039 x = new BigInteger(x);
13040 const two = new BigInteger(2);
13041 const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1
13042 const rqx = p.dec().imul(r).iadd(x);
13043 if (!y.equal(g.modExp(rqx, p))) {
13044 return false;
13045 }
13046
13047 return true;
13048}
13049
13050var elgamal = /*#__PURE__*/Object.freeze({
13051 __proto__: null,
13052 encrypt: encrypt$2,
13053 decrypt: decrypt$2,
13054 validateParams: validateParams$1
13055});
13056
13057// OpenPGP.js - An OpenPGP implementation in javascript
13058
13059class OID {
13060 constructor(oid) {
13061 if (oid instanceof OID) {
13062 this.oid = oid.oid;
13063 } else if (util.isArray(oid) ||
13064 util.isUint8Array(oid)) {
13065 oid = new Uint8Array(oid);
13066 if (oid[0] === 0x06) { // DER encoded oid byte array
13067 if (oid[1] !== oid.length - 2) {
13068 throw new Error('Length mismatch in DER encoded oid');
13069 }
13070 oid = oid.subarray(2);
13071 }
13072 this.oid = oid;
13073 } else {
13074 this.oid = '';
13075 }
13076 }
13077
13078 /**
13079 * Method to read an OID object
13080 * @param {Uint8Array} input - Where to read the OID from
13081 * @returns {Number} Number of read bytes.
13082 */
13083 read(input) {
13084 if (input.length >= 1) {
13085 const length = input[0];
13086 if (input.length >= 1 + length) {
13087 this.oid = input.subarray(1, 1 + length);
13088 return 1 + this.oid.length;
13089 }
13090 }
13091 throw new Error('Invalid oid');
13092 }
13093
13094 /**
13095 * Serialize an OID object
13096 * @returns {Uint8Array} Array with the serialized value the OID.
13097 */
13098 write() {
13099 return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);
13100 }
13101
13102 /**
13103 * Serialize an OID object as a hex string
13104 * @returns {string} String with the hex value of the OID.
13105 */
13106 toHex() {
13107 return util.uint8ArrayToHex(this.oid);
13108 }
13109
13110 /**
13111 * If a known curve object identifier, return the canonical name of the curve
13112 * @returns {string} String with the canonical name of the curve.
13113 */
13114 getName() {
13115 const hex = this.toHex();
13116 if (enums.curve[hex]) {
13117 return enums.write(enums.curve, hex);
13118 } else {
13119 throw new Error('Unknown curve object identifier.');
13120 }
13121 }
13122}
13123
13124// OpenPGP.js - An OpenPGP implementation in javascript
13125
13126function keyFromPrivate(indutnyCurve, priv) {
13127 const keyPair = indutnyCurve.keyPair({ priv: priv });
13128 return keyPair;
13129}
13130
13131function keyFromPublic(indutnyCurve, pub) {
13132 const keyPair = indutnyCurve.keyPair({ pub: pub });
13133 if (keyPair.validate().result !== true) {
13134 throw new Error('Invalid elliptic public key');
13135 }
13136 return keyPair;
13137}
13138
13139async function getIndutnyCurve(name) {
13140 if (!config.useIndutnyElliptic) {
13141 throw new Error('This curve is only supported in the full build of OpenPGP.js');
13142 }
13143 const { default: elliptic } = await Promise.resolve().then(function () { return elliptic$1; });
13144 return new elliptic.ec(name);
13145}
13146
13147// GPG4Browsers - An OpenPGP implementation in javascript
13148
13149function readSimpleLength(bytes) {
13150 let len = 0;
13151 let offset;
13152 const type = bytes[0];
13153
13154
13155 if (type < 192) {
13156 [len] = bytes;
13157 offset = 1;
13158 } else if (type < 255) {
13159 len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;
13160 offset = 2;
13161 } else if (type === 255) {
13162 len = util.readNumber(bytes.subarray(1, 1 + 4));
13163 offset = 5;
13164 }
13165
13166 return {
13167 len: len,
13168 offset: offset
13169 };
13170}
13171
13172/**
13173 * Encodes a given integer of length to the openpgp length specifier to a
13174 * string
13175 *
13176 * @param {Integer} length - The length to encode
13177 * @returns {Uint8Array} String with openpgp length representation.
13178 */
13179function writeSimpleLength(length) {
13180 if (length < 192) {
13181 return new Uint8Array([length]);
13182 } else if (length > 191 && length < 8384) {
13183 /*
13184 * let a = (total data packet length) - 192 let bc = two octet
13185 * representation of a let d = b + 192
13186 */
13187 return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);
13188 }
13189 return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);
13190}
13191
13192function writePartialLength(power) {
13193 if (power < 0 || power > 30) {
13194 throw new Error('Partial Length power must be between 1 and 30');
13195 }
13196 return new Uint8Array([224 + power]);
13197}
13198
13199function writeTag(tag_type) {
13200 /* we're only generating v4 packet headers here */
13201 return new Uint8Array([0xC0 | tag_type]);
13202}
13203
13204/**
13205 * Writes a packet header version 4 with the given tag_type and length to a
13206 * string
13207 *
13208 * @param {Integer} tag_type - Tag type
13209 * @param {Integer} length - Length of the payload
13210 * @returns {String} String of the header.
13211 */
13212function writeHeader(tag_type, length) {
13213 /* we're only generating v4 packet headers here */
13214 return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);
13215}
13216
13217/**
13218 * Whether the packet type supports partial lengths per RFC4880
13219 * @param {Integer} tag - Tag type
13220 * @returns {Boolean} String of the header.
13221 */
13222function supportsStreaming(tag) {
13223 return [
13224 enums.packet.literalData,
13225 enums.packet.compressedData,
13226 enums.packet.symmetricallyEncryptedData,
13227 enums.packet.symEncryptedIntegrityProtectedData,
13228 enums.packet.aeadEncryptedData
13229 ].includes(tag);
13230}
13231
13232/**
13233 * Generic static Packet Parser function
13234 *
13235 * @param {Uint8Array | ReadableStream<Uint8Array>} input - Input stream as string
13236 * @param {Function} callback - Function to call with the parsed packet
13237 * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.
13238 */
13239async function readPackets(input, callback) {
13240 const reader = getReader(input);
13241 let writer;
13242 let callbackReturned;
13243 try {
13244 const peekedBytes = await reader.peekBytes(2);
13245 // some sanity checks
13246 if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {
13247 throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');
13248 }
13249 const headerByte = await reader.readByte();
13250 let tag = -1;
13251 let format = -1;
13252 let packetLength;
13253
13254 format = 0; // 0 = old format; 1 = new format
13255 if ((headerByte & 0x40) !== 0) {
13256 format = 1;
13257 }
13258
13259 let packetLengthType;
13260 if (format) {
13261 // new format header
13262 tag = headerByte & 0x3F; // bit 5-0
13263 } else {
13264 // old format header
13265 tag = (headerByte & 0x3F) >> 2; // bit 5-2
13266 packetLengthType = headerByte & 0x03; // bit 1-0
13267 }
13268
13269 const packetSupportsStreaming = supportsStreaming(tag);
13270 let packet = null;
13271 if (packetSupportsStreaming) {
13272 if (util.isStream(input) === 'array') {
13273 const arrayStream = new ArrayStream();
13274 writer = getWriter(arrayStream);
13275 packet = arrayStream;
13276 } else {
13277 const transform = new TransformStream();
13278 writer = getWriter(transform.writable);
13279 packet = transform.readable;
13280 }
13281 // eslint-disable-next-line callback-return
13282 callbackReturned = callback({ tag, packet });
13283 } else {
13284 packet = [];
13285 }
13286
13287 let wasPartialLength;
13288 do {
13289 if (!format) {
13290 // 4.2.1. Old Format Packet Lengths
13291 switch (packetLengthType) {
13292 case 0:
13293 // The packet has a one-octet length. The header is 2 octets
13294 // long.
13295 packetLength = await reader.readByte();
13296 break;
13297 case 1:
13298 // The packet has a two-octet length. The header is 3 octets
13299 // long.
13300 packetLength = (await reader.readByte() << 8) | await reader.readByte();
13301 break;
13302 case 2:
13303 // The packet has a four-octet length. The header is 5
13304 // octets long.
13305 packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<
13306 8) | await reader.readByte();
13307 break;
13308 default:
13309 // 3 - The packet is of indeterminate length. The header is 1
13310 // octet long, and the implementation must determine how long
13311 // the packet is. If the packet is in a file, this means that
13312 // the packet extends until the end of the file. In general,
13313 // an implementation SHOULD NOT use indeterminate-length
13314 // packets except where the end of the data will be clear
13315 // from the context, and even then it is better to use a
13316 // definite length, or a new format header. The new format
13317 // headers described below have a mechanism for precisely
13318 // encoding data of indeterminate length.
13319 packetLength = Infinity;
13320 break;
13321 }
13322 } else { // 4.2.2. New Format Packet Lengths
13323 // 4.2.2.1. One-Octet Lengths
13324 const lengthByte = await reader.readByte();
13325 wasPartialLength = false;
13326 if (lengthByte < 192) {
13327 packetLength = lengthByte;
13328 // 4.2.2.2. Two-Octet Lengths
13329 } else if (lengthByte >= 192 && lengthByte < 224) {
13330 packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;
13331 // 4.2.2.4. Partial Body Lengths
13332 } else if (lengthByte > 223 && lengthByte < 255) {
13333 packetLength = 1 << (lengthByte & 0x1F);
13334 wasPartialLength = true;
13335 if (!packetSupportsStreaming) {
13336 throw new TypeError('This packet type does not support partial lengths.');
13337 }
13338 // 4.2.2.3. Five-Octet Lengths
13339 } else {
13340 packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<
13341 8) | await reader.readByte();
13342 }
13343 }
13344 if (packetLength > 0) {
13345 let bytesRead = 0;
13346 while (true) {
13347 if (writer) await writer.ready;
13348 const { done, value } = await reader.read();
13349 if (done) {
13350 if (packetLength === Infinity) break;
13351 throw new Error('Unexpected end of packet');
13352 }
13353 const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);
13354 if (writer) await writer.write(chunk);
13355 else packet.push(chunk);
13356 bytesRead += value.length;
13357 if (bytesRead >= packetLength) {
13358 reader.unshift(value.subarray(packetLength - bytesRead + value.length));
13359 break;
13360 }
13361 }
13362 }
13363 } while (wasPartialLength);
13364
13365 // If this was not a packet that "supports streaming", we peek to check
13366 // whether it is the last packet in the message. We peek 2 bytes instead
13367 // of 1 because the beginning of this function also peeks 2 bytes, and we
13368 // want to cut a `subarray` of the correct length into `web-stream-tools`'
13369 // `externalBuffer` as a tiny optimization here.
13370 //
13371 // If it *was* a streaming packet (i.e. the data packets), we peek at the
13372 // entire remainder of the stream, in order to forward errors in the
13373 // remainder of the stream to the packet data. (Note that this means we
13374 // read/peek at all signature packets before closing the literal data
13375 // packet, for example.) This forwards MDC errors to the literal data
13376 // stream, for example, so that they don't get lost / forgotten on
13377 // decryptedMessage.packets.stream, which we never look at.
13378 //
13379 // An example of what we do when stream-parsing a message containing
13380 // [ one-pass signature packet, literal data packet, signature packet ]:
13381 // 1. Read the one-pass signature packet
13382 // 2. Peek 2 bytes of the literal data packet
13383 // 3. Parse the one-pass signature packet
13384 //
13385 // 4. Read the literal data packet, simultaneously stream-parsing it
13386 // 5. Peek until the end of the message
13387 // 6. Finish parsing the literal data packet
13388 //
13389 // 7. Read the signature packet again (we already peeked at it in step 5)
13390 // 8. Peek at the end of the stream again (`peekBytes` returns undefined)
13391 // 9. Parse the signature packet
13392 //
13393 // Note that this means that if there's an error in the very end of the
13394 // stream, such as an MDC error, we throw in step 5 instead of in step 8
13395 // (or never), which is the point of this exercise.
13396 const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);
13397 if (writer) {
13398 await writer.ready;
13399 await writer.close();
13400 } else {
13401 packet = util.concatUint8Array(packet);
13402 // eslint-disable-next-line callback-return
13403 await callback({ tag, packet });
13404 }
13405 return !nextPacket || !nextPacket.length;
13406 } catch (e) {
13407 if (writer) {
13408 await writer.abort(e);
13409 return true;
13410 } else {
13411 throw e;
13412 }
13413 } finally {
13414 if (writer) {
13415 await callbackReturned;
13416 }
13417 reader.releaseLock();
13418 }
13419}
13420
13421class UnsupportedError extends Error {
13422 constructor(...params) {
13423 super(...params);
13424
13425 if (Error.captureStackTrace) {
13426 Error.captureStackTrace(this, UnsupportedError);
13427 }
13428
13429 this.name = 'UnsupportedError';
13430 }
13431}
13432
13433class UnparseablePacket {
13434 constructor(tag, rawContent) {
13435 this.tag = tag;
13436 this.rawContent = rawContent;
13437 }
13438
13439 write() {
13440 return this.rawContent;
13441 }
13442}
13443
13444// OpenPGP.js - An OpenPGP implementation in javascript
13445
13446const webCrypto$6 = util.getWebCrypto();
13447const nodeCrypto$7 = util.getNodeCrypto();
13448
13449const webCurves = {
13450 'p256': 'P-256',
13451 'p384': 'P-384',
13452 'p521': 'P-521'
13453};
13454const knownCurves = nodeCrypto$7 ? nodeCrypto$7.getCurves() : [];
13455const nodeCurves = nodeCrypto$7 ? {
13456 secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,
13457 p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,
13458 p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,
13459 p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,
13460 ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined,
13461 curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined,
13462 brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,
13463 brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,
13464 brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined
13465} : {};
13466
13467const curves = {
13468 p256: {
13469 oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],
13470 keyType: enums.publicKey.ecdsa,
13471 hash: enums.hash.sha256,
13472 cipher: enums.symmetric.aes128,
13473 node: nodeCurves.p256,
13474 web: webCurves.p256,
13475 payloadSize: 32,
13476 sharedSize: 256
13477 },
13478 p384: {
13479 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],
13480 keyType: enums.publicKey.ecdsa,
13481 hash: enums.hash.sha384,
13482 cipher: enums.symmetric.aes192,
13483 node: nodeCurves.p384,
13484 web: webCurves.p384,
13485 payloadSize: 48,
13486 sharedSize: 384
13487 },
13488 p521: {
13489 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],
13490 keyType: enums.publicKey.ecdsa,
13491 hash: enums.hash.sha512,
13492 cipher: enums.symmetric.aes256,
13493 node: nodeCurves.p521,
13494 web: webCurves.p521,
13495 payloadSize: 66,
13496 sharedSize: 528
13497 },
13498 secp256k1: {
13499 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],
13500 keyType: enums.publicKey.ecdsa,
13501 hash: enums.hash.sha256,
13502 cipher: enums.symmetric.aes128,
13503 node: nodeCurves.secp256k1,
13504 payloadSize: 32
13505 },
13506 ed25519: {
13507 oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],
13508 keyType: enums.publicKey.eddsaLegacy,
13509 hash: enums.hash.sha512,
13510 node: false, // nodeCurves.ed25519 TODO
13511 payloadSize: 32
13512 },
13513 curve25519: {
13514 oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],
13515 keyType: enums.publicKey.ecdh,
13516 hash: enums.hash.sha256,
13517 cipher: enums.symmetric.aes128,
13518 node: false, // nodeCurves.curve25519 TODO
13519 payloadSize: 32
13520 },
13521 brainpoolP256r1: {
13522 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],
13523 keyType: enums.publicKey.ecdsa,
13524 hash: enums.hash.sha256,
13525 cipher: enums.symmetric.aes128,
13526 node: nodeCurves.brainpoolP256r1,
13527 payloadSize: 32
13528 },
13529 brainpoolP384r1: {
13530 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],
13531 keyType: enums.publicKey.ecdsa,
13532 hash: enums.hash.sha384,
13533 cipher: enums.symmetric.aes192,
13534 node: nodeCurves.brainpoolP384r1,
13535 payloadSize: 48
13536 },
13537 brainpoolP512r1: {
13538 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],
13539 keyType: enums.publicKey.ecdsa,
13540 hash: enums.hash.sha512,
13541 cipher: enums.symmetric.aes256,
13542 node: nodeCurves.brainpoolP512r1,
13543 payloadSize: 64
13544 }
13545};
13546
13547class CurveWithOID {
13548 constructor(oidOrName, params) {
13549 try {
13550 if (util.isArray(oidOrName) ||
13551 util.isUint8Array(oidOrName)) {
13552 // by oid byte array
13553 oidOrName = new OID(oidOrName);
13554 }
13555 if (oidOrName instanceof OID) {
13556 // by curve OID
13557 oidOrName = oidOrName.getName();
13558 }
13559 // by curve name or oid string
13560 this.name = enums.write(enums.curve, oidOrName);
13561 } catch (err) {
13562 throw new UnsupportedError('Unknown curve');
13563 }
13564 params = params || curves[this.name];
13565
13566 this.keyType = params.keyType;
13567
13568 this.oid = params.oid;
13569 this.hash = params.hash;
13570 this.cipher = params.cipher;
13571 this.node = params.node && curves[this.name];
13572 this.web = params.web && curves[this.name];
13573 this.payloadSize = params.payloadSize;
13574 if (this.web && util.getWebCrypto()) {
13575 this.type = 'web';
13576 } else if (this.node && util.getNodeCrypto()) {
13577 this.type = 'node';
13578 } else if (this.name === 'curve25519') {
13579 this.type = 'curve25519';
13580 } else if (this.name === 'ed25519') {
13581 this.type = 'ed25519';
13582 }
13583 }
13584
13585 async genKeyPair() {
13586 let keyPair;
13587 switch (this.type) {
13588 case 'web':
13589 try {
13590 return await webGenKeyPair(this.name);
13591 } catch (err) {
13592 util.printDebugError('Browser did not support generating ec key ' + err.message);
13593 break;
13594 }
13595 case 'node':
13596 return nodeGenKeyPair(this.name);
13597 case 'curve25519': {
13598 const privateKey = getRandomBytes(32);
13599 privateKey[0] = (privateKey[0] & 127) | 64;
13600 privateKey[31] &= 248;
13601 const secretKey = privateKey.slice().reverse();
13602 keyPair = naclFastLight.box.keyPair.fromSecretKey(secretKey);
13603 const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);
13604 return { publicKey, privateKey };
13605 }
13606 case 'ed25519': {
13607 const privateKey = getRandomBytes(32);
13608 const keyPair = naclFastLight.sign.keyPair.fromSeed(privateKey);
13609 const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);
13610 return { publicKey, privateKey };
13611 }
13612 }
13613 const indutnyCurve = await getIndutnyCurve(this.name);
13614 keyPair = await indutnyCurve.genKeyPair({
13615 entropy: util.uint8ArrayToString(getRandomBytes(32))
13616 });
13617 return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) };
13618 }
13619}
13620
13621async function generate$1(curve) {
13622 const BigInteger = await util.getBigInteger();
13623
13624 curve = new CurveWithOID(curve);
13625 const keyPair = await curve.genKeyPair();
13626 const Q = new BigInteger(keyPair.publicKey).toUint8Array();
13627 const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize);
13628 return {
13629 oid: curve.oid,
13630 Q,
13631 secret,
13632 hash: curve.hash,
13633 cipher: curve.cipher
13634 };
13635}
13636
13637/**
13638 * Get preferred hash algo to use with the given curve
13639 * @param {module:type/oid} oid - curve oid
13640 * @returns {enums.hash} hash algorithm
13641 */
13642function getPreferredHashAlgo(oid) {
13643 return curves[enums.write(enums.curve, oid.toHex())].hash;
13644}
13645
13646/**
13647 * Validate ECDH and ECDSA parameters
13648 * Not suitable for EdDSA (different secret key format)
13649 * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves
13650 * @param {module:type/oid} oid - EC object identifier
13651 * @param {Uint8Array} Q - EC public point
13652 * @param {Uint8Array} d - EC secret scalar
13653 * @returns {Promise<Boolean>} Whether params are valid.
13654 * @async
13655 */
13656async function validateStandardParams(algo, oid, Q, d) {
13657 const supportedCurves = {
13658 p256: true,
13659 p384: true,
13660 p521: true,
13661 secp256k1: true,
13662 curve25519: algo === enums.publicKey.ecdh,
13663 brainpoolP256r1: true,
13664 brainpoolP384r1: true,
13665 brainpoolP512r1: true
13666 };
13667
13668 // Check whether the given curve is supported
13669 const curveName = oid.getName();
13670 if (!supportedCurves[curveName]) {
13671 return false;
13672 }
13673
13674 if (curveName === 'curve25519') {
13675 d = d.slice().reverse();
13676 // Re-derive public point Q'
13677 const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(d);
13678
13679 Q = new Uint8Array(Q);
13680 const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix
13681 if (!util.equalsUint8Array(dG, Q)) {
13682 return false;
13683 }
13684
13685 return true;
13686 }
13687
13688 const curve = await getIndutnyCurve(curveName);
13689 try {
13690 // Parse Q and check that it is on the curve but not at infinity
13691 Q = keyFromPublic(curve, Q).getPublic();
13692 } catch (validationErrors) {
13693 return false;
13694 }
13695
13696 /**
13697 * Re-derive public point Q' = dG from private key
13698 * Expect Q == Q'
13699 */
13700 const dG = keyFromPrivate(curve, d).getPublic();
13701 if (!dG.eq(Q)) {
13702 return false;
13703 }
13704
13705 return true;
13706}
13707
13708//////////////////////////
13709// //
13710// Helper functions //
13711// //
13712//////////////////////////
13713
13714
13715async function webGenKeyPair(name) {
13716 // Note: keys generated with ECDSA and ECDH are structurally equivalent
13717 const webCryptoKey = await webCrypto$6.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);
13718
13719 const privateKey = await webCrypto$6.exportKey('jwk', webCryptoKey.privateKey);
13720 const publicKey = await webCrypto$6.exportKey('jwk', webCryptoKey.publicKey);
13721
13722 return {
13723 publicKey: jwkToRawPublic(publicKey),
13724 privateKey: b64ToUint8Array(privateKey.d)
13725 };
13726}
13727
13728async function nodeGenKeyPair(name) {
13729 // Note: ECDSA and ECDH key generation is structurally equivalent
13730 const ecdh = nodeCrypto$7.createECDH(nodeCurves[name]);
13731 await ecdh.generateKeys();
13732 return {
13733 publicKey: new Uint8Array(ecdh.getPublicKey()),
13734 privateKey: new Uint8Array(ecdh.getPrivateKey())
13735 };
13736}
13737
13738//////////////////////////
13739// //
13740// Helper functions //
13741// //
13742//////////////////////////
13743
13744/**
13745 * @param {JsonWebKey} jwk - key for conversion
13746 *
13747 * @returns {Uint8Array} Raw public key.
13748 */
13749function jwkToRawPublic(jwk) {
13750 const bufX = b64ToUint8Array(jwk.x);
13751 const bufY = b64ToUint8Array(jwk.y);
13752 const publicKey = new Uint8Array(bufX.length + bufY.length + 1);
13753 publicKey[0] = 0x04;
13754 publicKey.set(bufX, 1);
13755 publicKey.set(bufY, bufX.length + 1);
13756 return publicKey;
13757}
13758
13759/**
13760 * @param {Integer} payloadSize - ec payload size
13761 * @param {String} name - curve name
13762 * @param {Uint8Array} publicKey - public key
13763 *
13764 * @returns {JsonWebKey} Public key in jwk format.
13765 */
13766function rawPublicToJWK(payloadSize, name, publicKey) {
13767 const len = payloadSize;
13768 const bufX = publicKey.slice(1, len + 1);
13769 const bufY = publicKey.slice(len + 1, len * 2 + 1);
13770 // https://www.rfc-editor.org/rfc/rfc7518.txt
13771 const jwk = {
13772 kty: 'EC',
13773 crv: name,
13774 x: uint8ArrayToB64(bufX, true),
13775 y: uint8ArrayToB64(bufY, true),
13776 ext: true
13777 };
13778 return jwk;
13779}
13780
13781/**
13782 * @param {Integer} payloadSize - ec payload size
13783 * @param {String} name - curve name
13784 * @param {Uint8Array} publicKey - public key
13785 * @param {Uint8Array} privateKey - private key
13786 *
13787 * @returns {JsonWebKey} Private key in jwk format.
13788 */
13789function privateToJWK$1(payloadSize, name, publicKey, privateKey) {
13790 const jwk = rawPublicToJWK(payloadSize, name, publicKey);
13791 jwk.d = uint8ArrayToB64(privateKey, true);
13792 return jwk;
13793}
13794
13795// OpenPGP.js - An OpenPGP implementation in javascript
13796
13797const webCrypto$7 = util.getWebCrypto();
13798const nodeCrypto$8 = util.getNodeCrypto();
13799
13800/**
13801 * Sign a message using the provided key
13802 * @param {module:type/oid} oid - Elliptic curve object identifier
13803 * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign
13804 * @param {Uint8Array} message - Message to sign
13805 * @param {Uint8Array} publicKey - Public key
13806 * @param {Uint8Array} privateKey - Private key used to sign the message
13807 * @param {Uint8Array} hashed - The hashed message
13808 * @returns {Promise<{
13809 * r: Uint8Array,
13810 * s: Uint8Array
13811 * }>} Signature of the message
13812 * @async
13813 */
13814async function sign$1(oid, hashAlgo, message, publicKey, privateKey, hashed) {
13815 const curve = new CurveWithOID(oid);
13816 if (message && !util.isStream(message)) {
13817 const keyPair = { publicKey, privateKey };
13818 switch (curve.type) {
13819 case 'web': {
13820 // If browser doesn't support a curve, we'll catch it
13821 try {
13822 // Need to await to make sure browser succeeds
13823 return await webSign$1(curve, hashAlgo, message, keyPair);
13824 } catch (err) {
13825 // We do not fallback if the error is related to key integrity
13826 // Unfortunaley Safari does not support p521 and throws a DataError when using it
13827 // So we need to always fallback for that curve
13828 if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {
13829 throw err;
13830 }
13831 util.printDebugError('Browser did not support signing: ' + err.message);
13832 }
13833 break;
13834 }
13835 case 'node': {
13836 const signature = await nodeSign$1(curve, hashAlgo, message, keyPair);
13837 return {
13838 r: signature.r.toArrayLike(Uint8Array),
13839 s: signature.s.toArrayLike(Uint8Array)
13840 };
13841 }
13842 }
13843 }
13844 return ellipticSign(curve, hashed, privateKey);
13845}
13846
13847/**
13848 * Verifies if a signature is valid for a message
13849 * @param {module:type/oid} oid - Elliptic curve object identifier
13850 * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature
13851 * @param {{r: Uint8Array,
13852 s: Uint8Array}} signature Signature to verify
13853 * @param {Uint8Array} message - Message to verify
13854 * @param {Uint8Array} publicKey - Public key used to verify the message
13855 * @param {Uint8Array} hashed - The hashed message
13856 * @returns {Boolean}
13857 * @async
13858 */
13859async function verify$1(oid, hashAlgo, signature, message, publicKey, hashed) {
13860 const curve = new CurveWithOID(oid);
13861 if (message && !util.isStream(message)) {
13862 switch (curve.type) {
13863 case 'web':
13864 try {
13865 // Need to await to make sure browser succeeds
13866 return await webVerify$1(curve, hashAlgo, signature, message, publicKey);
13867 } catch (err) {
13868 // We do not fallback if the error is related to key integrity
13869 // Unfortunately Safari does not support p521 and throws a DataError when using it
13870 // So we need to always fallback for that curve
13871 if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {
13872 throw err;
13873 }
13874 util.printDebugError('Browser did not support verifying: ' + err.message);
13875 }
13876 break;
13877 case 'node':
13878 return nodeVerify$1(curve, hashAlgo, signature, message, publicKey);
13879 }
13880 }
13881 const digest = (typeof hashAlgo === 'undefined') ? message : hashed;
13882 return ellipticVerify(curve, signature, digest, publicKey);
13883}
13884
13885/**
13886 * Validate ECDSA parameters
13887 * @param {module:type/oid} oid - Elliptic curve object identifier
13888 * @param {Uint8Array} Q - ECDSA public point
13889 * @param {Uint8Array} d - ECDSA secret scalar
13890 * @returns {Promise<Boolean>} Whether params are valid.
13891 * @async
13892 */
13893async function validateParams$2(oid, Q, d) {
13894 const curve = new CurveWithOID(oid);
13895 // Reject curves x25519 and ed25519
13896 if (curve.keyType !== enums.publicKey.ecdsa) {
13897 return false;
13898 }
13899
13900 // To speed up the validation, we try to use node- or webcrypto when available
13901 // and sign + verify a random message
13902 switch (curve.type) {
13903 case 'web':
13904 case 'node': {
13905 const message = getRandomBytes(8);
13906 const hashAlgo = enums.hash.sha256;
13907 const hashed = await hash.digest(hashAlgo, message);
13908 try {
13909 const signature = await sign$1(oid, hashAlgo, message, Q, d, hashed);
13910 return await verify$1(oid, hashAlgo, signature, message, Q, hashed);
13911 } catch (err) {
13912 return false;
13913 }
13914 }
13915 default:
13916 return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);
13917 }
13918}
13919
13920
13921//////////////////////////
13922// //
13923// Helper functions //
13924// //
13925//////////////////////////
13926
13927async function ellipticSign(curve, hashed, privateKey) {
13928 const indutnyCurve = await getIndutnyCurve(curve.name);
13929 const key = keyFromPrivate(indutnyCurve, privateKey);
13930 const signature = key.sign(hashed);
13931 return {
13932 r: signature.r.toArrayLike(Uint8Array),
13933 s: signature.s.toArrayLike(Uint8Array)
13934 };
13935}
13936
13937async function ellipticVerify(curve, signature, digest, publicKey) {
13938 const indutnyCurve = await getIndutnyCurve(curve.name);
13939 const key = keyFromPublic(indutnyCurve, publicKey);
13940 return key.verify(digest, signature);
13941}
13942
13943async function webSign$1(curve, hashAlgo, message, keyPair) {
13944 const len = curve.payloadSize;
13945 const jwk = privateToJWK$1(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);
13946 const key = await webCrypto$7.importKey(
13947 'jwk',
13948 jwk,
13949 {
13950 'name': 'ECDSA',
13951 'namedCurve': webCurves[curve.name],
13952 'hash': { name: enums.read(enums.webHash, curve.hash) }
13953 },
13954 false,
13955 ['sign']
13956 );
13957
13958 const signature = new Uint8Array(await webCrypto$7.sign(
13959 {
13960 'name': 'ECDSA',
13961 'namedCurve': webCurves[curve.name],
13962 'hash': { name: enums.read(enums.webHash, hashAlgo) }
13963 },
13964 key,
13965 message
13966 ));
13967
13968 return {
13969 r: signature.slice(0, len),
13970 s: signature.slice(len, len << 1)
13971 };
13972}
13973
13974async function webVerify$1(curve, hashAlgo, { r, s }, message, publicKey) {
13975 const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);
13976 const key = await webCrypto$7.importKey(
13977 'jwk',
13978 jwk,
13979 {
13980 'name': 'ECDSA',
13981 'namedCurve': webCurves[curve.name],
13982 'hash': { name: enums.read(enums.webHash, curve.hash) }
13983 },
13984 false,
13985 ['verify']
13986 );
13987
13988 const signature = util.concatUint8Array([r, s]).buffer;
13989
13990 return webCrypto$7.verify(
13991 {
13992 'name': 'ECDSA',
13993 'namedCurve': webCurves[curve.name],
13994 'hash': { name: enums.read(enums.webHash, hashAlgo) }
13995 },
13996 key,
13997 signature,
13998 message
13999 );
14000}
14001
14002async function nodeSign$1(curve, hashAlgo, message, keyPair) {
14003 const sign = nodeCrypto$8.createSign(enums.read(enums.hash, hashAlgo));
14004 sign.write(message);
14005 sign.end();
14006 const key = ECPrivateKey.encode({
14007 version: 1,
14008 parameters: curve.oid,
14009 privateKey: Array.from(keyPair.privateKey),
14010 publicKey: { unused: 0, data: Array.from(keyPair.publicKey) }
14011 }, 'pem', {
14012 label: 'EC PRIVATE KEY'
14013 });
14014
14015 return ECDSASignature.decode(sign.sign(key), 'der');
14016}
14017
14018async function nodeVerify$1(curve, hashAlgo, { r, s }, message, publicKey) {
14019 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
14020
14021 const verify = nodeCrypto$8.createVerify(enums.read(enums.hash, hashAlgo));
14022 verify.write(message);
14023 verify.end();
14024 const key = SubjectPublicKeyInfo.encode({
14025 algorithm: {
14026 algorithm: [1, 2, 840, 10045, 2, 1],
14027 parameters: curve.oid
14028 },
14029 subjectPublicKey: { unused: 0, data: Array.from(publicKey) }
14030 }, 'pem', {
14031 label: 'PUBLIC KEY'
14032 });
14033 const signature = ECDSASignature.encode({
14034 r: new BN(r), s: new BN(s)
14035 }, 'der');
14036
14037 try {
14038 return verify.verify(key, signature);
14039 } catch (err) {
14040 return false;
14041 }
14042}
14043
14044// Originally written by Owen Smith https://github.com/omsmith
14045// Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/
14046
14047/* eslint-disable no-invalid-this */
14048
14049const asn1$1 = nodeCrypto$8 ? void('asn1.js') : undefined;
14050
14051const ECDSASignature = nodeCrypto$8 ?
14052 asn1$1.define('ECDSASignature', function() {
14053 this.seq().obj(
14054 this.key('r').int(),
14055 this.key('s').int()
14056 );
14057 }) : undefined;
14058
14059const ECPrivateKey = nodeCrypto$8 ?
14060 asn1$1.define('ECPrivateKey', function() {
14061 this.seq().obj(
14062 this.key('version').int(),
14063 this.key('privateKey').octstr(),
14064 this.key('parameters').explicit(0).optional().any(),
14065 this.key('publicKey').explicit(1).optional().bitstr()
14066 );
14067 }) : undefined;
14068
14069const AlgorithmIdentifier = nodeCrypto$8 ?
14070 asn1$1.define('AlgorithmIdentifier', function() {
14071 this.seq().obj(
14072 this.key('algorithm').objid(),
14073 this.key('parameters').optional().any()
14074 );
14075 }) : undefined;
14076
14077const SubjectPublicKeyInfo = nodeCrypto$8 ?
14078 asn1$1.define('SubjectPublicKeyInfo', function() {
14079 this.seq().obj(
14080 this.key('algorithm').use(AlgorithmIdentifier),
14081 this.key('subjectPublicKey').bitstr()
14082 );
14083 }) : undefined;
14084
14085var ecdsa = /*#__PURE__*/Object.freeze({
14086 __proto__: null,
14087 sign: sign$1,
14088 verify: verify$1,
14089 validateParams: validateParams$2
14090});
14091
14092// OpenPGP.js - An OpenPGP implementation in javascript
14093
14094naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest());
14095
14096/**
14097 * Sign a message using the provided legacy EdDSA key
14098 * @param {module:type/oid} oid - Elliptic curve object identifier
14099 * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)
14100 * @param {Uint8Array} message - Message to sign
14101 * @param {Uint8Array} publicKey - Public key
14102 * @param {Uint8Array} privateKey - Private key used to sign the message
14103 * @param {Uint8Array} hashed - The hashed message
14104 * @returns {Promise<{
14105 * r: Uint8Array,
14106 * s: Uint8Array
14107 * }>} Signature of the message
14108 * @async
14109 */
14110async function sign$2(oid, hashAlgo, message, publicKey, privateKey, hashed) {
14111 if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {
14112 // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2
14113 throw new Error('Hash algorithm too weak for EdDSA.');
14114 }
14115 const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]);
14116 const signature = naclFastLight.sign.detached(hashed, secretKey);
14117 // EdDSA signature params are returned in little-endian format
14118 return {
14119 r: signature.subarray(0, 32),
14120 s: signature.subarray(32)
14121 };
14122}
14123
14124/**
14125 * Verifies if a legacy EdDSA signature is valid for a message
14126 * @param {module:type/oid} oid - Elliptic curve object identifier
14127 * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature
14128 * @param {{r: Uint8Array,
14129 s: Uint8Array}} signature Signature to verify the message
14130 * @param {Uint8Array} m - Message to verify
14131 * @param {Uint8Array} publicKey - Public key used to verify the message
14132 * @param {Uint8Array} hashed - The hashed message
14133 * @returns {Boolean}
14134 * @async
14135 */
14136async function verify$2(oid, hashAlgo, { r, s }, m, publicKey, hashed) {
14137 if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {
14138 throw new Error('Hash algorithm too weak for EdDSA.');
14139 }
14140 const signature = util.concatUint8Array([r, s]);
14141 return naclFastLight.sign.detached.verify(hashed, signature, publicKey.subarray(1));
14142}
14143/**
14144 * Validate legacy EdDSA parameters
14145 * @param {module:type/oid} oid - Elliptic curve object identifier
14146 * @param {Uint8Array} Q - EdDSA public point
14147 * @param {Uint8Array} k - EdDSA secret seed
14148 * @returns {Promise<Boolean>} Whether params are valid.
14149 * @async
14150 */
14151async function validateParams$3(oid, Q, k) {
14152 // Check whether the given curve is supported
14153 if (oid.getName() !== 'ed25519') {
14154 return false;
14155 }
14156
14157 /**
14158 * Derive public point Q' = dG from private key
14159 * and expect Q == Q'
14160 */
14161 const { publicKey } = naclFastLight.sign.keyPair.fromSeed(k);
14162 const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix
14163 return util.equalsUint8Array(Q, dG);
14164
14165}
14166
14167var eddsa_legacy = /*#__PURE__*/Object.freeze({
14168 __proto__: null,
14169 sign: sign$2,
14170 verify: verify$2,
14171 validateParams: validateParams$3
14172});
14173
14174// OpenPGP.js - An OpenPGP implementation in javascript
14175
14176naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest());
14177
14178/**
14179 * Generate (non-legacy) EdDSA key
14180 * @param {module:enums.publicKey} algo - Algorithm identifier
14181 * @returns {Promise<{ A: Uint8Array, seed: Uint8Array }>}
14182 */
14183async function generate$2(algo) {
14184 switch (algo) {
14185 case enums.publicKey.ed25519: {
14186 const seed = getRandomBytes(32);
14187 const { publicKey: A } = naclFastLight.sign.keyPair.fromSeed(seed);
14188 return { A, seed };
14189 }
14190 default:
14191 throw new Error('Unsupported EdDSA algorithm');
14192 }
14193}
14194
14195/**
14196 * Sign a message using the provided key
14197 * @param {module:enums.publicKey} algo - Algorithm identifier
14198 * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)
14199 * @param {Uint8Array} message - Message to sign
14200 * @param {Uint8Array} publicKey - Public key
14201 * @param {Uint8Array} privateKey - Private key used to sign the message
14202 * @param {Uint8Array} hashed - The hashed message
14203 * @returns {Promise<{
14204 * RS: Uint8Array
14205 * }>} Signature of the message
14206 * @async
14207 */
14208async function sign$3(algo, hashAlgo, message, publicKey, privateKey, hashed) {
14209 if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo$1(algo))) {
14210 throw new Error('Hash algorithm too weak for EdDSA.');
14211 }
14212 switch (algo) {
14213 case enums.publicKey.ed25519: {
14214 const secretKey = util.concatUint8Array([privateKey, publicKey]);
14215 const signature = naclFastLight.sign.detached(hashed, secretKey);
14216 return { RS: signature };
14217 }
14218 case enums.publicKey.ed448:
14219 default:
14220 throw new Error('Unsupported EdDSA algorithm');
14221 }
14222
14223}
14224
14225/**
14226 * Verifies if a signature is valid for a message
14227 * @param {module:enums.publicKey} algo - Algorithm identifier
14228 * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature
14229 * @param {{ RS: Uint8Array }} signature Signature to verify the message
14230 * @param {Uint8Array} m - Message to verify
14231 * @param {Uint8Array} publicKey - Public key used to verify the message
14232 * @param {Uint8Array} hashed - The hashed message
14233 * @returns {Boolean}
14234 * @async
14235 */
14236async function verify$3(algo, hashAlgo, { RS }, m, publicKey, hashed) {
14237 if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(getPreferredHashAlgo$1(algo))) {
14238 throw new Error('Hash algorithm too weak for EdDSA.');
14239 }
14240 switch (algo) {
14241 case enums.publicKey.ed25519: {
14242 return naclFastLight.sign.detached.verify(hashed, RS, publicKey);
14243 }
14244 case enums.publicKey.ed448:
14245 default:
14246 throw new Error('Unsupported EdDSA algorithm');
14247 }
14248}
14249/**
14250 * Validate (non-legacy) EdDSA parameters
14251 * @param {module:enums.publicKey} algo - Algorithm identifier
14252 * @param {Uint8Array} A - EdDSA public point
14253 * @param {Uint8Array} seed - EdDSA secret seed
14254 * @param {Uint8Array} oid - (legacy only) EdDSA OID
14255 * @returns {Promise<Boolean>} Whether params are valid.
14256 * @async
14257 */
14258async function validateParams$4(algo, A, seed) {
14259 switch (algo) {
14260 case enums.publicKey.ed25519: {
14261 /**
14262 * Derive public point A' from private key
14263 * and expect A == A'
14264 */
14265 const { publicKey } = naclFastLight.sign.keyPair.fromSeed(seed);
14266 return util.equalsUint8Array(A, publicKey);
14267 }
14268
14269 case enums.publicKey.ed448: // unsupported
14270 default:
14271 return false;
14272 }
14273}
14274
14275function getPreferredHashAlgo$1(algo) {
14276 switch (algo) {
14277 case enums.publicKey.ed25519:
14278 return enums.hash.sha256;
14279 default:
14280 throw new Error('Unknown EdDSA algo');
14281 }
14282}
14283
14284var eddsa = /*#__PURE__*/Object.freeze({
14285 __proto__: null,
14286 generate: generate$2,
14287 sign: sign$3,
14288 verify: verify$3,
14289 validateParams: validateParams$4,
14290 getPreferredHashAlgo: getPreferredHashAlgo$1
14291});
14292
14293// OpenPGP.js - An OpenPGP implementation in javascript
14294
14295/**
14296 * AES key wrap
14297 * @function
14298 * @param {Uint8Array} key
14299 * @param {Uint8Array} data
14300 * @returns {Uint8Array}
14301 */
14302function wrap(key, data) {
14303 const aes = new cipher['aes' + (key.length * 8)](key);
14304 const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
14305 const P = unpack(data);
14306 let A = IV;
14307 const R = P;
14308 const n = P.length / 2;
14309 const t = new Uint32Array([0, 0]);
14310 let B = new Uint32Array(4);
14311 for (let j = 0; j <= 5; ++j) {
14312 for (let i = 0; i < n; ++i) {
14313 t[1] = n * j + (1 + i);
14314 // B = A
14315 B[0] = A[0];
14316 B[1] = A[1];
14317 // B = A || R[i]
14318 B[2] = R[2 * i];
14319 B[3] = R[2 * i + 1];
14320 // B = AES(K, B)
14321 B = unpack(aes.encrypt(pack(B)));
14322 // A = MSB(64, B) ^ t
14323 A = B.subarray(0, 2);
14324 A[0] ^= t[0];
14325 A[1] ^= t[1];
14326 // R[i] = LSB(64, B)
14327 R[2 * i] = B[2];
14328 R[2 * i + 1] = B[3];
14329 }
14330 }
14331 return pack(A, R);
14332}
14333
14334/**
14335 * AES key unwrap
14336 * @function
14337 * @param {String} key
14338 * @param {String} data
14339 * @returns {Uint8Array}
14340 * @throws {Error}
14341 */
14342function unwrap(key, data) {
14343 const aes = new cipher['aes' + (key.length * 8)](key);
14344 const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
14345 const C = unpack(data);
14346 let A = C.subarray(0, 2);
14347 const R = C.subarray(2);
14348 const n = C.length / 2 - 1;
14349 const t = new Uint32Array([0, 0]);
14350 let B = new Uint32Array(4);
14351 for (let j = 5; j >= 0; --j) {
14352 for (let i = n - 1; i >= 0; --i) {
14353 t[1] = n * j + (i + 1);
14354 // B = A ^ t
14355 B[0] = A[0] ^ t[0];
14356 B[1] = A[1] ^ t[1];
14357 // B = (A ^ t) || R[i]
14358 B[2] = R[2 * i];
14359 B[3] = R[2 * i + 1];
14360 // B = AES-1(B)
14361 B = unpack(aes.decrypt(pack(B)));
14362 // A = MSB(64, B)
14363 A = B.subarray(0, 2);
14364 // R[i] = LSB(64, B)
14365 R[2 * i] = B[2];
14366 R[2 * i + 1] = B[3];
14367 }
14368 }
14369 if (A[0] === IV[0] && A[1] === IV[1]) {
14370 return pack(R);
14371 }
14372 throw new Error('Key Data Integrity failed');
14373}
14374
14375function createArrayBuffer(data) {
14376 if (util.isString(data)) {
14377 const { length } = data;
14378 const buffer = new ArrayBuffer(length);
14379 const view = new Uint8Array(buffer);
14380 for (let j = 0; j < length; ++j) {
14381 view[j] = data.charCodeAt(j);
14382 }
14383 return buffer;
14384 }
14385 return new Uint8Array(data).buffer;
14386}
14387
14388function unpack(data) {
14389 const { length } = data;
14390 const buffer = createArrayBuffer(data);
14391 const view = new DataView(buffer);
14392 const arr = new Uint32Array(length / 4);
14393 for (let i = 0; i < length / 4; ++i) {
14394 arr[i] = view.getUint32(4 * i);
14395 }
14396 return arr;
14397}
14398
14399function pack() {
14400 let length = 0;
14401 for (let k = 0; k < arguments.length; ++k) {
14402 length += 4 * arguments[k].length;
14403 }
14404 const buffer = new ArrayBuffer(length);
14405 const view = new DataView(buffer);
14406 let offset = 0;
14407 for (let i = 0; i < arguments.length; ++i) {
14408 for (let j = 0; j < arguments[i].length; ++j) {
14409 view.setUint32(offset + 4 * j, arguments[i][j]);
14410 }
14411 offset += 4 * arguments[i].length;
14412 }
14413 return new Uint8Array(buffer);
14414}
14415
14416var aesKW = /*#__PURE__*/Object.freeze({
14417 __proto__: null,
14418 wrap: wrap,
14419 unwrap: unwrap
14420});
14421
14422// OpenPGP.js - An OpenPGP implementation in javascript
14423
14424/**
14425 * @fileoverview Functions to add and remove PKCS5 padding
14426 * @see PublicKeyEncryptedSessionKeyPacket
14427 * @module crypto/pkcs5
14428 * @private
14429 */
14430
14431/**
14432 * Add pkcs5 padding to a message
14433 * @param {Uint8Array} message - message to pad
14434 * @returns {Uint8Array} Padded message.
14435 */
14436function encode$1(message) {
14437 const c = 8 - (message.length % 8);
14438 const padded = new Uint8Array(message.length + c).fill(c);
14439 padded.set(message);
14440 return padded;
14441}
14442
14443/**
14444 * Remove pkcs5 padding from a message
14445 * @param {Uint8Array} message - message to remove padding from
14446 * @returns {Uint8Array} Message without padding.
14447 */
14448function decode$1(message) {
14449 const len = message.length;
14450 if (len > 0) {
14451 const c = message[len - 1];
14452 if (c >= 1) {
14453 const provided = message.subarray(len - c);
14454 const computed = new Uint8Array(c).fill(c);
14455 if (util.equalsUint8Array(provided, computed)) {
14456 return message.subarray(0, len - c);
14457 }
14458 }
14459 }
14460 throw new Error('Invalid padding');
14461}
14462
14463var pkcs5 = /*#__PURE__*/Object.freeze({
14464 __proto__: null,
14465 encode: encode$1,
14466 decode: decode$1
14467});
14468
14469// OpenPGP.js - An OpenPGP implementation in javascript
14470
14471const webCrypto$8 = util.getWebCrypto();
14472const nodeCrypto$9 = util.getNodeCrypto();
14473
14474/**
14475 * Validate ECDH parameters
14476 * @param {module:type/oid} oid - Elliptic curve object identifier
14477 * @param {Uint8Array} Q - ECDH public point
14478 * @param {Uint8Array} d - ECDH secret scalar
14479 * @returns {Promise<Boolean>} Whether params are valid.
14480 * @async
14481 */
14482async function validateParams$5(oid, Q, d) {
14483 return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);
14484}
14485
14486// Build Param for ECDH algorithm (RFC 6637)
14487function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {
14488 return util.concatUint8Array([
14489 oid.write(),
14490 new Uint8Array([public_algo]),
14491 kdfParams.write(),
14492 util.stringToUint8Array('Anonymous Sender '),
14493 fingerprint.subarray(0, 20)
14494 ]);
14495}
14496
14497// Key Derivation Function (RFC 6637)
14498async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {
14499 // Note: X is little endian for Curve25519, big-endian for all others.
14500 // This is not ideal, but the RFC's are unclear
14501 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
14502 let i;
14503 if (stripLeading) {
14504 // Work around old go crypto bug
14505 for (i = 0; i < X.length && X[i] === 0; i++);
14506 X = X.subarray(i);
14507 }
14508 if (stripTrailing) {
14509 // Work around old OpenPGP.js bug
14510 for (i = X.length - 1; i >= 0 && X[i] === 0; i--);
14511 X = X.subarray(0, i + 1);
14512 }
14513 const digest = await hash.digest(hashAlgo, util.concatUint8Array([
14514 new Uint8Array([0, 0, 0, 1]),
14515 X,
14516 param
14517 ]));
14518 return digest.subarray(0, length);
14519}
14520
14521/**
14522 * Generate ECDHE ephemeral key and secret from public key
14523 *
14524 * @param {CurveWithOID} curve - Elliptic curve object
14525 * @param {Uint8Array} Q - Recipient public key
14526 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
14527 * @async
14528 */
14529async function genPublicEphemeralKey(curve, Q) {
14530 switch (curve.type) {
14531 case 'curve25519': {
14532 const d = getRandomBytes(32);
14533 const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d);
14534 let { publicKey } = naclFastLight.box.keyPair.fromSecretKey(secretKey);
14535 publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]);
14536 return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
14537 }
14538 case 'web':
14539 if (curve.web && util.getWebCrypto()) {
14540 try {
14541 return await webPublicEphemeralKey(curve, Q);
14542 } catch (err) {
14543 util.printDebugError(err);
14544 }
14545 }
14546 break;
14547 case 'node':
14548 return nodePublicEphemeralKey(curve, Q);
14549 }
14550 return ellipticPublicEphemeralKey(curve, Q);
14551}
14552
14553/**
14554 * Encrypt and wrap a session key
14555 *
14556 * @param {module:type/oid} oid - Elliptic curve object identifier
14557 * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use
14558 * @param {Uint8Array} data - Unpadded session key data
14559 * @param {Uint8Array} Q - Recipient public key
14560 * @param {Uint8Array} fingerprint - Recipient fingerprint
14561 * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}
14562 * @async
14563 */
14564async function encrypt$3(oid, kdfParams, data, Q, fingerprint) {
14565 const m = encode$1(data);
14566
14567 const curve = new CurveWithOID(oid);
14568 const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);
14569 const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);
14570 const { keySize } = getCipher(kdfParams.cipher);
14571 const Z = await kdf(kdfParams.hash, sharedKey, keySize, param);
14572 const wrappedKey = wrap(Z, m);
14573 return { publicKey, wrappedKey };
14574}
14575
14576/**
14577 * Generate ECDHE secret from private key and public part of ephemeral key
14578 *
14579 * @param {CurveWithOID} curve - Elliptic curve object
14580 * @param {Uint8Array} V - Public part of ephemeral key
14581 * @param {Uint8Array} Q - Recipient public key
14582 * @param {Uint8Array} d - Recipient private key
14583 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
14584 * @async
14585 */
14586async function genPrivateEphemeralKey(curve, V, Q, d) {
14587 if (d.length !== curve.payloadSize) {
14588 const privateKey = new Uint8Array(curve.payloadSize);
14589 privateKey.set(d, curve.payloadSize - d.length);
14590 d = privateKey;
14591 }
14592 switch (curve.type) {
14593 case 'curve25519': {
14594 const secretKey = d.slice().reverse();
14595 const sharedKey = naclFastLight.scalarMult(secretKey, V.subarray(1));
14596 return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
14597 }
14598 case 'web':
14599 if (curve.web && util.getWebCrypto()) {
14600 try {
14601 return await webPrivateEphemeralKey(curve, V, Q, d);
14602 } catch (err) {
14603 util.printDebugError(err);
14604 }
14605 }
14606 break;
14607 case 'node':
14608 return nodePrivateEphemeralKey(curve, V, d);
14609 }
14610 return ellipticPrivateEphemeralKey(curve, V, d);
14611}
14612
14613/**
14614 * Decrypt and unwrap the value derived from session key
14615 *
14616 * @param {module:type/oid} oid - Elliptic curve object identifier
14617 * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use
14618 * @param {Uint8Array} V - Public part of ephemeral key
14619 * @param {Uint8Array} C - Encrypted and wrapped value derived from session key
14620 * @param {Uint8Array} Q - Recipient public key
14621 * @param {Uint8Array} d - Recipient private key
14622 * @param {Uint8Array} fingerprint - Recipient fingerprint
14623 * @returns {Promise<Uint8Array>} Value derived from session key.
14624 * @async
14625 */
14626async function decrypt$3(oid, kdfParams, V, C, Q, d, fingerprint) {
14627 const curve = new CurveWithOID(oid);
14628 const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);
14629 const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);
14630 const { keySize } = getCipher(kdfParams.cipher);
14631 let err;
14632 for (let i = 0; i < 3; i++) {
14633 try {
14634 // Work around old go crypto bug and old OpenPGP.js bug, respectively.
14635 const Z = await kdf(kdfParams.hash, sharedKey, keySize, param, i === 1, i === 2);
14636 return decode$1(unwrap(Z, C));
14637 } catch (e) {
14638 err = e;
14639 }
14640 }
14641 throw err;
14642}
14643
14644/**
14645 * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto
14646 *
14647 * @param {CurveWithOID} curve - Elliptic curve object
14648 * @param {Uint8Array} V - Public part of ephemeral key
14649 * @param {Uint8Array} Q - Recipient public key
14650 * @param {Uint8Array} d - Recipient private key
14651 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
14652 * @async
14653 */
14654async function webPrivateEphemeralKey(curve, V, Q, d) {
14655 const recipient = privateToJWK$1(curve.payloadSize, curve.web.web, Q, d);
14656 let privateKey = webCrypto$8.importKey(
14657 'jwk',
14658 recipient,
14659 {
14660 name: 'ECDH',
14661 namedCurve: curve.web.web
14662 },
14663 true,
14664 ['deriveKey', 'deriveBits']
14665 );
14666 const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V);
14667 let sender = webCrypto$8.importKey(
14668 'jwk',
14669 jwk,
14670 {
14671 name: 'ECDH',
14672 namedCurve: curve.web.web
14673 },
14674 true,
14675 []
14676 );
14677 [privateKey, sender] = await Promise.all([privateKey, sender]);
14678 let S = webCrypto$8.deriveBits(
14679 {
14680 name: 'ECDH',
14681 namedCurve: curve.web.web,
14682 public: sender
14683 },
14684 privateKey,
14685 curve.web.sharedSize
14686 );
14687 let secret = webCrypto$8.exportKey(
14688 'jwk',
14689 privateKey
14690 );
14691 [S, secret] = await Promise.all([S, secret]);
14692 const sharedKey = new Uint8Array(S);
14693 const secretKey = b64ToUint8Array(secret.d);
14694 return { secretKey, sharedKey };
14695}
14696
14697/**
14698 * Generate ECDHE ephemeral key and secret from public key using webCrypto
14699 *
14700 * @param {CurveWithOID} curve - Elliptic curve object
14701 * @param {Uint8Array} Q - Recipient public key
14702 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
14703 * @async
14704 */
14705async function webPublicEphemeralKey(curve, Q) {
14706 const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q);
14707 let keyPair = webCrypto$8.generateKey(
14708 {
14709 name: 'ECDH',
14710 namedCurve: curve.web.web
14711 },
14712 true,
14713 ['deriveKey', 'deriveBits']
14714 );
14715 let recipient = webCrypto$8.importKey(
14716 'jwk',
14717 jwk,
14718 {
14719 name: 'ECDH',
14720 namedCurve: curve.web.web
14721 },
14722 false,
14723 []
14724 );
14725 [keyPair, recipient] = await Promise.all([keyPair, recipient]);
14726 let s = webCrypto$8.deriveBits(
14727 {
14728 name: 'ECDH',
14729 namedCurve: curve.web.web,
14730 public: recipient
14731 },
14732 keyPair.privateKey,
14733 curve.web.sharedSize
14734 );
14735 let p = webCrypto$8.exportKey(
14736 'jwk',
14737 keyPair.publicKey
14738 );
14739 [s, p] = await Promise.all([s, p]);
14740 const sharedKey = new Uint8Array(s);
14741 const publicKey = new Uint8Array(jwkToRawPublic(p));
14742 return { publicKey, sharedKey };
14743}
14744
14745/**
14746 * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic
14747 *
14748 * @param {CurveWithOID} curve - Elliptic curve object
14749 * @param {Uint8Array} V - Public part of ephemeral key
14750 * @param {Uint8Array} d - Recipient private key
14751 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
14752 * @async
14753 */
14754async function ellipticPrivateEphemeralKey(curve, V, d) {
14755 const indutnyCurve = await getIndutnyCurve(curve.name);
14756 V = keyFromPublic(indutnyCurve, V);
14757 d = keyFromPrivate(indutnyCurve, d);
14758 const secretKey = new Uint8Array(d.getPrivate());
14759 const S = d.derive(V.getPublic());
14760 const len = indutnyCurve.curve.p.byteLength();
14761 const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
14762 return { secretKey, sharedKey };
14763}
14764
14765/**
14766 * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic
14767 *
14768 * @param {CurveWithOID} curve - Elliptic curve object
14769 * @param {Uint8Array} Q - Recipient public key
14770 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
14771 * @async
14772 */
14773async function ellipticPublicEphemeralKey(curve, Q) {
14774 const indutnyCurve = await getIndutnyCurve(curve.name);
14775 const v = await curve.genKeyPair();
14776 Q = keyFromPublic(indutnyCurve, Q);
14777 const V = keyFromPrivate(indutnyCurve, v.privateKey);
14778 const publicKey = v.publicKey;
14779 const S = V.derive(Q.getPublic());
14780 const len = indutnyCurve.curve.p.byteLength();
14781 const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
14782 return { publicKey, sharedKey };
14783}
14784
14785/**
14786 * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto
14787 *
14788 * @param {CurveWithOID} curve - Elliptic curve object
14789 * @param {Uint8Array} V - Public part of ephemeral key
14790 * @param {Uint8Array} d - Recipient private key
14791 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
14792 * @async
14793 */
14794async function nodePrivateEphemeralKey(curve, V, d) {
14795 const recipient = nodeCrypto$9.createECDH(curve.node.node);
14796 recipient.setPrivateKey(d);
14797 const sharedKey = new Uint8Array(recipient.computeSecret(V));
14798 const secretKey = new Uint8Array(recipient.getPrivateKey());
14799 return { secretKey, sharedKey };
14800}
14801
14802/**
14803 * Generate ECDHE ephemeral key and secret from public key using nodeCrypto
14804 *
14805 * @param {CurveWithOID} curve - Elliptic curve object
14806 * @param {Uint8Array} Q - Recipient public key
14807 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
14808 * @async
14809 */
14810async function nodePublicEphemeralKey(curve, Q) {
14811 const sender = nodeCrypto$9.createECDH(curve.node.node);
14812 sender.generateKeys();
14813 const sharedKey = new Uint8Array(sender.computeSecret(Q));
14814 const publicKey = new Uint8Array(sender.getPublicKey());
14815 return { publicKey, sharedKey };
14816}
14817
14818var ecdh = /*#__PURE__*/Object.freeze({
14819 __proto__: null,
14820 validateParams: validateParams$5,
14821 encrypt: encrypt$3,
14822 decrypt: decrypt$3
14823});
14824
14825/**
14826 * @fileoverview This module implements HKDF using either the WebCrypto API or Node.js' crypto API.
14827 * @module crypto/hkdf
14828 * @private
14829 */
14830
14831const webCrypto$9 = util.getWebCrypto();
14832const nodeCrypto$a = util.getNodeCrypto();
14833const nodeSubtleCrypto = nodeCrypto$a && nodeCrypto$a.webcrypto && nodeCrypto$a.webcrypto.subtle;
14834
14835async function HKDF(hashAlgo, inputKey, salt, info, outLen) {
14836 const hash = enums.read(enums.webHash, hashAlgo);
14837 if (!hash) throw new Error('Hash algo not supported with HKDF');
14838
14839 if (webCrypto$9 || nodeSubtleCrypto) {
14840 const crypto = webCrypto$9 || nodeSubtleCrypto;
14841 const importedKey = await crypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']);
14842 const bits = await crypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8);
14843 return new Uint8Array(bits);
14844 }
14845
14846 if (nodeCrypto$a) {
14847 const hashAlgoName = enums.read(enums.hash, hashAlgo);
14848 // Node-only HKDF implementation based on https://www.rfc-editor.org/rfc/rfc5869
14849
14850 const computeHMAC = (hmacKey, hmacMessage) => nodeCrypto$a.createHmac(hashAlgoName, hmacKey).update(hmacMessage).digest();
14851 // Step 1: Extract
14852 // PRK = HMAC-Hash(salt, IKM)
14853 const pseudoRandomKey = computeHMAC(salt, inputKey);
14854
14855 const hashLen = pseudoRandomKey.length;
14856
14857 // Step 2: Expand
14858 // HKDF-Expand(PRK, info, L) -> OKM
14859 const n = Math.ceil(outLen / hashLen);
14860 const outputKeyingMaterial = new Uint8Array(n * hashLen);
14861
14862 // HMAC input buffer updated at each iteration
14863 const roundInput = new Uint8Array(hashLen + info.length + 1);
14864 // T_i and last byte are updated at each iteration, but `info` remains constant
14865 roundInput.set(info, hashLen);
14866
14867 for (let i = 0; i < n; i++) {
14868 // T(0) = empty string (zero length)
14869 // T(i) = HMAC-Hash(PRK, T(i-1) | info | i)
14870 roundInput[roundInput.length - 1] = i + 1;
14871 // t = T(i+1)
14872 const t = computeHMAC(pseudoRandomKey, i > 0 ? roundInput : roundInput.subarray(hashLen));
14873 roundInput.set(t, 0);
14874
14875 outputKeyingMaterial.set(t, i * hashLen);
14876 }
14877
14878 return outputKeyingMaterial.subarray(0, outLen);
14879 }
14880
14881 throw new Error('No HKDF implementation available');
14882}
14883
14884/**
14885 * @fileoverview Key encryption and decryption for RFC 6637 ECDH
14886 * @module crypto/public_key/elliptic/ecdh
14887 * @private
14888 */
14889
14890const HKDF_INFO = {
14891 x25519: util.encodeUTF8('OpenPGP X25519')
14892};
14893
14894/**
14895 * Generate ECDH key for Montgomery curves
14896 * @param {module:enums.publicKey} algo - Algorithm identifier
14897 * @returns {Promise<{ A: Uint8Array, k: Uint8Array }>}
14898 */
14899async function generate$3(algo) {
14900 switch (algo) {
14901 case enums.publicKey.x25519: {
14902 // k stays in little-endian, unlike legacy ECDH over curve25519
14903 const k = getRandomBytes(32);
14904 const { publicKey: A } = naclFastLight.box.keyPair.fromSecretKey(k);
14905 return { A, k };
14906 }
14907 default:
14908 throw new Error('Unsupported ECDH algorithm');
14909 }
14910}
14911
14912/**
14913* Validate ECDH parameters
14914* @param {module:enums.publicKey} algo - Algorithm identifier
14915* @param {Uint8Array} A - ECDH public point
14916* @param {Uint8Array} k - ECDH secret scalar
14917* @returns {Promise<Boolean>} Whether params are valid.
14918* @async
14919*/
14920async function validateParams$6(algo, A, k) {
14921 switch (algo) {
14922 case enums.publicKey.x25519: {
14923 /**
14924 * Derive public point A' from private key
14925 * and expect A == A'
14926 */
14927 const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(k);
14928 return util.equalsUint8Array(A, publicKey);
14929 }
14930
14931 default:
14932 return false;
14933 }
14934}
14935
14936/**
14937 * Wrap and encrypt a session key
14938 *
14939 * @param {module:enums.publicKey} algo - Algorithm identifier
14940 * @param {Uint8Array} data - session key data to be encrypted
14941 * @param {Uint8Array} recipientA - Recipient public key (K_B)
14942 * @returns {Promise<{
14943 * ephemeralPublicKey: Uint8Array,
14944 * wrappedKey: Uint8Array
14945 * }>} ephemeral public key (K_A) and encrypted key
14946 * @async
14947 */
14948async function encrypt$4(algo, data, recipientA) {
14949 switch (algo) {
14950 case enums.publicKey.x25519: {
14951 const ephemeralSecretKey = getRandomBytes(32);
14952 const sharedSecret = naclFastLight.scalarMult(ephemeralSecretKey, recipientA);
14953 const { publicKey: ephemeralPublicKey } = naclFastLight.box.keyPair.fromSecretKey(ephemeralSecretKey);
14954 const hkdfInput = util.concatUint8Array([
14955 ephemeralPublicKey,
14956 recipientA,
14957 sharedSecret
14958 ]);
14959 const { keySize } = getCipher(enums.symmetric.aes128);
14960 const encryptionKey = await HKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);
14961 const wrappedKey = wrap(encryptionKey, data);
14962 return { ephemeralPublicKey, wrappedKey };
14963 }
14964
14965 default:
14966 throw new Error('Unsupported ECDH algorithm');
14967 }
14968}
14969
14970/**
14971 * Decrypt and unwrap the session key
14972 *
14973 * @param {module:enums.publicKey} algo - Algorithm identifier
14974 * @param {Uint8Array} ephemeralPublicKey - (K_A)
14975 * @param {Uint8Array} wrappedKey,
14976 * @param {Uint8Array} A - Recipient public key (K_b), needed for KDF
14977 * @param {Uint8Array} k - Recipient secret key (b)
14978 * @returns {Promise<Uint8Array>} decrypted session key data
14979 * @async
14980 */
14981async function decrypt$4(algo, ephemeralPublicKey, wrappedKey, A, k) {
14982 switch (algo) {
14983 case enums.publicKey.x25519: {
14984 const sharedSecret = naclFastLight.scalarMult(k, ephemeralPublicKey);
14985 const hkdfInput = util.concatUint8Array([
14986 ephemeralPublicKey,
14987 A,
14988 sharedSecret
14989 ]);
14990 const { keySize } = getCipher(enums.symmetric.aes128);
14991 const encryptionKey = await HKDF(enums.hash.sha256, hkdfInput, new Uint8Array(), HKDF_INFO.x25519, keySize);
14992 return unwrap(encryptionKey, wrappedKey);
14993 }
14994 default:
14995 throw new Error('Unsupported ECDH algorithm');
14996 }
14997}
14998
14999var ecdh_x = /*#__PURE__*/Object.freeze({
15000 __proto__: null,
15001 generate: generate$3,
15002 validateParams: validateParams$6,
15003 encrypt: encrypt$4,
15004 decrypt: decrypt$4
15005});
15006
15007// OpenPGP.js - An OpenPGP implementation in javascript
15008
15009var elliptic = /*#__PURE__*/Object.freeze({
15010 __proto__: null,
15011 CurveWithOID: CurveWithOID,
15012 ecdh: ecdh,
15013 ecdhX: ecdh_x,
15014 ecdsa: ecdsa,
15015 eddsaLegacy: eddsa_legacy,
15016 eddsa: eddsa,
15017 generate: generate$1,
15018 getPreferredHashAlgo: getPreferredHashAlgo
15019});
15020
15021// GPG4Browsers - An OpenPGP implementation in javascript
15022
15023/*
15024 TODO regarding the hash function, read:
15025 https://tools.ietf.org/html/rfc4880#section-13.6
15026 https://tools.ietf.org/html/rfc4880#section-14
15027*/
15028
15029/**
15030 * DSA Sign function
15031 * @param {Integer} hashAlgo
15032 * @param {Uint8Array} hashed
15033 * @param {Uint8Array} g
15034 * @param {Uint8Array} p
15035 * @param {Uint8Array} q
15036 * @param {Uint8Array} x
15037 * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}
15038 * @async
15039 */
15040async function sign$4(hashAlgo, hashed, g, p, q, x) {
15041 const BigInteger = await util.getBigInteger();
15042 const one = new BigInteger(1);
15043 p = new BigInteger(p);
15044 q = new BigInteger(q);
15045 g = new BigInteger(g);
15046 x = new BigInteger(x);
15047
15048 let k;
15049 let r;
15050 let s;
15051 let t;
15052 g = g.mod(p);
15053 x = x.mod(q);
15054 // If the output size of the chosen hash is larger than the number of
15055 // bits of q, the hash result is truncated to fit by taking the number
15056 // of leftmost bits equal to the number of bits of q. This (possibly
15057 // truncated) hash function result is treated as a number and used
15058 // directly in the DSA signature algorithm.
15059 const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q);
15060 // FIPS-186-4, section 4.6:
15061 // The values of r and s shall be checked to determine if r = 0 or s = 0.
15062 // If either r = 0 or s = 0, a new value of k shall be generated, and the
15063 // signature shall be recalculated. It is extremely unlikely that r = 0
15064 // or s = 0 if signatures are generated properly.
15065 while (true) {
15066 // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
15067 k = await getRandomBigInteger(one, q); // returns in [1, q-1]
15068 r = g.modExp(k, p).imod(q); // (g**k mod p) mod q
15069 if (r.isZero()) {
15070 continue;
15071 }
15072 const xr = x.mul(r).imod(q);
15073 t = h.add(xr).imod(q); // H(m) + x*r mod q
15074 s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q
15075 if (s.isZero()) {
15076 continue;
15077 }
15078 break;
15079 }
15080 return {
15081 r: r.toUint8Array('be', q.byteLength()),
15082 s: s.toUint8Array('be', q.byteLength())
15083 };
15084}
15085
15086/**
15087 * DSA Verify function
15088 * @param {Integer} hashAlgo
15089 * @param {Uint8Array} r
15090 * @param {Uint8Array} s
15091 * @param {Uint8Array} hashed
15092 * @param {Uint8Array} g
15093 * @param {Uint8Array} p
15094 * @param {Uint8Array} q
15095 * @param {Uint8Array} y
15096 * @returns {boolean}
15097 * @async
15098 */
15099async function verify$4(hashAlgo, r, s, hashed, g, p, q, y) {
15100 const BigInteger = await util.getBigInteger();
15101 const zero = new BigInteger(0);
15102 r = new BigInteger(r);
15103 s = new BigInteger(s);
15104
15105 p = new BigInteger(p);
15106 q = new BigInteger(q);
15107 g = new BigInteger(g);
15108 y = new BigInteger(y);
15109
15110 if (r.lte(zero) || r.gte(q) ||
15111 s.lte(zero) || s.gte(q)) {
15112 util.printDebug('invalid DSA Signature');
15113 return false;
15114 }
15115 const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q);
15116 const w = s.modInv(q); // s**-1 mod q
15117 if (w.isZero()) {
15118 util.printDebug('invalid DSA Signature');
15119 return false;
15120 }
15121
15122 g = g.mod(p);
15123 y = y.mod(p);
15124 const u1 = h.mul(w).imod(q); // H(m) * w mod q
15125 const u2 = r.mul(w).imod(q); // r * w mod q
15126 const t1 = g.modExp(u1, p); // g**u1 mod p
15127 const t2 = y.modExp(u2, p); // y**u2 mod p
15128 const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q
15129 return v.equal(r);
15130}
15131
15132/**
15133 * Validate DSA parameters
15134 * @param {Uint8Array} p - DSA prime
15135 * @param {Uint8Array} q - DSA group order
15136 * @param {Uint8Array} g - DSA sub-group generator
15137 * @param {Uint8Array} y - DSA public key
15138 * @param {Uint8Array} x - DSA private key
15139 * @returns {Promise<Boolean>} Whether params are valid.
15140 * @async
15141 */
15142async function validateParams$7(p, q, g, y, x) {
15143 const BigInteger = await util.getBigInteger();
15144 p = new BigInteger(p);
15145 q = new BigInteger(q);
15146 g = new BigInteger(g);
15147 y = new BigInteger(y);
15148 const one = new BigInteger(1);
15149 // Check that 1 < g < p
15150 if (g.lte(one) || g.gte(p)) {
15151 return false;
15152 }
15153
15154 /**
15155 * Check that subgroup order q divides p-1
15156 */
15157 if (!p.dec().mod(q).isZero()) {
15158 return false;
15159 }
15160
15161 /**
15162 * g has order q
15163 * Check that g ** q = 1 mod p
15164 */
15165 if (!g.modExp(q, p).isOne()) {
15166 return false;
15167 }
15168
15169 /**
15170 * Check q is large and probably prime (we mainly want to avoid small factors)
15171 */
15172 const qSize = new BigInteger(q.bitLength());
15173 const n150 = new BigInteger(150);
15174 if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) {
15175 return false;
15176 }
15177
15178 /**
15179 * Re-derive public key y' = g ** x mod p
15180 * Expect y == y'
15181 *
15182 * Blinded exponentiation computes g**{rq + x} to compare to y
15183 */
15184 x = new BigInteger(x);
15185 const two = new BigInteger(2);
15186 const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q
15187 const rqx = q.mul(r).add(x);
15188 if (!y.equal(g.modExp(rqx, p))) {
15189 return false;
15190 }
15191
15192 return true;
15193}
15194
15195var dsa = /*#__PURE__*/Object.freeze({
15196 __proto__: null,
15197 sign: sign$4,
15198 verify: verify$4,
15199 validateParams: validateParams$7
15200});
15201
15202/**
15203 * @fileoverview Asymmetric cryptography functions
15204 * @module crypto/public_key
15205 * @private
15206 */
15207
15208var publicKey = {
15209 /** @see module:crypto/public_key/rsa */
15210 rsa: rsa,
15211 /** @see module:crypto/public_key/elgamal */
15212 elgamal: elgamal,
15213 /** @see module:crypto/public_key/elliptic */
15214 elliptic: elliptic,
15215 /** @see module:crypto/public_key/dsa */
15216 dsa: dsa,
15217 /** @see tweetnacl */
15218 nacl: naclFastLight
15219};
15220
15221/**
15222 * @fileoverview Provides functions for asymmetric signing and signature verification
15223 * @module crypto/signature
15224 * @private
15225 */
15226
15227/**
15228 * Parse signature in binary form to get the parameters.
15229 * The returned values are only padded for EdDSA, since in the other cases their expected length
15230 * depends on the key params, hence we delegate the padding to the signature verification function.
15231 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
15232 * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}
15233 * @param {module:enums.publicKey} algo - Public key algorithm
15234 * @param {Uint8Array} signature - Data for which the signature was created
15235 * @returns {Promise<Object>} True if signature is valid.
15236 * @async
15237 */
15238function parseSignatureParams(algo, signature) {
15239 let read = 0;
15240 switch (algo) {
15241 // Algorithm-Specific Fields for RSA signatures:
15242 // - MPI of RSA signature value m**d mod n.
15243 case enums.publicKey.rsaEncryptSign:
15244 case enums.publicKey.rsaEncrypt:
15245 case enums.publicKey.rsaSign: {
15246 const s = util.readMPI(signature.subarray(read));
15247 // The signature needs to be the same length as the public key modulo n.
15248 // We pad s on signature verification, where we have access to n.
15249 return { s };
15250 }
15251 // Algorithm-Specific Fields for DSA or ECDSA signatures:
15252 // - MPI of DSA or ECDSA value r.
15253 // - MPI of DSA or ECDSA value s.
15254 case enums.publicKey.dsa:
15255 case enums.publicKey.ecdsa:
15256 {
15257 const r = util.readMPI(signature.subarray(read)); read += r.length + 2;
15258 const s = util.readMPI(signature.subarray(read));
15259 return { r, s };
15260 }
15261 // Algorithm-Specific Fields for legacy EdDSA signatures:
15262 // - MPI of an EC point r.
15263 // - EdDSA value s, in MPI, in the little endian representation
15264 case enums.publicKey.eddsaLegacy: {
15265 // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values:
15266 // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9
15267 let r = util.readMPI(signature.subarray(read)); read += r.length + 2;
15268 r = util.leftPad(r, 32);
15269 let s = util.readMPI(signature.subarray(read));
15270 s = util.leftPad(s, 32);
15271 return { r, s };
15272 }
15273 // Algorithm-Specific Fields for Ed25519 signatures:
15274 // - 64 octets of the native signature
15275 case enums.publicKey.ed25519: {
15276 const RS = signature.subarray(read, read + 64); read += RS.length;
15277 return { RS };
15278 }
15279 default:
15280 throw new UnsupportedError('Unknown signature algorithm.');
15281 }
15282}
15283
15284/**
15285 * Verifies the signature provided for data using specified algorithms and public key parameters.
15286 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
15287 * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
15288 * for public key and hash algorithms.
15289 * @param {module:enums.publicKey} algo - Public key algorithm
15290 * @param {module:enums.hash} hashAlgo - Hash algorithm
15291 * @param {Object} signature - Named algorithm-specific signature parameters
15292 * @param {Object} publicParams - Algorithm-specific public key parameters
15293 * @param {Uint8Array} data - Data for which the signature was created
15294 * @param {Uint8Array} hashed - The hashed data
15295 * @returns {Promise<Boolean>} True if signature is valid.
15296 * @async
15297 */
15298async function verify$5(algo, hashAlgo, signature, publicParams, data, hashed) {
15299 switch (algo) {
15300 case enums.publicKey.rsaEncryptSign:
15301 case enums.publicKey.rsaEncrypt:
15302 case enums.publicKey.rsaSign: {
15303 const { n, e } = publicParams;
15304 const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto
15305 return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);
15306 }
15307 case enums.publicKey.dsa: {
15308 const { g, p, q, y } = publicParams;
15309 const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers
15310 return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);
15311 }
15312 case enums.publicKey.ecdsa: {
15313 const { oid, Q } = publicParams;
15314 const curveSize = new publicKey.elliptic.CurveWithOID(oid).payloadSize;
15315 // padding needed for webcrypto
15316 const r = util.leftPad(signature.r, curveSize);
15317 const s = util.leftPad(signature.s, curveSize);
15318 return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);
15319 }
15320 case enums.publicKey.eddsaLegacy: {
15321 const { oid, Q } = publicParams;
15322 // signature already padded on parsing
15323 return publicKey.elliptic.eddsaLegacy.verify(oid, hashAlgo, signature, data, Q, hashed);
15324 }
15325 case enums.publicKey.ed25519: {
15326 const { A } = publicParams;
15327 return publicKey.elliptic.eddsa.verify(algo, hashAlgo, signature, data, A, hashed);
15328 }
15329 default:
15330 throw new Error('Unknown signature algorithm.');
15331 }
15332}
15333
15334/**
15335 * Creates a signature on data using specified algorithms and private key parameters.
15336 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
15337 * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
15338 * for public key and hash algorithms.
15339 * @param {module:enums.publicKey} algo - Public key algorithm
15340 * @param {module:enums.hash} hashAlgo - Hash algorithm
15341 * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters
15342 * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters
15343 * @param {Uint8Array} data - Data to be signed
15344 * @param {Uint8Array} hashed - The hashed data
15345 * @returns {Promise<Object>} Signature Object containing named signature parameters.
15346 * @async
15347 */
15348async function sign$5(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {
15349 if (!publicKeyParams || !privateKeyParams) {
15350 throw new Error('Missing key parameters');
15351 }
15352 switch (algo) {
15353 case enums.publicKey.rsaEncryptSign:
15354 case enums.publicKey.rsaEncrypt:
15355 case enums.publicKey.rsaSign: {
15356 const { n, e } = publicKeyParams;
15357 const { d, p, q, u } = privateKeyParams;
15358 const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);
15359 return { s };
15360 }
15361 case enums.publicKey.dsa: {
15362 const { g, p, q } = publicKeyParams;
15363 const { x } = privateKeyParams;
15364 return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);
15365 }
15366 case enums.publicKey.elgamal: {
15367 throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');
15368 }
15369 case enums.publicKey.ecdsa: {
15370 const { oid, Q } = publicKeyParams;
15371 const { d } = privateKeyParams;
15372 return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);
15373 }
15374 case enums.publicKey.eddsaLegacy: {
15375 const { oid, Q } = publicKeyParams;
15376 const { seed } = privateKeyParams;
15377 return publicKey.elliptic.eddsaLegacy.sign(oid, hashAlgo, data, Q, seed, hashed);
15378 }
15379 case enums.publicKey.ed25519: {
15380 const { A } = publicKeyParams;
15381 const { seed } = privateKeyParams;
15382 return publicKey.elliptic.eddsa.sign(algo, hashAlgo, data, A, seed, hashed);
15383 }
15384 default:
15385 throw new Error('Unknown signature algorithm.');
15386 }
15387}
15388
15389var signature = /*#__PURE__*/Object.freeze({
15390 __proto__: null,
15391 parseSignatureParams: parseSignatureParams,
15392 verify: verify$5,
15393 sign: sign$5
15394});
15395
15396// OpenPGP.js - An OpenPGP implementation in javascript
15397
15398class ECDHSymmetricKey {
15399 constructor(data) {
15400 if (data) {
15401 this.data = data;
15402 }
15403 }
15404
15405 /**
15406 * Read an ECDHSymmetricKey from an Uint8Array:
15407 * - 1 octect for the length `l`
15408 * - `l` octects of encoded session key data
15409 * @param {Uint8Array} bytes
15410 * @returns {Number} Number of read bytes.
15411 */
15412 read(bytes) {
15413 if (bytes.length >= 1) {
15414 const length = bytes[0];
15415 if (bytes.length >= 1 + length) {
15416 this.data = bytes.subarray(1, 1 + length);
15417 return 1 + this.data.length;
15418 }
15419 }
15420 throw new Error('Invalid symmetric key');
15421 }
15422
15423 /**
15424 * Write an ECDHSymmetricKey as an Uint8Array
15425 * @returns {Uint8Array} Serialised data
15426 */
15427 write() {
15428 return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);
15429 }
15430}
15431
15432// OpenPGP.js - An OpenPGP implementation in javascript
15433
15434/**
15435 * Implementation of type KDF parameters
15436 *
15437 * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:
15438 * A key derivation function (KDF) is necessary to implement the EC
15439 * encryption. The Concatenation Key Derivation Function (Approved
15440 * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is
15441 * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.
15442 * @module type/kdf_params
15443 * @private
15444 */
15445
15446class KDFParams {
15447 /**
15448 * @param {enums.hash} hash - Hash algorithm
15449 * @param {enums.symmetric} cipher - Symmetric algorithm
15450 */
15451 constructor(data) {
15452 if (data) {
15453 const { hash, cipher } = data;
15454 this.hash = hash;
15455 this.cipher = cipher;
15456 } else {
15457 this.hash = null;
15458 this.cipher = null;
15459 }
15460 }
15461
15462 /**
15463 * Read KDFParams from an Uint8Array
15464 * @param {Uint8Array} input - Where to read the KDFParams from
15465 * @returns {Number} Number of read bytes.
15466 */
15467 read(input) {
15468 if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {
15469 throw new UnsupportedError('Cannot read KDFParams');
15470 }
15471 this.hash = input[2];
15472 this.cipher = input[3];
15473 return 4;
15474 }
15475
15476 /**
15477 * Write KDFParams to an Uint8Array
15478 * @returns {Uint8Array} Array with the KDFParams value
15479 */
15480 write() {
15481 return new Uint8Array([3, 1, this.hash, this.cipher]);
15482 }
15483}
15484
15485/**
15486 * Encoded symmetric key for x25519 and x448
15487 * The payload format varies for v3 and v6 PKESK:
15488 * the former includes an algorithm byte preceeding the encrypted session key.
15489 *
15490 * @module type/x25519x448_symkey
15491 */
15492
15493class ECDHXSymmetricKey {
15494 static fromObject({ wrappedKey, algorithm }) {
15495 const instance = new ECDHXSymmetricKey();
15496 instance.wrappedKey = wrappedKey;
15497 instance.algorithm = algorithm;
15498 return instance;
15499 }
15500
15501 /**
15502 * - 1 octect for the length `l`
15503 * - `l` octects of encoded session key data (with optional leading algorithm byte)
15504 * @param {Uint8Array} bytes
15505 * @returns {Number} Number of read bytes.
15506 */
15507 read(bytes) {
15508 let read = 0;
15509 let followLength = bytes[read++];
15510 this.algorithm = followLength % 2 ? bytes[read++] : null; // session key size is always even
15511 followLength -= followLength % 2;
15512 this.wrappedKey = bytes.subarray(read, read + followLength); read += followLength;
15513 }
15514
15515 /**
15516 * Write an MontgomerySymmetricKey as an Uint8Array
15517 * @returns {Uint8Array} Serialised data
15518 */
15519 write() {
15520 return util.concatUint8Array([
15521 this.algorithm ?
15522 new Uint8Array([this.wrappedKey.length + 1, this.algorithm]) :
15523 new Uint8Array([this.wrappedKey.length]),
15524 this.wrappedKey
15525 ]);
15526 }
15527}
15528
15529// GPG4Browsers - An OpenPGP implementation in javascript
15530
15531/**
15532 * Encrypts data using specified algorithm and public key parameters.
15533 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.
15534 * @param {module:enums.publicKey} keyAlgo - Public key algorithm
15535 * @param {module:enums.symmetric} symmetricAlgo - Cipher algorithm
15536 * @param {Object} publicParams - Algorithm-specific public key parameters
15537 * @param {Uint8Array} data - Session key data to be encrypted
15538 * @param {Uint8Array} fingerprint - Recipient fingerprint
15539 * @returns {Promise<Object>} Encrypted session key parameters.
15540 * @async
15541 */
15542async function publicKeyEncrypt(keyAlgo, symmetricAlgo, publicParams, data, fingerprint) {
15543 switch (keyAlgo) {
15544 case enums.publicKey.rsaEncrypt:
15545 case enums.publicKey.rsaEncryptSign: {
15546 const { n, e } = publicParams;
15547 const c = await publicKey.rsa.encrypt(data, n, e);
15548 return { c };
15549 }
15550 case enums.publicKey.elgamal: {
15551 const { p, g, y } = publicParams;
15552 return publicKey.elgamal.encrypt(data, p, g, y);
15553 }
15554 case enums.publicKey.ecdh: {
15555 const { oid, Q, kdfParams } = publicParams;
15556 const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(
15557 oid, kdfParams, data, Q, fingerprint);
15558 return { V, C: new ECDHSymmetricKey(C) };
15559 }
15560 case enums.publicKey.x25519: {
15561 if (!util.isAES(symmetricAlgo)) {
15562 // see https://gitlab.com/openpgp-wg/rfc4880bis/-/merge_requests/276
15563 throw new Error('X25519 keys can only encrypt AES session keys');
15564 }
15565 const { A } = publicParams;
15566 const { ephemeralPublicKey, wrappedKey } = await publicKey.elliptic.ecdhX.encrypt(
15567 keyAlgo, data, A);
15568 const C = ECDHXSymmetricKey.fromObject({ algorithm: symmetricAlgo, wrappedKey });
15569 return { ephemeralPublicKey, C };
15570 }
15571 default:
15572 return [];
15573 }
15574}
15575
15576/**
15577 * Decrypts data using specified algorithm and private key parameters.
15578 * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}
15579 * @param {module:enums.publicKey} algo - Public key algorithm
15580 * @param {Object} publicKeyParams - Algorithm-specific public key parameters
15581 * @param {Object} privateKeyParams - Algorithm-specific private key parameters
15582 * @param {Object} sessionKeyParams - Encrypted session key parameters
15583 * @param {Uint8Array} fingerprint - Recipient fingerprint
15584 * @param {Uint8Array} [randomPayload] - Data to return on decryption error, instead of throwing
15585 * (needed for constant-time processing in RSA and ElGamal)
15586 * @returns {Promise<Uint8Array>} Decrypted data.
15587 * @throws {Error} on sensitive decryption error, unless `randomPayload` is given
15588 * @async
15589 */
15590async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint, randomPayload) {
15591 switch (algo) {
15592 case enums.publicKey.rsaEncryptSign:
15593 case enums.publicKey.rsaEncrypt: {
15594 const { c } = sessionKeyParams;
15595 const { n, e } = publicKeyParams;
15596 const { d, p, q, u } = privateKeyParams;
15597 return publicKey.rsa.decrypt(c, n, e, d, p, q, u, randomPayload);
15598 }
15599 case enums.publicKey.elgamal: {
15600 const { c1, c2 } = sessionKeyParams;
15601 const p = publicKeyParams.p;
15602 const x = privateKeyParams.x;
15603 return publicKey.elgamal.decrypt(c1, c2, p, x, randomPayload);
15604 }
15605 case enums.publicKey.ecdh: {
15606 const { oid, Q, kdfParams } = publicKeyParams;
15607 const { d } = privateKeyParams;
15608 const { V, C } = sessionKeyParams;
15609 return publicKey.elliptic.ecdh.decrypt(
15610 oid, kdfParams, V, C.data, Q, d, fingerprint);
15611 }
15612 case enums.publicKey.x25519: {
15613 const { A } = publicKeyParams;
15614 const { k } = privateKeyParams;
15615 const { ephemeralPublicKey, C } = sessionKeyParams;
15616 if (!util.isAES(C.algorithm)) {
15617 throw new Error('AES session key expected');
15618 }
15619 return publicKey.elliptic.ecdhX.decrypt(
15620 algo, ephemeralPublicKey, C.wrappedKey, A, k);
15621 }
15622 default:
15623 throw new Error('Unknown public key encryption algorithm.');
15624 }
15625}
15626
15627/**
15628 * Parse public key material in binary form to get the key parameters
15629 * @param {module:enums.publicKey} algo - The key algorithm
15630 * @param {Uint8Array} bytes - The key material to parse
15631 * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.
15632 */
15633function parsePublicKeyParams(algo, bytes) {
15634 let read = 0;
15635 switch (algo) {
15636 case enums.publicKey.rsaEncrypt:
15637 case enums.publicKey.rsaEncryptSign:
15638 case enums.publicKey.rsaSign: {
15639 const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;
15640 const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;
15641 return { read, publicParams: { n, e } };
15642 }
15643 case enums.publicKey.dsa: {
15644 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
15645 const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;
15646 const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;
15647 const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;
15648 return { read, publicParams: { p, q, g, y } };
15649 }
15650 case enums.publicKey.elgamal: {
15651 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
15652 const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;
15653 const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;
15654 return { read, publicParams: { p, g, y } };
15655 }
15656 case enums.publicKey.ecdsa: {
15657 const oid = new OID(); read += oid.read(bytes);
15658 checkSupportedCurve(oid);
15659 const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
15660 return { read: read, publicParams: { oid, Q } };
15661 }
15662 case enums.publicKey.eddsaLegacy: {
15663 const oid = new OID(); read += oid.read(bytes);
15664 checkSupportedCurve(oid);
15665 let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
15666 Q = util.leftPad(Q, 33);
15667 return { read: read, publicParams: { oid, Q } };
15668 }
15669 case enums.publicKey.ecdh: {
15670 const oid = new OID(); read += oid.read(bytes);
15671 checkSupportedCurve(oid);
15672 const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
15673 const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));
15674 return { read: read, publicParams: { oid, Q, kdfParams } };
15675 }
15676 case enums.publicKey.ed25519:
15677 case enums.publicKey.x25519: {
15678 const A = bytes.subarray(read, read + 32); read += A.length;
15679 return { read, publicParams: { A } };
15680 }
15681 default:
15682 throw new UnsupportedError('Unknown public key encryption algorithm.');
15683 }
15684}
15685
15686/**
15687 * Parse private key material in binary form to get the key parameters
15688 * @param {module:enums.publicKey} algo - The key algorithm
15689 * @param {Uint8Array} bytes - The key material to parse
15690 * @param {Object} publicParams - (ECC only) public params, needed to format some private params
15691 * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.
15692 */
15693function parsePrivateKeyParams(algo, bytes, publicParams) {
15694 let read = 0;
15695 switch (algo) {
15696 case enums.publicKey.rsaEncrypt:
15697 case enums.publicKey.rsaEncryptSign:
15698 case enums.publicKey.rsaSign: {
15699 const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;
15700 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
15701 const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;
15702 const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;
15703 return { read, privateParams: { d, p, q, u } };
15704 }
15705 case enums.publicKey.dsa:
15706 case enums.publicKey.elgamal: {
15707 const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;
15708 return { read, privateParams: { x } };
15709 }
15710 case enums.publicKey.ecdsa:
15711 case enums.publicKey.ecdh: {
15712 const curve = new CurveWithOID(publicParams.oid);
15713 let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;
15714 d = util.leftPad(d, curve.payloadSize);
15715 return { read, privateParams: { d } };
15716 }
15717 case enums.publicKey.eddsaLegacy: {
15718 const curve = new CurveWithOID(publicParams.oid);
15719 let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;
15720 seed = util.leftPad(seed, curve.payloadSize);
15721 return { read, privateParams: { seed } };
15722 }
15723 case enums.publicKey.ed25519: {
15724 const seed = bytes.subarray(read, read + 32); read += seed.length;
15725 return { read, privateParams: { seed } };
15726 }
15727 case enums.publicKey.x25519: {
15728 const k = bytes.subarray(read, read + 32); read += k.length;
15729 return { read, privateParams: { k } };
15730 }
15731 default:
15732 throw new UnsupportedError('Unknown public key encryption algorithm.');
15733 }
15734}
15735
15736/** Returns the types comprising the encrypted session key of an algorithm
15737 * @param {module:enums.publicKey} algo - The key algorithm
15738 * @param {Uint8Array} bytes - The key material to parse
15739 * @returns {Object} The session key parameters referenced by name.
15740 */
15741function parseEncSessionKeyParams(algo, bytes) {
15742 let read = 0;
15743 switch (algo) {
15744 // Algorithm-Specific Fields for RSA encrypted session keys:
15745 // - MPI of RSA encrypted value m**e mod n.
15746 case enums.publicKey.rsaEncrypt:
15747 case enums.publicKey.rsaEncryptSign: {
15748 const c = util.readMPI(bytes.subarray(read));
15749 return { c };
15750 }
15751
15752 // Algorithm-Specific Fields for Elgamal encrypted session keys:
15753 // - MPI of Elgamal value g**k mod p
15754 // - MPI of Elgamal value m * y**k mod p
15755 case enums.publicKey.elgamal: {
15756 const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;
15757 const c2 = util.readMPI(bytes.subarray(read));
15758 return { c1, c2 };
15759 }
15760 // Algorithm-Specific Fields for ECDH encrypted session keys:
15761 // - MPI containing the ephemeral key used to establish the shared secret
15762 // - ECDH Symmetric Key
15763 case enums.publicKey.ecdh: {
15764 const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;
15765 const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read));
15766 return { V, C };
15767 }
15768 // Algorithm-Specific Fields for X25519 encrypted session keys:
15769 // - 32 octets representing an ephemeral X25519 public key.
15770 // - A one-octet size of the following fields.
15771 // - The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet).
15772 // - The encrypted session key.
15773 case enums.publicKey.x25519: {
15774 const ephemeralPublicKey = bytes.subarray(read, read + 32); read += ephemeralPublicKey.length;
15775 const C = new ECDHXSymmetricKey(); C.read(bytes.subarray(read));
15776 return { ephemeralPublicKey, C };
15777 }
15778 default:
15779 throw new UnsupportedError('Unknown public key encryption algorithm.');
15780 }
15781}
15782
15783/**
15784 * Convert params to MPI and serializes them in the proper order
15785 * @param {module:enums.publicKey} algo - The public key algorithm
15786 * @param {Object} params - The key parameters indexed by name
15787 * @returns {Uint8Array} The array containing the MPIs.
15788 */
15789function serializeParams(algo, params) {
15790 // Some algorithms do not rely on MPIs to store the binary params
15791 const algosWithNativeRepresentation = new Set([enums.publicKey.ed25519, enums.publicKey.x25519]);
15792 const orderedParams = Object.keys(params).map(name => {
15793 const param = params[name];
15794 if (!util.isUint8Array(param)) return param.write();
15795 return algosWithNativeRepresentation.has(algo) ? param : util.uint8ArrayToMPI(param);
15796 });
15797 return util.concatUint8Array(orderedParams);
15798}
15799
15800/**
15801 * Generate algorithm-specific key parameters
15802 * @param {module:enums.publicKey} algo - The public key algorithm
15803 * @param {Integer} bits - Bit length for RSA keys
15804 * @param {module:type/oid} oid - Object identifier for ECC keys
15805 * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.
15806 * @async
15807 */
15808function generateParams(algo, bits, oid) {
15809 switch (algo) {
15810 case enums.publicKey.rsaEncrypt:
15811 case enums.publicKey.rsaEncryptSign:
15812 case enums.publicKey.rsaSign: {
15813 return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({
15814 privateParams: { d, p, q, u },
15815 publicParams: { n, e }
15816 }));
15817 }
15818 case enums.publicKey.ecdsa:
15819 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({
15820 privateParams: { d: secret },
15821 publicParams: { oid: new OID(oid), Q }
15822 }));
15823 case enums.publicKey.eddsaLegacy:
15824 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({
15825 privateParams: { seed: secret },
15826 publicParams: { oid: new OID(oid), Q }
15827 }));
15828 case enums.publicKey.ecdh:
15829 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({
15830 privateParams: { d: secret },
15831 publicParams: {
15832 oid: new OID(oid),
15833 Q,
15834 kdfParams: new KDFParams({ hash, cipher })
15835 }
15836 }));
15837 case enums.publicKey.ed25519:
15838 return publicKey.elliptic.eddsa.generate(algo).then(({ A, seed }) => ({
15839 privateParams: { seed },
15840 publicParams: { A }
15841 }));
15842 case enums.publicKey.x25519:
15843 return publicKey.elliptic.ecdhX.generate(algo).then(({ A, k }) => ({
15844 privateParams: { k },
15845 publicParams: { A }
15846 }));
15847 case enums.publicKey.dsa:
15848 case enums.publicKey.elgamal:
15849 throw new Error('Unsupported algorithm for key generation.');
15850 default:
15851 throw new Error('Unknown public key algorithm.');
15852 }
15853}
15854
15855/**
15856 * Validate algorithm-specific key parameters
15857 * @param {module:enums.publicKey} algo - The public key algorithm
15858 * @param {Object} publicParams - Algorithm-specific public key parameters
15859 * @param {Object} privateParams - Algorithm-specific private key parameters
15860 * @returns {Promise<Boolean>} Whether the parameters are valid.
15861 * @async
15862 */
15863async function validateParams$8(algo, publicParams, privateParams) {
15864 if (!publicParams || !privateParams) {
15865 throw new Error('Missing key parameters');
15866 }
15867 switch (algo) {
15868 case enums.publicKey.rsaEncrypt:
15869 case enums.publicKey.rsaEncryptSign:
15870 case enums.publicKey.rsaSign: {
15871 const { n, e } = publicParams;
15872 const { d, p, q, u } = privateParams;
15873 return publicKey.rsa.validateParams(n, e, d, p, q, u);
15874 }
15875 case enums.publicKey.dsa: {
15876 const { p, q, g, y } = publicParams;
15877 const { x } = privateParams;
15878 return publicKey.dsa.validateParams(p, q, g, y, x);
15879 }
15880 case enums.publicKey.elgamal: {
15881 const { p, g, y } = publicParams;
15882 const { x } = privateParams;
15883 return publicKey.elgamal.validateParams(p, g, y, x);
15884 }
15885 case enums.publicKey.ecdsa:
15886 case enums.publicKey.ecdh: {
15887 const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];
15888 const { oid, Q } = publicParams;
15889 const { d } = privateParams;
15890 return algoModule.validateParams(oid, Q, d);
15891 }
15892 case enums.publicKey.eddsaLegacy: {
15893 const { Q, oid } = publicParams;
15894 const { seed } = privateParams;
15895 return publicKey.elliptic.eddsaLegacy.validateParams(oid, Q, seed);
15896 }
15897 case enums.publicKey.ed25519: {
15898 const { A } = publicParams;
15899 const { seed } = privateParams;
15900 return publicKey.elliptic.eddsa.validateParams(algo, A, seed);
15901 }
15902 case enums.publicKey.x25519: {
15903 const { A } = publicParams;
15904 const { k } = privateParams;
15905 return publicKey.elliptic.ecdhX.validateParams(algo, A, k);
15906 }
15907 default:
15908 throw new Error('Unknown public key algorithm.');
15909 }
15910}
15911
15912/**
15913 * Generates a random byte prefix for the specified algorithm
15914 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
15915 * @param {module:enums.symmetric} algo - Symmetric encryption algorithm
15916 * @returns {Promise<Uint8Array>} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.
15917 * @async
15918 */
15919async function getPrefixRandom(algo) {
15920 const { blockSize } = getCipher(algo);
15921 const prefixrandom = await getRandomBytes(blockSize);
15922 const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);
15923 return util.concat([prefixrandom, repeat]);
15924}
15925
15926/**
15927 * Generating a session key for the specified symmetric algorithm
15928 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
15929 * @param {module:enums.symmetric} algo - Symmetric encryption algorithm
15930 * @returns {Uint8Array} Random bytes as a string to be used as a key.
15931 */
15932function generateSessionKey(algo) {
15933 const { keySize } = getCipher(algo);
15934 return getRandomBytes(keySize);
15935}
15936
15937/**
15938 * Get implementation of the given AEAD mode
15939 * @param {enums.aead} algo
15940 * @returns {Object}
15941 * @throws {Error} on invalid algo
15942 */
15943function getAEADMode(algo) {
15944 const algoName = enums.read(enums.aead, algo);
15945 return mode[algoName];
15946}
15947
15948/**
15949 * Check whether the given curve OID is supported
15950 * @param {module:type/oid} oid - EC object identifier
15951 * @throws {UnsupportedError} if curve is not supported
15952 */
15953function checkSupportedCurve(oid) {
15954 try {
15955 oid.getName();
15956 } catch (e) {
15957 throw new UnsupportedError('Unknown curve OID');
15958 }
15959}
15960
15961/**
15962 * Get preferred hash algo for a given elliptic algo
15963 * @param {module:enums.publicKey} algo - alrogithm identifier
15964 * @param {module:type/oid} [oid] - curve OID if needed by algo
15965 */
15966function getPreferredCurveHashAlgo(algo, oid) {
15967 switch (algo) {
15968 case enums.publicKey.ecdsa:
15969 case enums.publicKey.eddsaLegacy:
15970 return publicKey.elliptic.getPreferredHashAlgo(oid);
15971 case enums.publicKey.ed25519:
15972 return publicKey.elliptic.eddsa.getPreferredHashAlgo(algo);
15973 default:
15974 throw new Error('Unknown elliptic signing algo');
15975 }
15976}
15977
15978var crypto$1 = /*#__PURE__*/Object.freeze({
15979 __proto__: null,
15980 publicKeyEncrypt: publicKeyEncrypt,
15981 publicKeyDecrypt: publicKeyDecrypt,
15982 parsePublicKeyParams: parsePublicKeyParams,
15983 parsePrivateKeyParams: parsePrivateKeyParams,
15984 parseEncSessionKeyParams: parseEncSessionKeyParams,
15985 serializeParams: serializeParams,
15986 generateParams: generateParams,
15987 validateParams: validateParams$8,
15988 getPrefixRandom: getPrefixRandom,
15989 generateSessionKey: generateSessionKey,
15990 getAEADMode: getAEADMode,
15991 getCipher: getCipher,
15992 getPreferredCurveHashAlgo: getPreferredCurveHashAlgo
15993});
15994
15995/**
15996 * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js
15997 * @see module:crypto/crypto
15998 * @see module:crypto/signature
15999 * @see module:crypto/public_key
16000 * @see module:crypto/cipher
16001 * @see module:crypto/random
16002 * @see module:crypto/hash
16003 * @module crypto
16004 * @private
16005 */
16006
16007// TODO move cfb and gcm to cipher
16008const mod = {
16009 /** @see module:crypto/cipher */
16010 cipher: cipher,
16011 /** @see module:crypto/hash */
16012 hash: hash,
16013 /** @see module:crypto/mode */
16014 mode: mode,
16015 /** @see module:crypto/public_key */
16016 publicKey: publicKey,
16017 /** @see module:crypto/signature */
16018 signature: signature,
16019 /** @see module:crypto/random */
16020 random: random,
16021 /** @see module:crypto/pkcs1 */
16022 pkcs1: pkcs1,
16023 /** @see module:crypto/pkcs5 */
16024 pkcs5: pkcs5,
16025 /** @see module:crypto/aes_kw */
16026 aesKW: aesKW
16027};
16028
16029Object.assign(mod, crypto$1);
16030
16031var TYPED_OK = typeof Uint8Array !== "undefined" &&
16032 typeof Uint16Array !== "undefined" &&
16033 typeof Int32Array !== "undefined";
16034
16035
16036// reduce buffer size, avoiding mem copy
16037function shrinkBuf(buf, size) {
16038 if (buf.length === size) {
16039 return buf;
16040 }
16041 if (buf.subarray) {
16042 return buf.subarray(0, size);
16043 }
16044 buf.length = size;
16045 return buf;
16046}
16047
16048
16049const fnTyped = {
16050 arraySet: function (dest, src, src_offs, len, dest_offs) {
16051 if (src.subarray && dest.subarray) {
16052 dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
16053 return;
16054 }
16055 // Fallback to ordinary array
16056 for (let i = 0; i < len; i++) {
16057 dest[dest_offs + i] = src[src_offs + i];
16058 }
16059 },
16060 // Join array of chunks to single array.
16061 flattenChunks: function (chunks) {
16062 let i, l, len, pos, chunk;
16063
16064 // calculate data length
16065 len = 0;
16066 for (i = 0, l = chunks.length; i < l; i++) {
16067 len += chunks[i].length;
16068 }
16069
16070 // join chunks
16071 const result = new Uint8Array(len);
16072 pos = 0;
16073 for (i = 0, l = chunks.length; i < l; i++) {
16074 chunk = chunks[i];
16075 result.set(chunk, pos);
16076 pos += chunk.length;
16077 }
16078
16079 return result;
16080 }
16081};
16082
16083const fnUntyped = {
16084 arraySet: function (dest, src, src_offs, len, dest_offs) {
16085 for (let i = 0; i < len; i++) {
16086 dest[dest_offs + i] = src[src_offs + i];
16087 }
16088 },
16089 // Join array of chunks to single array.
16090 flattenChunks: function (chunks) {
16091 return [].concat.apply([], chunks);
16092 }
16093};
16094
16095
16096// Enable/Disable typed arrays use, for testing
16097//
16098
16099let Buf8 = TYPED_OK ? Uint8Array : Array;
16100let Buf16 = TYPED_OK ? Uint16Array : Array;
16101let Buf32 = TYPED_OK ? Int32Array : Array;
16102let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks;
16103let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet;
16104
16105// (C) 1995-2013 Jean-loup Gailly and Mark Adler
16106// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
16107//
16108// This software is provided 'as-is', without any express or implied
16109// warranty. In no event will the authors be held liable for any damages
16110// arising from the use of this software.
16111//
16112// Permission is granted to anyone to use this software for any purpose,
16113// including commercial applications, and to alter it and redistribute it
16114// freely, subject to the following restrictions:
16115//
16116// 1. The origin of this software must not be misrepresented; you must not
16117// claim that you wrote the original software. If you use this software
16118// in a product, an acknowledgment in the product documentation would be
16119// appreciated but is not required.
16120// 2. Altered source versions must be plainly marked as such, and must not be
16121// misrepresented as being the original software.
16122// 3. This notice may not be removed or altered from any source distribution.
16123
16124/* Allowed flush values; see deflate() and inflate() below for details */
16125const Z_NO_FLUSH = 0;
16126const Z_PARTIAL_FLUSH = 1;
16127const Z_SYNC_FLUSH = 2;
16128const Z_FULL_FLUSH = 3;
16129const Z_FINISH = 4;
16130const Z_BLOCK = 5;
16131const Z_TREES = 6;
16132
16133/* Return codes for the compression/decompression functions. Negative values
16134 * are errors, positive values are used for special but normal events.
16135 */
16136const Z_OK = 0;
16137const Z_STREAM_END = 1;
16138const Z_NEED_DICT = 2;
16139const Z_STREAM_ERROR = -2;
16140const Z_DATA_ERROR = -3;
16141//export const Z_MEM_ERROR = -4;
16142const Z_BUF_ERROR = -5;
16143const Z_DEFAULT_COMPRESSION = -1;
16144
16145
16146const Z_FILTERED = 1;
16147const Z_HUFFMAN_ONLY = 2;
16148const Z_RLE = 3;
16149const Z_FIXED = 4;
16150const Z_DEFAULT_STRATEGY = 0;
16151
16152/* Possible values of the data_type field (though see inflate()) */
16153const Z_BINARY = 0;
16154const Z_TEXT = 1;
16155//export const Z_ASCII = 1; // = Z_TEXT (deprecated)
16156const Z_UNKNOWN = 2;
16157
16158/* The deflate compression method */
16159const Z_DEFLATED = 8;
16160//export const Z_NULL = null // Use -1 or null inline, depending on var type
16161
16162/*============================================================================*/
16163
16164
16165function zero$1(buf) {
16166 let len = buf.length; while (--len >= 0) {
16167 buf[len] = 0;
16168 }
16169}
16170
16171// From zutil.h
16172
16173const STORED_BLOCK = 0;
16174const STATIC_TREES = 1;
16175const DYN_TREES = 2;
16176/* The three kinds of block type */
16177
16178const MIN_MATCH = 3;
16179const MAX_MATCH = 258;
16180/* The minimum and maximum match lengths */
16181
16182// From deflate.h
16183/* ===========================================================================
16184 * Internal compression state.
16185 */
16186
16187const LENGTH_CODES = 29;
16188/* number of length codes, not counting the special END_BLOCK code */
16189
16190const LITERALS = 256;
16191/* number of literal bytes 0..255 */
16192
16193const L_CODES = LITERALS + 1 + LENGTH_CODES;
16194/* number of Literal or Length codes, including the END_BLOCK code */
16195
16196const D_CODES = 30;
16197/* number of distance codes */
16198
16199const BL_CODES = 19;
16200/* number of codes used to transfer the bit lengths */
16201
16202const HEAP_SIZE = 2 * L_CODES + 1;
16203/* maximum heap size */
16204
16205const MAX_BITS = 15;
16206/* All codes must not exceed MAX_BITS bits */
16207
16208const Buf_size = 16;
16209/* size of bit buffer in bi_buf */
16210
16211
16212/* ===========================================================================
16213 * Constants
16214 */
16215
16216const MAX_BL_BITS = 7;
16217/* Bit length codes must not exceed MAX_BL_BITS bits */
16218
16219const END_BLOCK = 256;
16220/* end of block literal code */
16221
16222const REP_3_6 = 16;
16223/* repeat previous bit length 3-6 times (2 bits of repeat count) */
16224
16225const REPZ_3_10 = 17;
16226/* repeat a zero length 3-10 times (3 bits of repeat count) */
16227
16228const REPZ_11_138 = 18;
16229/* repeat a zero length 11-138 times (7 bits of repeat count) */
16230
16231/* eslint-disable comma-spacing,array-bracket-spacing */
16232const extra_lbits = /* extra bits for each length code */
16233 [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];
16234
16235const extra_dbits = /* extra bits for each distance code */
16236 [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];
16237
16238const extra_blbits = /* extra bits for each bit length code */
16239 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
16240
16241const bl_order =
16242 [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
16243/* eslint-enable comma-spacing,array-bracket-spacing */
16244
16245/* The lengths of the bit length codes are sent in order of decreasing
16246 * probability, to avoid transmitting the lengths for unused bit length codes.
16247 */
16248
16249/* ===========================================================================
16250 * Local data. These are initialized only once.
16251 */
16252
16253// We pre-fill arrays with 0 to avoid uninitialized gaps
16254
16255const DIST_CODE_LEN = 512; /* see definition of array dist_code below */
16256
16257// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
16258const static_ltree = new Array((L_CODES + 2) * 2);
16259zero$1(static_ltree);
16260/* The static literal tree. Since the bit lengths are imposed, there is no
16261 * need for the L_CODES extra codes used during heap construction. However
16262 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
16263 * below).
16264 */
16265
16266const static_dtree = new Array(D_CODES * 2);
16267zero$1(static_dtree);
16268/* The static distance tree. (Actually a trivial tree since all codes use
16269 * 5 bits.)
16270 */
16271
16272const _dist_code = new Array(DIST_CODE_LEN);
16273zero$1(_dist_code);
16274/* Distance codes. The first 256 values correspond to the distances
16275 * 3 .. 258, the last 256 values correspond to the top 8 bits of
16276 * the 15 bit distances.
16277 */
16278
16279const _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
16280zero$1(_length_code);
16281/* length code for each normalized match length (0 == MIN_MATCH) */
16282
16283const base_length = new Array(LENGTH_CODES);
16284zero$1(base_length);
16285/* First normalized length for each code (0 = MIN_MATCH) */
16286
16287const base_dist = new Array(D_CODES);
16288zero$1(base_dist);
16289/* First normalized distance for each code (0 = distance of 1) */
16290
16291
16292function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
16293
16294 this.static_tree = static_tree; /* static tree or NULL */
16295 this.extra_bits = extra_bits; /* extra bits for each code or NULL */
16296 this.extra_base = extra_base; /* base index for extra_bits */
16297 this.elems = elems; /* max number of elements in the tree */
16298 this.max_length = max_length; /* max bit length for the codes */
16299
16300 // show if `static_tree` has data or dummy - needed for monomorphic objects
16301 this.has_stree = static_tree && static_tree.length;
16302}
16303
16304
16305let static_l_desc;
16306let static_d_desc;
16307let static_bl_desc;
16308
16309
16310function TreeDesc(dyn_tree, stat_desc) {
16311 this.dyn_tree = dyn_tree; /* the dynamic tree */
16312 this.max_code = 0; /* largest code with non zero frequency */
16313 this.stat_desc = stat_desc; /* the corresponding static tree */
16314}
16315
16316
16317
16318function d_code(dist) {
16319 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
16320}
16321
16322
16323/* ===========================================================================
16324 * Output a short LSB first on the stream.
16325 * IN assertion: there is enough room in pendingBuf.
16326 */
16327function put_short(s, w) {
16328// put_byte(s, (uch)((w) & 0xff));
16329// put_byte(s, (uch)((ush)(w) >> 8));
16330 s.pending_buf[s.pending++] = w & 0xff;
16331 s.pending_buf[s.pending++] = w >>> 8 & 0xff;
16332}
16333
16334
16335/* ===========================================================================
16336 * Send a value on a given number of bits.
16337 * IN assertion: length <= 16 and value fits in length bits.
16338 */
16339function send_bits(s, value, length) {
16340 if (s.bi_valid > Buf_size - length) {
16341 s.bi_buf |= value << s.bi_valid & 0xffff;
16342 put_short(s, s.bi_buf);
16343 s.bi_buf = value >> Buf_size - s.bi_valid;
16344 s.bi_valid += length - Buf_size;
16345 } else {
16346 s.bi_buf |= value << s.bi_valid & 0xffff;
16347 s.bi_valid += length;
16348 }
16349}
16350
16351
16352function send_code(s, c, tree) {
16353 send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
16354}
16355
16356
16357/* ===========================================================================
16358 * Reverse the first len bits of a code, using straightforward code (a faster
16359 * method would use a table)
16360 * IN assertion: 1 <= len <= 15
16361 */
16362function bi_reverse(code, len) {
16363 let res = 0;
16364 do {
16365 res |= code & 1;
16366 code >>>= 1;
16367 res <<= 1;
16368 } while (--len > 0);
16369 return res >>> 1;
16370}
16371
16372
16373/* ===========================================================================
16374 * Flush the bit buffer, keeping at most 7 bits in it.
16375 */
16376function bi_flush(s) {
16377 if (s.bi_valid === 16) {
16378 put_short(s, s.bi_buf);
16379 s.bi_buf = 0;
16380 s.bi_valid = 0;
16381
16382 } else if (s.bi_valid >= 8) {
16383 s.pending_buf[s.pending++] = s.bi_buf & 0xff;
16384 s.bi_buf >>= 8;
16385 s.bi_valid -= 8;
16386 }
16387}
16388
16389
16390/* ===========================================================================
16391 * Compute the optimal bit lengths for a tree and update the total bit length
16392 * for the current block.
16393 * IN assertion: the fields freq and dad are set, heap[heap_max] and
16394 * above are the tree nodes sorted by increasing frequency.
16395 * OUT assertions: the field len is set to the optimal bit length, the
16396 * array bl_count contains the frequencies for each bit length.
16397 * The length opt_len is updated; static_len is also updated if stree is
16398 * not null.
16399 */
16400function gen_bitlen(s, desc)
16401// deflate_state *s;
16402// tree_desc *desc; /* the tree descriptor */
16403{
16404 const tree = desc.dyn_tree;
16405 const max_code = desc.max_code;
16406 const stree = desc.stat_desc.static_tree;
16407 const has_stree = desc.stat_desc.has_stree;
16408 const extra = desc.stat_desc.extra_bits;
16409 const base = desc.stat_desc.extra_base;
16410 const max_length = desc.stat_desc.max_length;
16411 let h; /* heap index */
16412 let n, m; /* iterate over the tree elements */
16413 let bits; /* bit length */
16414 let xbits; /* extra bits */
16415 let f; /* frequency */
16416 let overflow = 0; /* number of elements with bit length too large */
16417
16418 for (bits = 0; bits <= MAX_BITS; bits++) {
16419 s.bl_count[bits] = 0;
16420 }
16421
16422 /* In a first pass, compute the optimal bit lengths (which may
16423 * overflow in the case of the bit length tree).
16424 */
16425 tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
16426
16427 for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
16428 n = s.heap[h];
16429 bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
16430 if (bits > max_length) {
16431 bits = max_length;
16432 overflow++;
16433 }
16434 tree[n * 2 + 1]/*.Len*/ = bits;
16435 /* We overwrite tree[n].Dad which is no longer needed */
16436
16437 if (n > max_code) {
16438 continue;
16439 } /* not a leaf node */
16440
16441 s.bl_count[bits]++;
16442 xbits = 0;
16443 if (n >= base) {
16444 xbits = extra[n - base];
16445 }
16446 f = tree[n * 2]/*.Freq*/;
16447 s.opt_len += f * (bits + xbits);
16448 if (has_stree) {
16449 s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
16450 }
16451 }
16452 if (overflow === 0) {
16453 return;
16454 }
16455
16456 // Trace((stderr,"\nbit length overflow\n"));
16457 /* This happens for example on obj2 and pic of the Calgary corpus */
16458
16459 /* Find the first bit length which could increase: */
16460 do {
16461 bits = max_length - 1;
16462 while (s.bl_count[bits] === 0) {
16463 bits--;
16464 }
16465 s.bl_count[bits]--; /* move one leaf down the tree */
16466 s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
16467 s.bl_count[max_length]--;
16468 /* The brother of the overflow item also moves one step up,
16469 * but this does not affect bl_count[max_length]
16470 */
16471 overflow -= 2;
16472 } while (overflow > 0);
16473
16474 /* Now recompute all bit lengths, scanning in increasing frequency.
16475 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
16476 * lengths instead of fixing only the wrong ones. This idea is taken
16477 * from 'ar' written by Haruhiko Okumura.)
16478 */
16479 for (bits = max_length; bits !== 0; bits--) {
16480 n = s.bl_count[bits];
16481 while (n !== 0) {
16482 m = s.heap[--h];
16483 if (m > max_code) {
16484 continue;
16485 }
16486 if (tree[m * 2 + 1]/*.Len*/ !== bits) {
16487 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
16488 s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
16489 tree[m * 2 + 1]/*.Len*/ = bits;
16490 }
16491 n--;
16492 }
16493 }
16494}
16495
16496
16497/* ===========================================================================
16498 * Generate the codes for a given tree and bit counts (which need not be
16499 * optimal).
16500 * IN assertion: the array bl_count contains the bit length statistics for
16501 * the given tree and the field len is set for all tree elements.
16502 * OUT assertion: the field code is set for all tree elements of non
16503 * zero code length.
16504 */
16505function gen_codes(tree, max_code, bl_count)
16506// ct_data *tree; /* the tree to decorate */
16507// int max_code; /* largest code with non zero frequency */
16508// ushf *bl_count; /* number of codes at each bit length */
16509{
16510 const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
16511 let code = 0; /* running code value */
16512 let bits; /* bit index */
16513 let n; /* code index */
16514
16515 /* The distribution counts are first used to generate the code values
16516 * without bit reversal.
16517 */
16518 for (bits = 1; bits <= MAX_BITS; bits++) {
16519 next_code[bits] = code = code + bl_count[bits - 1] << 1;
16520 }
16521 /* Check that the bit counts in bl_count are consistent. The last code
16522 * must be all ones.
16523 */
16524 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
16525 // "inconsistent bit counts");
16526 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
16527
16528 for (n = 0; n <= max_code; n++) {
16529 const len = tree[n * 2 + 1]/*.Len*/;
16530 if (len === 0) {
16531 continue;
16532 }
16533 /* Now reverse the bits */
16534 tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
16535
16536 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
16537 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
16538 }
16539}
16540
16541
16542/* ===========================================================================
16543 * Initialize the various 'constant' tables.
16544 */
16545function tr_static_init() {
16546 let n; /* iterates over tree elements */
16547 let bits; /* bit counter */
16548 let length; /* length value */
16549 let code; /* code value */
16550 let dist; /* distance index */
16551 const bl_count = new Array(MAX_BITS + 1);
16552 /* number of codes at each bit length for an optimal tree */
16553
16554 // do check in _tr_init()
16555 //if (static_init_done) return;
16556
16557 /* For some embedded targets, global variables are not initialized: */
16558 /*#ifdef NO_INIT_GLOBAL_POINTERS
16559 static_l_desc.static_tree = static_ltree;
16560 static_l_desc.extra_bits = extra_lbits;
16561 static_d_desc.static_tree = static_dtree;
16562 static_d_desc.extra_bits = extra_dbits;
16563 static_bl_desc.extra_bits = extra_blbits;
16564#endif*/
16565
16566 /* Initialize the mapping length (0..255) -> length code (0..28) */
16567 length = 0;
16568 for (code = 0; code < LENGTH_CODES - 1; code++) {
16569 base_length[code] = length;
16570 for (n = 0; n < 1 << extra_lbits[code]; n++) {
16571 _length_code[length++] = code;
16572 }
16573 }
16574 //Assert (length == 256, "tr_static_init: length != 256");
16575 /* Note that the length 255 (match length 258) can be represented
16576 * in two different ways: code 284 + 5 bits or code 285, so we
16577 * overwrite length_code[255] to use the best encoding:
16578 */
16579 _length_code[length - 1] = code;
16580
16581 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
16582 dist = 0;
16583 for (code = 0; code < 16; code++) {
16584 base_dist[code] = dist;
16585 for (n = 0; n < 1 << extra_dbits[code]; n++) {
16586 _dist_code[dist++] = code;
16587 }
16588 }
16589 //Assert (dist == 256, "tr_static_init: dist != 256");
16590 dist >>= 7; /* from now on, all distances are divided by 128 */
16591 for (; code < D_CODES; code++) {
16592 base_dist[code] = dist << 7;
16593 for (n = 0; n < 1 << extra_dbits[code] - 7; n++) {
16594 _dist_code[256 + dist++] = code;
16595 }
16596 }
16597 //Assert (dist == 256, "tr_static_init: 256+dist != 512");
16598
16599 /* Construct the codes of the static literal tree */
16600 for (bits = 0; bits <= MAX_BITS; bits++) {
16601 bl_count[bits] = 0;
16602 }
16603
16604 n = 0;
16605 while (n <= 143) {
16606 static_ltree[n * 2 + 1]/*.Len*/ = 8;
16607 n++;
16608 bl_count[8]++;
16609 }
16610 while (n <= 255) {
16611 static_ltree[n * 2 + 1]/*.Len*/ = 9;
16612 n++;
16613 bl_count[9]++;
16614 }
16615 while (n <= 279) {
16616 static_ltree[n * 2 + 1]/*.Len*/ = 7;
16617 n++;
16618 bl_count[7]++;
16619 }
16620 while (n <= 287) {
16621 static_ltree[n * 2 + 1]/*.Len*/ = 8;
16622 n++;
16623 bl_count[8]++;
16624 }
16625 /* Codes 286 and 287 do not exist, but we must include them in the
16626 * tree construction to get a canonical Huffman tree (longest code
16627 * all ones)
16628 */
16629 gen_codes(static_ltree, L_CODES + 1, bl_count);
16630
16631 /* The static distance tree is trivial: */
16632 for (n = 0; n < D_CODES; n++) {
16633 static_dtree[n * 2 + 1]/*.Len*/ = 5;
16634 static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
16635 }
16636
16637 // Now data ready and we can init static trees
16638 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
16639 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
16640 static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
16641
16642 //static_init_done = true;
16643}
16644
16645
16646/* ===========================================================================
16647 * Initialize a new block.
16648 */
16649function init_block(s) {
16650 let n; /* iterates over tree elements */
16651
16652 /* Initialize the trees. */
16653 for (n = 0; n < L_CODES; n++) {
16654 s.dyn_ltree[n * 2]/*.Freq*/ = 0;
16655 }
16656 for (n = 0; n < D_CODES; n++) {
16657 s.dyn_dtree[n * 2]/*.Freq*/ = 0;
16658 }
16659 for (n = 0; n < BL_CODES; n++) {
16660 s.bl_tree[n * 2]/*.Freq*/ = 0;
16661 }
16662
16663 s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
16664 s.opt_len = s.static_len = 0;
16665 s.last_lit = s.matches = 0;
16666}
16667
16668
16669/* ===========================================================================
16670 * Flush the bit buffer and align the output on a byte boundary
16671 */
16672function bi_windup(s) {
16673 if (s.bi_valid > 8) {
16674 put_short(s, s.bi_buf);
16675 } else if (s.bi_valid > 0) {
16676 //put_byte(s, (Byte)s->bi_buf);
16677 s.pending_buf[s.pending++] = s.bi_buf;
16678 }
16679 s.bi_buf = 0;
16680 s.bi_valid = 0;
16681}
16682
16683/* ===========================================================================
16684 * Copy a stored block, storing first the length and its
16685 * one's complement if requested.
16686 */
16687function copy_block(s, buf, len, header)
16688//DeflateState *s;
16689//charf *buf; /* the input data */
16690//unsigned len; /* its length */
16691//int header; /* true if block header must be written */
16692{
16693 bi_windup(s); /* align on byte boundary */
16694
16695 if (header) {
16696 put_short(s, len);
16697 put_short(s, ~len);
16698 }
16699 // while (len--) {
16700 // put_byte(s, *buf++);
16701 // }
16702 arraySet(s.pending_buf, s.window, buf, len, s.pending);
16703 s.pending += len;
16704}
16705
16706/* ===========================================================================
16707 * Compares to subtrees, using the tree depth as tie breaker when
16708 * the subtrees have equal frequency. This minimizes the worst case length.
16709 */
16710function smaller(tree, n, m, depth) {
16711 const _n2 = n * 2;
16712 const _m2 = m * 2;
16713 return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
16714 tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m];
16715}
16716
16717/* ===========================================================================
16718 * Restore the heap property by moving down the tree starting at node k,
16719 * exchanging a node with the smallest of its two sons if necessary, stopping
16720 * when the heap property is re-established (each father smaller than its
16721 * two sons).
16722 */
16723function pqdownheap(s, tree, k)
16724// deflate_state *s;
16725// ct_data *tree; /* the tree to restore */
16726// int k; /* node to move down */
16727{
16728 const v = s.heap[k];
16729 let j = k << 1; /* left son of k */
16730 while (j <= s.heap_len) {
16731 /* Set j to the smallest of the two sons: */
16732 if (j < s.heap_len &&
16733 smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
16734 j++;
16735 }
16736 /* Exit if v is smaller than both sons */
16737 if (smaller(tree, v, s.heap[j], s.depth)) {
16738 break;
16739 }
16740
16741 /* Exchange v with the smallest son */
16742 s.heap[k] = s.heap[j];
16743 k = j;
16744
16745 /* And continue down the tree, setting j to the left son of k */
16746 j <<= 1;
16747 }
16748 s.heap[k] = v;
16749}
16750
16751
16752// inlined manually
16753// var SMALLEST = 1;
16754
16755/* ===========================================================================
16756 * Send the block data compressed using the given Huffman trees
16757 */
16758function compress_block(s, ltree, dtree)
16759// deflate_state *s;
16760// const ct_data *ltree; /* literal tree */
16761// const ct_data *dtree; /* distance tree */
16762{
16763 let dist; /* distance of matched string */
16764 let lc; /* match length or unmatched char (if dist == 0) */
16765 let lx = 0; /* running index in l_buf */
16766 let code; /* the code to send */
16767 let extra; /* number of extra bits to send */
16768
16769 if (s.last_lit !== 0) {
16770 do {
16771 dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1];
16772 lc = s.pending_buf[s.l_buf + lx];
16773 lx++;
16774
16775 if (dist === 0) {
16776 send_code(s, lc, ltree); /* send a literal byte */
16777 //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
16778 } else {
16779 /* Here, lc is the match length - MIN_MATCH */
16780 code = _length_code[lc];
16781 send_code(s, code + LITERALS + 1, ltree); /* send the length code */
16782 extra = extra_lbits[code];
16783 if (extra !== 0) {
16784 lc -= base_length[code];
16785 send_bits(s, lc, extra); /* send the extra length bits */
16786 }
16787 dist--; /* dist is now the match distance - 1 */
16788 code = d_code(dist);
16789 //Assert (code < D_CODES, "bad d_code");
16790
16791 send_code(s, code, dtree); /* send the distance code */
16792 extra = extra_dbits[code];
16793 if (extra !== 0) {
16794 dist -= base_dist[code];
16795 send_bits(s, dist, extra); /* send the extra distance bits */
16796 }
16797 } /* literal or match pair ? */
16798
16799 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
16800 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
16801 // "pendingBuf overflow");
16802
16803 } while (lx < s.last_lit);
16804 }
16805
16806 send_code(s, END_BLOCK, ltree);
16807}
16808
16809
16810/* ===========================================================================
16811 * Construct one Huffman tree and assigns the code bit strings and lengths.
16812 * Update the total bit length for the current block.
16813 * IN assertion: the field freq is set for all tree elements.
16814 * OUT assertions: the fields len and code are set to the optimal bit length
16815 * and corresponding code. The length opt_len is updated; static_len is
16816 * also updated if stree is not null. The field max_code is set.
16817 */
16818function build_tree(s, desc)
16819// deflate_state *s;
16820// tree_desc *desc; /* the tree descriptor */
16821{
16822 const tree = desc.dyn_tree;
16823 const stree = desc.stat_desc.static_tree;
16824 const has_stree = desc.stat_desc.has_stree;
16825 const elems = desc.stat_desc.elems;
16826 let n, m; /* iterate over heap elements */
16827 let max_code = -1; /* largest code with non zero frequency */
16828 let node; /* new node being created */
16829
16830 /* Construct the initial heap, with least frequent element in
16831 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
16832 * heap[0] is not used.
16833 */
16834 s.heap_len = 0;
16835 s.heap_max = HEAP_SIZE;
16836
16837 for (n = 0; n < elems; n++) {
16838 if (tree[n * 2]/*.Freq*/ !== 0) {
16839 s.heap[++s.heap_len] = max_code = n;
16840 s.depth[n] = 0;
16841
16842 } else {
16843 tree[n * 2 + 1]/*.Len*/ = 0;
16844 }
16845 }
16846
16847 /* The pkzip format requires that at least one distance code exists,
16848 * and that at least one bit should be sent even if there is only one
16849 * possible code. So to avoid special checks later on we force at least
16850 * two codes of non zero frequency.
16851 */
16852 while (s.heap_len < 2) {
16853 node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
16854 tree[node * 2]/*.Freq*/ = 1;
16855 s.depth[node] = 0;
16856 s.opt_len--;
16857
16858 if (has_stree) {
16859 s.static_len -= stree[node * 2 + 1]/*.Len*/;
16860 }
16861 /* node is 0 or 1 so it does not have extra bits */
16862 }
16863 desc.max_code = max_code;
16864
16865 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
16866 * establish sub-heaps of increasing lengths:
16867 */
16868 for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) {
16869 pqdownheap(s, tree, n);
16870 }
16871
16872 /* Construct the Huffman tree by repeatedly combining the least two
16873 * frequent nodes.
16874 */
16875 node = elems; /* next internal node of the tree */
16876 do {
16877 //pqremove(s, tree, n); /* n = node of least frequency */
16878 /*** pqremove ***/
16879 n = s.heap[1/*SMALLEST*/];
16880 s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
16881 pqdownheap(s, tree, 1/*SMALLEST*/);
16882 /***/
16883
16884 m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
16885
16886 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
16887 s.heap[--s.heap_max] = m;
16888
16889 /* Create a new node father of n and m */
16890 tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
16891 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
16892 tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
16893
16894 /* and insert the new node in the heap */
16895 s.heap[1/*SMALLEST*/] = node++;
16896 pqdownheap(s, tree, 1/*SMALLEST*/);
16897
16898 } while (s.heap_len >= 2);
16899
16900 s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
16901
16902 /* At this point, the fields freq and dad are set. We can now
16903 * generate the bit lengths.
16904 */
16905 gen_bitlen(s, desc);
16906
16907 /* The field len is now set, we can generate the bit codes */
16908 gen_codes(tree, max_code, s.bl_count);
16909}
16910
16911
16912/* ===========================================================================
16913 * Scan a literal or distance tree to determine the frequencies of the codes
16914 * in the bit length tree.
16915 */
16916function scan_tree(s, tree, max_code)
16917// deflate_state *s;
16918// ct_data *tree; /* the tree to be scanned */
16919// int max_code; /* and its largest code of non zero frequency */
16920{
16921 let n; /* iterates over all tree elements */
16922 let prevlen = -1; /* last emitted length */
16923 let curlen; /* length of current code */
16924
16925 let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
16926
16927 let count = 0; /* repeat count of the current code */
16928 let max_count = 7; /* max repeat count */
16929 let min_count = 4; /* min repeat count */
16930
16931 if (nextlen === 0) {
16932 max_count = 138;
16933 min_count = 3;
16934 }
16935 tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
16936
16937 for (n = 0; n <= max_code; n++) {
16938 curlen = nextlen;
16939 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
16940
16941 if (++count < max_count && curlen === nextlen) {
16942 continue;
16943
16944 } else if (count < min_count) {
16945 s.bl_tree[curlen * 2]/*.Freq*/ += count;
16946
16947 } else if (curlen !== 0) {
16948
16949 if (curlen !== prevlen) {
16950 s.bl_tree[curlen * 2]/*.Freq*/++;
16951 }
16952 s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
16953
16954 } else if (count <= 10) {
16955 s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
16956
16957 } else {
16958 s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
16959 }
16960
16961 count = 0;
16962 prevlen = curlen;
16963
16964 if (nextlen === 0) {
16965 max_count = 138;
16966 min_count = 3;
16967
16968 } else if (curlen === nextlen) {
16969 max_count = 6;
16970 min_count = 3;
16971
16972 } else {
16973 max_count = 7;
16974 min_count = 4;
16975 }
16976 }
16977}
16978
16979
16980/* ===========================================================================
16981 * Send a literal or distance tree in compressed form, using the codes in
16982 * bl_tree.
16983 */
16984function send_tree(s, tree, max_code)
16985// deflate_state *s;
16986// ct_data *tree; /* the tree to be scanned */
16987// int max_code; /* and its largest code of non zero frequency */
16988{
16989 let n; /* iterates over all tree elements */
16990 let prevlen = -1; /* last emitted length */
16991 let curlen; /* length of current code */
16992
16993 let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
16994
16995 let count = 0; /* repeat count of the current code */
16996 let max_count = 7; /* max repeat count */
16997 let min_count = 4; /* min repeat count */
16998
16999 /* tree[max_code+1].Len = -1; */ /* guard already set */
17000 if (nextlen === 0) {
17001 max_count = 138;
17002 min_count = 3;
17003 }
17004
17005 for (n = 0; n <= max_code; n++) {
17006 curlen = nextlen;
17007 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
17008
17009 if (++count < max_count && curlen === nextlen) {
17010 continue;
17011
17012 } else if (count < min_count) {
17013 do {
17014 send_code(s, curlen, s.bl_tree);
17015 } while (--count !== 0);
17016
17017 } else if (curlen !== 0) {
17018 if (curlen !== prevlen) {
17019 send_code(s, curlen, s.bl_tree);
17020 count--;
17021 }
17022 //Assert(count >= 3 && count <= 6, " 3_6?");
17023 send_code(s, REP_3_6, s.bl_tree);
17024 send_bits(s, count - 3, 2);
17025
17026 } else if (count <= 10) {
17027 send_code(s, REPZ_3_10, s.bl_tree);
17028 send_bits(s, count - 3, 3);
17029
17030 } else {
17031 send_code(s, REPZ_11_138, s.bl_tree);
17032 send_bits(s, count - 11, 7);
17033 }
17034
17035 count = 0;
17036 prevlen = curlen;
17037 if (nextlen === 0) {
17038 max_count = 138;
17039 min_count = 3;
17040
17041 } else if (curlen === nextlen) {
17042 max_count = 6;
17043 min_count = 3;
17044
17045 } else {
17046 max_count = 7;
17047 min_count = 4;
17048 }
17049 }
17050}
17051
17052
17053/* ===========================================================================
17054 * Construct the Huffman tree for the bit lengths and return the index in
17055 * bl_order of the last bit length code to send.
17056 */
17057function build_bl_tree(s) {
17058 let max_blindex; /* index of last bit length code of non zero freq */
17059
17060 /* Determine the bit length frequencies for literal and distance trees */
17061 scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
17062 scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
17063
17064 /* Build the bit length tree: */
17065 build_tree(s, s.bl_desc);
17066 /* opt_len now includes the length of the tree representations, except
17067 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
17068 */
17069
17070 /* Determine the number of bit length codes to send. The pkzip format
17071 * requires that at least 4 bit length codes be sent. (appnote.txt says
17072 * 3 but the actual value used is 4.)
17073 */
17074 for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
17075 if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
17076 break;
17077 }
17078 }
17079 /* Update opt_len to include the bit length tree and counts */
17080 s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
17081 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
17082 // s->opt_len, s->static_len));
17083
17084 return max_blindex;
17085}
17086
17087
17088/* ===========================================================================
17089 * Send the header for a block using dynamic Huffman trees: the counts, the
17090 * lengths of the bit length codes, the literal tree and the distance tree.
17091 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
17092 */
17093function send_all_trees(s, lcodes, dcodes, blcodes)
17094// deflate_state *s;
17095// int lcodes, dcodes, blcodes; /* number of codes for each tree */
17096{
17097 let rank; /* index in bl_order */
17098
17099 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
17100 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
17101 // "too many codes");
17102 //Tracev((stderr, "\nbl counts: "));
17103 send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
17104 send_bits(s, dcodes - 1, 5);
17105 send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
17106 for (rank = 0; rank < blcodes; rank++) {
17107 //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
17108 send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
17109 }
17110 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
17111
17112 send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
17113 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
17114
17115 send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
17116 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
17117}
17118
17119
17120/* ===========================================================================
17121 * Check if the data type is TEXT or BINARY, using the following algorithm:
17122 * - TEXT if the two conditions below are satisfied:
17123 * a) There are no non-portable control characters belonging to the
17124 * "black list" (0..6, 14..25, 28..31).
17125 * b) There is at least one printable character belonging to the
17126 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
17127 * - BINARY otherwise.
17128 * - The following partially-portable control characters form a
17129 * "gray list" that is ignored in this detection algorithm:
17130 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
17131 * IN assertion: the fields Freq of dyn_ltree are set.
17132 */
17133function detect_data_type(s) {
17134 /* black_mask is the bit mask of black-listed bytes
17135 * set bits 0..6, 14..25, and 28..31
17136 * 0xf3ffc07f = binary 11110011111111111100000001111111
17137 */
17138 let black_mask = 0xf3ffc07f;
17139 let n;
17140
17141 /* Check for non-textual ("black-listed") bytes. */
17142 for (n = 0; n <= 31; n++, black_mask >>>= 1) {
17143 if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
17144 return Z_BINARY;
17145 }
17146 }
17147
17148 /* Check for textual ("white-listed") bytes. */
17149 if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
17150 s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
17151 return Z_TEXT;
17152 }
17153 for (n = 32; n < LITERALS; n++) {
17154 if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
17155 return Z_TEXT;
17156 }
17157 }
17158
17159 /* There are no "black-listed" or "white-listed" bytes:
17160 * this stream either is empty or has tolerated ("gray-listed") bytes only.
17161 */
17162 return Z_BINARY;
17163}
17164
17165
17166let static_init_done = false;
17167
17168/* ===========================================================================
17169 * Initialize the tree data structures for a new zlib stream.
17170 */
17171function _tr_init(s) {
17172
17173 if (!static_init_done) {
17174 tr_static_init();
17175 static_init_done = true;
17176 }
17177
17178 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
17179 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
17180 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
17181
17182 s.bi_buf = 0;
17183 s.bi_valid = 0;
17184
17185 /* Initialize the first block of the first file: */
17186 init_block(s);
17187}
17188
17189
17190/* ===========================================================================
17191 * Send a stored block
17192 */
17193function _tr_stored_block(s, buf, stored_len, last)
17194//DeflateState *s;
17195//charf *buf; /* input block */
17196//ulg stored_len; /* length of input block */
17197//int last; /* one if this is the last block for a file */
17198{
17199 send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
17200 copy_block(s, buf, stored_len, true); /* with header */
17201}
17202
17203
17204/* ===========================================================================
17205 * Send one empty static block to give enough lookahead for inflate.
17206 * This takes 10 bits, of which 7 may remain in the bit buffer.
17207 */
17208function _tr_align(s) {
17209 send_bits(s, STATIC_TREES << 1, 3);
17210 send_code(s, END_BLOCK, static_ltree);
17211 bi_flush(s);
17212}
17213
17214
17215/* ===========================================================================
17216 * Determine the best encoding for the current block: dynamic trees, static
17217 * trees or store, and output the encoded block to the zip file.
17218 */
17219function _tr_flush_block(s, buf, stored_len, last)
17220//DeflateState *s;
17221//charf *buf; /* input block, or NULL if too old */
17222//ulg stored_len; /* length of input block */
17223//int last; /* one if this is the last block for a file */
17224{
17225 let opt_lenb, static_lenb; /* opt_len and static_len in bytes */
17226 let max_blindex = 0; /* index of last bit length code of non zero freq */
17227
17228 /* Build the Huffman trees unless a stored block is forced */
17229 if (s.level > 0) {
17230
17231 /* Check if the file is binary or text */
17232 if (s.strm.data_type === Z_UNKNOWN) {
17233 s.strm.data_type = detect_data_type(s);
17234 }
17235
17236 /* Construct the literal and distance trees */
17237 build_tree(s, s.l_desc);
17238 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
17239 // s->static_len));
17240
17241 build_tree(s, s.d_desc);
17242 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
17243 // s->static_len));
17244 /* At this point, opt_len and static_len are the total bit lengths of
17245 * the compressed block data, excluding the tree representations.
17246 */
17247
17248 /* Build the bit length tree for the above two trees, and get the index
17249 * in bl_order of the last bit length code to send.
17250 */
17251 max_blindex = build_bl_tree(s);
17252
17253 /* Determine the best encoding. Compute the block lengths in bytes. */
17254 opt_lenb = s.opt_len + 3 + 7 >>> 3;
17255 static_lenb = s.static_len + 3 + 7 >>> 3;
17256
17257 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
17258 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
17259 // s->last_lit));
17260
17261 if (static_lenb <= opt_lenb) {
17262 opt_lenb = static_lenb;
17263 }
17264
17265 } else {
17266 // Assert(buf != (char*)0, "lost buf");
17267 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
17268 }
17269
17270 if (stored_len + 4 <= opt_lenb && buf !== -1) {
17271 /* 4: two words for the lengths */
17272
17273 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
17274 * Otherwise we can't have processed more than WSIZE input bytes since
17275 * the last block flush, because compression would have been
17276 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
17277 * transform a block into a stored block.
17278 */
17279 _tr_stored_block(s, buf, stored_len, last);
17280
17281 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
17282
17283 send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
17284 compress_block(s, static_ltree, static_dtree);
17285
17286 } else {
17287 send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
17288 send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
17289 compress_block(s, s.dyn_ltree, s.dyn_dtree);
17290 }
17291 // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
17292 /* The above check is made mod 2^32, for files larger than 512 MB
17293 * and uLong implemented on 32 bits.
17294 */
17295 init_block(s);
17296
17297 if (last) {
17298 bi_windup(s);
17299 }
17300 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
17301 // s->compressed_len-7*last));
17302}
17303
17304/* ===========================================================================
17305 * Save the match info and tally the frequency counts. Return true if
17306 * the current block must be flushed.
17307 */
17308function _tr_tally(s, dist, lc)
17309// deflate_state *s;
17310// unsigned dist; /* distance of matched string */
17311// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
17312{
17313 //var out_length, in_length, dcode;
17314
17315 s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff;
17316 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
17317
17318 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
17319 s.last_lit++;
17320
17321 if (dist === 0) {
17322 /* lc is the unmatched char */
17323 s.dyn_ltree[lc * 2]/*.Freq*/++;
17324 } else {
17325 s.matches++;
17326 /* Here, lc is the match length - MIN_MATCH */
17327 dist--; /* dist = match distance - 1 */
17328 //Assert((ush)dist < (ush)MAX_DIST(s) &&
17329 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
17330 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
17331
17332 s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
17333 s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
17334 }
17335
17336 // (!) This block is disabled in zlib defaults,
17337 // don't enable it for binary compatibility
17338
17339 //#ifdef TRUNCATE_BLOCK
17340 // /* Try to guess if it is profitable to stop the current block here */
17341 // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
17342 // /* Compute an upper bound for the compressed length */
17343 // out_length = s.last_lit*8;
17344 // in_length = s.strstart - s.block_start;
17345 //
17346 // for (dcode = 0; dcode < D_CODES; dcode++) {
17347 // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
17348 // }
17349 // out_length >>>= 3;
17350 // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
17351 // // s->last_lit, in_length, out_length,
17352 // // 100L - out_length*100L/in_length));
17353 // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
17354 // return true;
17355 // }
17356 // }
17357 //#endif
17358
17359 return s.last_lit === s.lit_bufsize - 1;
17360 /* We avoid equality with lit_bufsize because of wraparound at 64K
17361 * on 16 bit machines and because stored blocks are restricted to
17362 * 64K-1 bytes.
17363 */
17364}
17365
17366// Note: adler32 takes 12% for level 0 and 2% for level 6.
17367// It isn't worth it to make additional optimizations as in original.
17368// Small size is preferable.
17369
17370// (C) 1995-2013 Jean-loup Gailly and Mark Adler
17371// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
17372//
17373// This software is provided 'as-is', without any express or implied
17374// warranty. In no event will the authors be held liable for any damages
17375// arising from the use of this software.
17376//
17377// Permission is granted to anyone to use this software for any purpose,
17378// including commercial applications, and to alter it and redistribute it
17379// freely, subject to the following restrictions:
17380//
17381// 1. The origin of this software must not be misrepresented; you must not
17382// claim that you wrote the original software. If you use this software
17383// in a product, an acknowledgment in the product documentation would be
17384// appreciated but is not required.
17385// 2. Altered source versions must be plainly marked as such, and must not be
17386// misrepresented as being the original software.
17387// 3. This notice may not be removed or altered from any source distribution.
17388
17389function adler32(adler, buf, len, pos) {
17390 let s1 = adler & 0xffff |0,
17391 s2 = adler >>> 16 & 0xffff |0,
17392 n = 0;
17393
17394 while (len !== 0) {
17395 // Set limit ~ twice less than 5552, to keep
17396 // s2 in 31-bits, because we force signed ints.
17397 // in other case %= will fail.
17398 n = len > 2000 ? 2000 : len;
17399 len -= n;
17400
17401 do {
17402 s1 = s1 + buf[pos++] |0;
17403 s2 = s2 + s1 |0;
17404 } while (--n);
17405
17406 s1 %= 65521;
17407 s2 %= 65521;
17408 }
17409
17410 return s1 | s2 << 16 |0;
17411}
17412
17413// Note: we can't get significant speed boost here.
17414// So write code to minimize size - no pregenerated tables
17415// and array tools dependencies.
17416
17417// (C) 1995-2013 Jean-loup Gailly and Mark Adler
17418// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
17419//
17420// This software is provided 'as-is', without any express or implied
17421// warranty. In no event will the authors be held liable for any damages
17422// arising from the use of this software.
17423//
17424// Permission is granted to anyone to use this software for any purpose,
17425// including commercial applications, and to alter it and redistribute it
17426// freely, subject to the following restrictions:
17427//
17428// 1. The origin of this software must not be misrepresented; you must not
17429// claim that you wrote the original software. If you use this software
17430// in a product, an acknowledgment in the product documentation would be
17431// appreciated but is not required.
17432// 2. Altered source versions must be plainly marked as such, and must not be
17433// misrepresented as being the original software.
17434// 3. This notice may not be removed or altered from any source distribution.
17435
17436// Use ordinary array, since untyped makes no boost here
17437function makeTable() {
17438 let c;
17439 const table = [];
17440
17441 for (let n = 0; n < 256; n++) {
17442 c = n;
17443 for (let k = 0; k < 8; k++) {
17444 c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
17445 }
17446 table[n] = c;
17447 }
17448
17449 return table;
17450}
17451
17452// Create table on load. Just 255 signed longs. Not a problem.
17453const crcTable = makeTable();
17454
17455
17456function crc32(crc, buf, len, pos) {
17457 const t = crcTable,
17458 end = pos + len;
17459
17460 crc ^= -1;
17461
17462 for (let i = pos; i < end; i++) {
17463 crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF];
17464 }
17465
17466 return crc ^ -1; // >>> 0;
17467}
17468
17469// (C) 1995-2013 Jean-loup Gailly and Mark Adler
17470// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
17471//
17472// This software is provided 'as-is', without any express or implied
17473// warranty. In no event will the authors be held liable for any damages
17474// arising from the use of this software.
17475//
17476// Permission is granted to anyone to use this software for any purpose,
17477// including commercial applications, and to alter it and redistribute it
17478// freely, subject to the following restrictions:
17479//
17480// 1. The origin of this software must not be misrepresented; you must not
17481// claim that you wrote the original software. If you use this software
17482// in a product, an acknowledgment in the product documentation would be
17483// appreciated but is not required.
17484// 2. Altered source versions must be plainly marked as such, and must not be
17485// misrepresented as being the original software.
17486// 3. This notice may not be removed or altered from any source distribution.
17487
17488var msg = {
17489 2: "need dictionary", /* Z_NEED_DICT 2 */
17490 1: "stream end", /* Z_STREAM_END 1 */
17491 0: "", /* Z_OK 0 */
17492 "-1": "file error", /* Z_ERRNO (-1) */
17493 "-2": "stream error", /* Z_STREAM_ERROR (-2) */
17494 "-3": "data error", /* Z_DATA_ERROR (-3) */
17495 "-4": "insufficient memory", /* Z_MEM_ERROR (-4) */
17496 "-5": "buffer error", /* Z_BUF_ERROR (-5) */
17497 "-6": "incompatible version" /* Z_VERSION_ERROR (-6) */
17498};
17499
17500/*============================================================================*/
17501
17502
17503const MAX_MEM_LEVEL = 9;
17504
17505
17506const LENGTH_CODES$1 = 29;
17507/* number of length codes, not counting the special END_BLOCK code */
17508const LITERALS$1 = 256;
17509/* number of literal bytes 0..255 */
17510const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;
17511/* number of Literal or Length codes, including the END_BLOCK code */
17512const D_CODES$1 = 30;
17513/* number of distance codes */
17514const BL_CODES$1 = 19;
17515/* number of codes used to transfer the bit lengths */
17516const HEAP_SIZE$1 = 2 * L_CODES$1 + 1;
17517/* maximum heap size */
17518const MAX_BITS$1 = 15;
17519/* All codes must not exceed MAX_BITS bits */
17520
17521const MIN_MATCH$1 = 3;
17522const MAX_MATCH$1 = 258;
17523const MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1);
17524
17525const PRESET_DICT = 0x20;
17526
17527const INIT_STATE = 42;
17528const EXTRA_STATE = 69;
17529const NAME_STATE = 73;
17530const COMMENT_STATE = 91;
17531const HCRC_STATE = 103;
17532const BUSY_STATE = 113;
17533const FINISH_STATE = 666;
17534
17535const BS_NEED_MORE = 1; /* block not completed, need more input or more output */
17536const BS_BLOCK_DONE = 2; /* block flush performed */
17537const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
17538const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
17539
17540const OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
17541
17542function err(strm, errorCode) {
17543 strm.msg = msg[errorCode];
17544 return errorCode;
17545}
17546
17547function rank(f) {
17548 return ((f) << 1) - ((f) > 4 ? 9 : 0);
17549}
17550
17551function zero$2(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }
17552
17553
17554/* =========================================================================
17555 * Flush as much pending output as possible. All deflate() output goes
17556 * through this function so some applications may wish to modify it
17557 * to avoid allocating a large strm->output buffer and copying into it.
17558 * (See also read_buf()).
17559 */
17560function flush_pending(strm) {
17561 const s = strm.state;
17562
17563 //_tr_flush_bits(s);
17564 let len = s.pending;
17565 if (len > strm.avail_out) {
17566 len = strm.avail_out;
17567 }
17568 if (len === 0) { return; }
17569
17570 arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
17571 strm.next_out += len;
17572 s.pending_out += len;
17573 strm.total_out += len;
17574 strm.avail_out -= len;
17575 s.pending -= len;
17576 if (s.pending === 0) {
17577 s.pending_out = 0;
17578 }
17579}
17580
17581
17582function flush_block_only(s, last) {
17583 _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
17584 s.block_start = s.strstart;
17585 flush_pending(s.strm);
17586}
17587
17588
17589function put_byte(s, b) {
17590 s.pending_buf[s.pending++] = b;
17591}
17592
17593
17594/* =========================================================================
17595 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
17596 * IN assertion: the stream state is correct and there is enough room in
17597 * pending_buf.
17598 */
17599function putShortMSB(s, b) {
17600 // put_byte(s, (Byte)(b >> 8));
17601 // put_byte(s, (Byte)(b & 0xff));
17602 s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
17603 s.pending_buf[s.pending++] = b & 0xff;
17604}
17605
17606
17607/* ===========================================================================
17608 * Read a new buffer from the current input stream, update the adler32
17609 * and total number of bytes read. All deflate() input goes through
17610 * this function so some applications may wish to modify it to avoid
17611 * allocating a large strm->input buffer and copying from it.
17612 * (See also flush_pending()).
17613 */
17614function read_buf(strm, buf, start, size) {
17615 let len = strm.avail_in;
17616
17617 if (len > size) { len = size; }
17618 if (len === 0) { return 0; }
17619
17620 strm.avail_in -= len;
17621
17622 // zmemcpy(buf, strm->next_in, len);
17623 arraySet(buf, strm.input, strm.next_in, len, start);
17624 if (strm.state.wrap === 1) {
17625 strm.adler = adler32(strm.adler, buf, len, start);
17626 }
17627
17628 else if (strm.state.wrap === 2) {
17629 strm.adler = crc32(strm.adler, buf, len, start);
17630 }
17631
17632 strm.next_in += len;
17633 strm.total_in += len;
17634
17635 return len;
17636}
17637
17638
17639/* ===========================================================================
17640 * Set match_start to the longest match starting at the given string and
17641 * return its length. Matches shorter or equal to prev_length are discarded,
17642 * in which case the result is equal to prev_length and match_start is
17643 * garbage.
17644 * IN assertions: cur_match is the head of the hash chain for the current
17645 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
17646 * OUT assertion: the match length is not greater than s->lookahead.
17647 */
17648function longest_match(s, cur_match) {
17649 let chain_length = s.max_chain_length; /* max hash chain length */
17650 let scan = s.strstart; /* current string */
17651 let match; /* matched string */
17652 let len; /* length of current match */
17653 let best_len = s.prev_length; /* best match length so far */
17654 let nice_match = s.nice_match; /* stop if match long enough */
17655 const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
17656 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
17657
17658 const _win = s.window; // shortcut
17659
17660 const wmask = s.w_mask;
17661 const prev = s.prev;
17662
17663 /* Stop when cur_match becomes <= limit. To simplify the code,
17664 * we prevent matches with the string of window index 0.
17665 */
17666
17667 const strend = s.strstart + MAX_MATCH$1;
17668 let scan_end1 = _win[scan + best_len - 1];
17669 let scan_end = _win[scan + best_len];
17670
17671 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
17672 * It is easy to get rid of this optimization if necessary.
17673 */
17674 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
17675
17676 /* Do not waste too much time if we already have a good match: */
17677 if (s.prev_length >= s.good_match) {
17678 chain_length >>= 2;
17679 }
17680 /* Do not look for matches beyond the end of the input. This is necessary
17681 * to make deflate deterministic.
17682 */
17683 if (nice_match > s.lookahead) { nice_match = s.lookahead; }
17684
17685 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
17686
17687 do {
17688 // Assert(cur_match < s->strstart, "no future");
17689 match = cur_match;
17690
17691 /* Skip to next match if the match length cannot increase
17692 * or if the match length is less than 2. Note that the checks below
17693 * for insufficient lookahead only occur occasionally for performance
17694 * reasons. Therefore uninitialized memory will be accessed, and
17695 * conditional jumps will be made that depend on those values.
17696 * However the length of the match is limited to the lookahead, so
17697 * the output of deflate is not affected by the uninitialized values.
17698 */
17699
17700 if (_win[match + best_len] !== scan_end ||
17701 _win[match + best_len - 1] !== scan_end1 ||
17702 _win[match] !== _win[scan] ||
17703 _win[++match] !== _win[scan + 1]) {
17704 continue;
17705 }
17706
17707 /* The check at best_len-1 can be removed because it will be made
17708 * again later. (This heuristic is not always a win.)
17709 * It is not necessary to compare scan[2] and match[2] since they
17710 * are always equal when the other bytes match, given that
17711 * the hash keys are equal and that HASH_BITS >= 8.
17712 */
17713 scan += 2;
17714 match++;
17715 // Assert(*scan == *match, "match[2]?");
17716
17717 /* We check for insufficient lookahead only every 8th comparison;
17718 * the 256th check will be made at strstart+258.
17719 */
17720 do {
17721 /*jshint noempty:false*/
17722 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
17723 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
17724 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
17725 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
17726 scan < strend);
17727
17728 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
17729
17730 len = MAX_MATCH$1 - (strend - scan);
17731 scan = strend - MAX_MATCH$1;
17732
17733 if (len > best_len) {
17734 s.match_start = cur_match;
17735 best_len = len;
17736 if (len >= nice_match) {
17737 break;
17738 }
17739 scan_end1 = _win[scan + best_len - 1];
17740 scan_end = _win[scan + best_len];
17741 }
17742 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
17743
17744 if (best_len <= s.lookahead) {
17745 return best_len;
17746 }
17747 return s.lookahead;
17748}
17749
17750
17751/* ===========================================================================
17752 * Fill the window when the lookahead becomes insufficient.
17753 * Updates strstart and lookahead.
17754 *
17755 * IN assertion: lookahead < MIN_LOOKAHEAD
17756 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
17757 * At least one byte has been read, or avail_in == 0; reads are
17758 * performed for at least two bytes (required for the zip translate_eol
17759 * option -- not supported here).
17760 */
17761function fill_window(s) {
17762 const _w_size = s.w_size;
17763 let p, n, m, more, str;
17764
17765 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
17766
17767 do {
17768 more = s.window_size - s.lookahead - s.strstart;
17769
17770 // JS ints have 32 bit, block below not needed
17771 /* Deal with !@#$% 64K limit: */
17772 //if (sizeof(int) <= 2) {
17773 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
17774 // more = wsize;
17775 //
17776 // } else if (more == (unsigned)(-1)) {
17777 // /* Very unlikely, but possible on 16 bit machine if
17778 // * strstart == 0 && lookahead == 1 (input done a byte at time)
17779 // */
17780 // more--;
17781 // }
17782 //}
17783
17784
17785 /* If the window is almost full and there is insufficient lookahead,
17786 * move the upper half to the lower one to make room in the upper half.
17787 */
17788 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
17789
17790 arraySet(s.window, s.window, _w_size, _w_size, 0);
17791 s.match_start -= _w_size;
17792 s.strstart -= _w_size;
17793 /* we now have strstart >= MAX_DIST */
17794 s.block_start -= _w_size;
17795
17796 /* Slide the hash table (could be avoided with 32 bit values
17797 at the expense of memory usage). We slide even when level == 0
17798 to keep the hash table consistent if we switch back to level > 0
17799 later. (Using level 0 permanently is not an optimal usage of
17800 zlib, so we don't care about this pathological case.)
17801 */
17802
17803 n = s.hash_size;
17804 p = n;
17805 do {
17806 m = s.head[--p];
17807 s.head[p] = (m >= _w_size ? m - _w_size : 0);
17808 } while (--n);
17809
17810 n = _w_size;
17811 p = n;
17812 do {
17813 m = s.prev[--p];
17814 s.prev[p] = (m >= _w_size ? m - _w_size : 0);
17815 /* If n is not on any hash chain, prev[n] is garbage but
17816 * its value will never be used.
17817 */
17818 } while (--n);
17819
17820 more += _w_size;
17821 }
17822 if (s.strm.avail_in === 0) {
17823 break;
17824 }
17825
17826 /* If there was no sliding:
17827 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
17828 * more == window_size - lookahead - strstart
17829 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
17830 * => more >= window_size - 2*WSIZE + 2
17831 * In the BIG_MEM or MMAP case (not yet supported),
17832 * window_size == input_size + MIN_LOOKAHEAD &&
17833 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
17834 * Otherwise, window_size == 2*WSIZE so more >= 2.
17835 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
17836 */
17837 //Assert(more >= 2, "more < 2");
17838 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
17839 s.lookahead += n;
17840
17841 /* Initialize the hash value now that we have some input: */
17842 if (s.lookahead + s.insert >= MIN_MATCH$1) {
17843 str = s.strstart - s.insert;
17844 s.ins_h = s.window[str];
17845
17846 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
17847 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
17848 //#if MIN_MATCH != 3
17849 // Call update_hash() MIN_MATCH-3 more times
17850 //#endif
17851 while (s.insert) {
17852 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
17853 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;
17854
17855 s.prev[str & s.w_mask] = s.head[s.ins_h];
17856 s.head[s.ins_h] = str;
17857 str++;
17858 s.insert--;
17859 if (s.lookahead + s.insert < MIN_MATCH$1) {
17860 break;
17861 }
17862 }
17863 }
17864 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
17865 * but this is not important since only literal bytes will be emitted.
17866 */
17867
17868 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
17869
17870 /* If the WIN_INIT bytes after the end of the current data have never been
17871 * written, then zero those bytes in order to avoid memory check reports of
17872 * the use of uninitialized (or uninitialised as Julian writes) bytes by
17873 * the longest match routines. Update the high water mark for the next
17874 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
17875 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
17876 */
17877 // if (s.high_water < s.window_size) {
17878 // var curr = s.strstart + s.lookahead;
17879 // var init = 0;
17880 //
17881 // if (s.high_water < curr) {
17882 // /* Previous high water mark below current data -- zero WIN_INIT
17883 // * bytes or up to end of window, whichever is less.
17884 // */
17885 // init = s.window_size - curr;
17886 // if (init > WIN_INIT)
17887 // init = WIN_INIT;
17888 // zmemzero(s->window + curr, (unsigned)init);
17889 // s->high_water = curr + init;
17890 // }
17891 // else if (s->high_water < (ulg)curr + WIN_INIT) {
17892 // /* High water mark at or above current data, but below current data
17893 // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
17894 // * to end of window, whichever is less.
17895 // */
17896 // init = (ulg)curr + WIN_INIT - s->high_water;
17897 // if (init > s->window_size - s->high_water)
17898 // init = s->window_size - s->high_water;
17899 // zmemzero(s->window + s->high_water, (unsigned)init);
17900 // s->high_water += init;
17901 // }
17902 // }
17903 //
17904 // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
17905 // "not enough room for search");
17906}
17907
17908/* ===========================================================================
17909 * Copy without compression as much as possible from the input stream, return
17910 * the current block state.
17911 * This function does not insert new strings in the dictionary since
17912 * uncompressible data is probably not useful. This function is used
17913 * only for the level=0 compression option.
17914 * NOTE: this function should be optimized to avoid extra copying from
17915 * window to pending_buf.
17916 */
17917function deflate_stored(s, flush) {
17918 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
17919 * to pending_buf_size, and each stored block has a 5 byte header:
17920 */
17921 let max_block_size = 0xffff;
17922
17923 if (max_block_size > s.pending_buf_size - 5) {
17924 max_block_size = s.pending_buf_size - 5;
17925 }
17926
17927 /* Copy as much as possible from input to output: */
17928 for (; ;) {
17929 /* Fill the window as much as possible: */
17930 if (s.lookahead <= 1) {
17931
17932 //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
17933 // s->block_start >= (long)s->w_size, "slide too late");
17934 // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
17935 // s.block_start >= s.w_size)) {
17936 // throw new Error("slide too late");
17937 // }
17938
17939 fill_window(s);
17940 if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
17941 return BS_NEED_MORE;
17942 }
17943
17944 if (s.lookahead === 0) {
17945 break;
17946 }
17947 /* flush the current block */
17948 }
17949 //Assert(s->block_start >= 0L, "block gone");
17950 // if (s.block_start < 0) throw new Error("block gone");
17951
17952 s.strstart += s.lookahead;
17953 s.lookahead = 0;
17954
17955 /* Emit a stored block if pending_buf will be full: */
17956 const max_start = s.block_start + max_block_size;
17957
17958 if (s.strstart === 0 || s.strstart >= max_start) {
17959 /* strstart == 0 is possible when wraparound on 16-bit machine */
17960 s.lookahead = s.strstart - max_start;
17961 s.strstart = max_start;
17962 /*** FLUSH_BLOCK(s, 0); ***/
17963 flush_block_only(s, false);
17964 if (s.strm.avail_out === 0) {
17965 return BS_NEED_MORE;
17966 }
17967 /***/
17968
17969
17970 }
17971 /* Flush if we may have to slide, otherwise block_start may become
17972 * negative and the data will be gone:
17973 */
17974 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
17975 /*** FLUSH_BLOCK(s, 0); ***/
17976 flush_block_only(s, false);
17977 if (s.strm.avail_out === 0) {
17978 return BS_NEED_MORE;
17979 }
17980 /***/
17981 }
17982 }
17983
17984 s.insert = 0;
17985
17986 if (flush === Z_FINISH) {
17987 /*** FLUSH_BLOCK(s, 1); ***/
17988 flush_block_only(s, true);
17989 if (s.strm.avail_out === 0) {
17990 return BS_FINISH_STARTED;
17991 }
17992 /***/
17993 return BS_FINISH_DONE;
17994 }
17995
17996 if (s.strstart > s.block_start) {
17997 /*** FLUSH_BLOCK(s, 0); ***/
17998 flush_block_only(s, false);
17999 if (s.strm.avail_out === 0) {
18000 return BS_NEED_MORE;
18001 }
18002 /***/
18003 }
18004
18005 return BS_NEED_MORE;
18006}
18007
18008/* ===========================================================================
18009 * Compress as much as possible from the input stream, return the current
18010 * block state.
18011 * This function does not perform lazy evaluation of matches and inserts
18012 * new strings in the dictionary only for unmatched strings or for short
18013 * matches. It is used only for the fast compression options.
18014 */
18015function deflate_fast(s, flush) {
18016 let hash_head; /* head of the hash chain */
18017 let bflush; /* set if current block must be flushed */
18018
18019 for (; ;) {
18020 /* Make sure that we always have enough lookahead, except
18021 * at the end of the input file. We need MAX_MATCH bytes
18022 * for the next match, plus MIN_MATCH bytes to insert the
18023 * string following the next match.
18024 */
18025 if (s.lookahead < MIN_LOOKAHEAD) {
18026 fill_window(s);
18027 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
18028 return BS_NEED_MORE;
18029 }
18030 if (s.lookahead === 0) {
18031 break; /* flush the current block */
18032 }
18033 }
18034
18035 /* Insert the string window[strstart .. strstart+2] in the
18036 * dictionary, and set hash_head to the head of the hash chain:
18037 */
18038 hash_head = 0/*NIL*/;
18039 if (s.lookahead >= MIN_MATCH$1) {
18040 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
18041 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
18042 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
18043 s.head[s.ins_h] = s.strstart;
18044 /***/
18045 }
18046
18047 /* Find the longest match, discarding those <= prev_length.
18048 * At this point we have always match_length < MIN_MATCH
18049 */
18050 if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
18051 /* To simplify the code, we prevent matches with the string
18052 * of window index 0 (in particular we have to avoid a match
18053 * of the string with itself at the start of the input file).
18054 */
18055 s.match_length = longest_match(s, hash_head);
18056 /* longest_match() sets match_start */
18057 }
18058 if (s.match_length >= MIN_MATCH$1) {
18059 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
18060
18061 /*** _tr_tally_dist(s, s.strstart - s.match_start,
18062 s.match_length - MIN_MATCH, bflush); ***/
18063 bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1);
18064
18065 s.lookahead -= s.match_length;
18066
18067 /* Insert new strings in the hash table only if the match length
18068 * is not too large. This saves time but degrades compression.
18069 */
18070 if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) {
18071 s.match_length--; /* string at strstart already in table */
18072 do {
18073 s.strstart++;
18074 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
18075 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
18076 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
18077 s.head[s.ins_h] = s.strstart;
18078 /***/
18079 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
18080 * always MIN_MATCH bytes ahead.
18081 */
18082 } while (--s.match_length !== 0);
18083 s.strstart++;
18084 } else {
18085 s.strstart += s.match_length;
18086 s.match_length = 0;
18087 s.ins_h = s.window[s.strstart];
18088 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
18089 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
18090
18091 //#if MIN_MATCH != 3
18092 // Call UPDATE_HASH() MIN_MATCH-3 more times
18093 //#endif
18094 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
18095 * matter since it will be recomputed at next deflate call.
18096 */
18097 }
18098 } else {
18099 /* No match, output a literal byte */
18100 //Tracevv((stderr,"%c", s.window[s.strstart]));
18101 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
18102 bflush = _tr_tally(s, 0, s.window[s.strstart]);
18103
18104 s.lookahead--;
18105 s.strstart++;
18106 }
18107 if (bflush) {
18108 /*** FLUSH_BLOCK(s, 0); ***/
18109 flush_block_only(s, false);
18110 if (s.strm.avail_out === 0) {
18111 return BS_NEED_MORE;
18112 }
18113 /***/
18114 }
18115 }
18116 s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1);
18117 if (flush === Z_FINISH) {
18118 /*** FLUSH_BLOCK(s, 1); ***/
18119 flush_block_only(s, true);
18120 if (s.strm.avail_out === 0) {
18121 return BS_FINISH_STARTED;
18122 }
18123 /***/
18124 return BS_FINISH_DONE;
18125 }
18126 if (s.last_lit) {
18127 /*** FLUSH_BLOCK(s, 0); ***/
18128 flush_block_only(s, false);
18129 if (s.strm.avail_out === 0) {
18130 return BS_NEED_MORE;
18131 }
18132 /***/
18133 }
18134 return BS_BLOCK_DONE;
18135}
18136
18137/* ===========================================================================
18138 * Same as above, but achieves better compression. We use a lazy
18139 * evaluation for matches: a match is finally adopted only if there is
18140 * no better match at the next window position.
18141 */
18142function deflate_slow(s, flush) {
18143 let hash_head; /* head of hash chain */
18144 let bflush; /* set if current block must be flushed */
18145
18146 let max_insert;
18147
18148 /* Process the input block. */
18149 for (; ;) {
18150 /* Make sure that we always have enough lookahead, except
18151 * at the end of the input file. We need MAX_MATCH bytes
18152 * for the next match, plus MIN_MATCH bytes to insert the
18153 * string following the next match.
18154 */
18155 if (s.lookahead < MIN_LOOKAHEAD) {
18156 fill_window(s);
18157 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
18158 return BS_NEED_MORE;
18159 }
18160 if (s.lookahead === 0) { break; } /* flush the current block */
18161 }
18162
18163 /* Insert the string window[strstart .. strstart+2] in the
18164 * dictionary, and set hash_head to the head of the hash chain:
18165 */
18166 hash_head = 0/*NIL*/;
18167 if (s.lookahead >= MIN_MATCH$1) {
18168 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
18169 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
18170 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
18171 s.head[s.ins_h] = s.strstart;
18172 /***/
18173 }
18174
18175 /* Find the longest match, discarding those <= prev_length.
18176 */
18177 s.prev_length = s.match_length;
18178 s.prev_match = s.match_start;
18179 s.match_length = MIN_MATCH$1 - 1;
18180
18181 if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
18182 s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
18183 /* To simplify the code, we prevent matches with the string
18184 * of window index 0 (in particular we have to avoid a match
18185 * of the string with itself at the start of the input file).
18186 */
18187 s.match_length = longest_match(s, hash_head);
18188 /* longest_match() sets match_start */
18189
18190 if (s.match_length <= 5 &&
18191 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
18192
18193 /* If prev_match is also MIN_MATCH, match_start is garbage
18194 * but we will ignore the current match anyway.
18195 */
18196 s.match_length = MIN_MATCH$1 - 1;
18197 }
18198 }
18199 /* If there was a match at the previous step and the current
18200 * match is not better, output the previous match:
18201 */
18202 if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) {
18203 max_insert = s.strstart + s.lookahead - MIN_MATCH$1;
18204 /* Do not insert strings in hash table beyond this. */
18205
18206 //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
18207
18208 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
18209 s.prev_length - MIN_MATCH, bflush);***/
18210 bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1);
18211 /* Insert in hash table all strings up to the end of the match.
18212 * strstart-1 and strstart are already inserted. If there is not
18213 * enough lookahead, the last two strings are not inserted in
18214 * the hash table.
18215 */
18216 s.lookahead -= s.prev_length - 1;
18217 s.prev_length -= 2;
18218 do {
18219 if (++s.strstart <= max_insert) {
18220 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
18221 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
18222 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
18223 s.head[s.ins_h] = s.strstart;
18224 /***/
18225 }
18226 } while (--s.prev_length !== 0);
18227 s.match_available = 0;
18228 s.match_length = MIN_MATCH$1 - 1;
18229 s.strstart++;
18230
18231 if (bflush) {
18232 /*** FLUSH_BLOCK(s, 0); ***/
18233 flush_block_only(s, false);
18234 if (s.strm.avail_out === 0) {
18235 return BS_NEED_MORE;
18236 }
18237 /***/
18238 }
18239
18240 } else if (s.match_available) {
18241 /* If there was no match at the previous position, output a
18242 * single literal. If there was a match but the current match
18243 * is longer, truncate the previous match to a single literal.
18244 */
18245 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
18246 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
18247 bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
18248
18249 if (bflush) {
18250 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
18251 flush_block_only(s, false);
18252 /***/
18253 }
18254 s.strstart++;
18255 s.lookahead--;
18256 if (s.strm.avail_out === 0) {
18257 return BS_NEED_MORE;
18258 }
18259 } else {
18260 /* There is no previous match to compare with, wait for
18261 * the next step to decide.
18262 */
18263 s.match_available = 1;
18264 s.strstart++;
18265 s.lookahead--;
18266 }
18267 }
18268 //Assert (flush != Z_NO_FLUSH, "no flush?");
18269 if (s.match_available) {
18270 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
18271 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
18272 bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
18273
18274 s.match_available = 0;
18275 }
18276 s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1;
18277 if (flush === Z_FINISH) {
18278 /*** FLUSH_BLOCK(s, 1); ***/
18279 flush_block_only(s, true);
18280 if (s.strm.avail_out === 0) {
18281 return BS_FINISH_STARTED;
18282 }
18283 /***/
18284 return BS_FINISH_DONE;
18285 }
18286 if (s.last_lit) {
18287 /*** FLUSH_BLOCK(s, 0); ***/
18288 flush_block_only(s, false);
18289 if (s.strm.avail_out === 0) {
18290 return BS_NEED_MORE;
18291 }
18292 /***/
18293 }
18294
18295 return BS_BLOCK_DONE;
18296}
18297
18298
18299/* ===========================================================================
18300 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
18301 * one. Do not maintain a hash table. (It will be regenerated if this run of
18302 * deflate switches away from Z_RLE.)
18303 */
18304function deflate_rle(s, flush) {
18305 let bflush; /* set if current block must be flushed */
18306 let prev; /* byte at distance one to match */
18307 let scan, strend; /* scan goes up to strend for length of run */
18308
18309 const _win = s.window;
18310
18311 for (; ;) {
18312 /* Make sure that we always have enough lookahead, except
18313 * at the end of the input file. We need MAX_MATCH bytes
18314 * for the longest run, plus one for the unrolled loop.
18315 */
18316 if (s.lookahead <= MAX_MATCH$1) {
18317 fill_window(s);
18318 if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) {
18319 return BS_NEED_MORE;
18320 }
18321 if (s.lookahead === 0) { break; } /* flush the current block */
18322 }
18323
18324 /* See how many times the previous byte repeats */
18325 s.match_length = 0;
18326 if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) {
18327 scan = s.strstart - 1;
18328 prev = _win[scan];
18329 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
18330 strend = s.strstart + MAX_MATCH$1;
18331 do {
18332 /*jshint noempty:false*/
18333 } while (prev === _win[++scan] && prev === _win[++scan] &&
18334 prev === _win[++scan] && prev === _win[++scan] &&
18335 prev === _win[++scan] && prev === _win[++scan] &&
18336 prev === _win[++scan] && prev === _win[++scan] &&
18337 scan < strend);
18338 s.match_length = MAX_MATCH$1 - (strend - scan);
18339 if (s.match_length > s.lookahead) {
18340 s.match_length = s.lookahead;
18341 }
18342 }
18343 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
18344 }
18345
18346 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
18347 if (s.match_length >= MIN_MATCH$1) {
18348 //check_match(s, s.strstart, s.strstart - 1, s.match_length);
18349
18350 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
18351 bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH$1);
18352
18353 s.lookahead -= s.match_length;
18354 s.strstart += s.match_length;
18355 s.match_length = 0;
18356 } else {
18357 /* No match, output a literal byte */
18358 //Tracevv((stderr,"%c", s->window[s->strstart]));
18359 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
18360 bflush = _tr_tally(s, 0, s.window[s.strstart]);
18361
18362 s.lookahead--;
18363 s.strstart++;
18364 }
18365 if (bflush) {
18366 /*** FLUSH_BLOCK(s, 0); ***/
18367 flush_block_only(s, false);
18368 if (s.strm.avail_out === 0) {
18369 return BS_NEED_MORE;
18370 }
18371 /***/
18372 }
18373 }
18374 s.insert = 0;
18375 if (flush === Z_FINISH) {
18376 /*** FLUSH_BLOCK(s, 1); ***/
18377 flush_block_only(s, true);
18378 if (s.strm.avail_out === 0) {
18379 return BS_FINISH_STARTED;
18380 }
18381 /***/
18382 return BS_FINISH_DONE;
18383 }
18384 if (s.last_lit) {
18385 /*** FLUSH_BLOCK(s, 0); ***/
18386 flush_block_only(s, false);
18387 if (s.strm.avail_out === 0) {
18388 return BS_NEED_MORE;
18389 }
18390 /***/
18391 }
18392 return BS_BLOCK_DONE;
18393}
18394
18395/* ===========================================================================
18396 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
18397 * (It will be regenerated if this run of deflate switches away from Huffman.)
18398 */
18399function deflate_huff(s, flush) {
18400 let bflush; /* set if current block must be flushed */
18401
18402 for (; ;) {
18403 /* Make sure that we have a literal to write. */
18404 if (s.lookahead === 0) {
18405 fill_window(s);
18406 if (s.lookahead === 0) {
18407 if (flush === Z_NO_FLUSH) {
18408 return BS_NEED_MORE;
18409 }
18410 break; /* flush the current block */
18411 }
18412 }
18413
18414 /* Output a literal byte */
18415 s.match_length = 0;
18416 //Tracevv((stderr,"%c", s->window[s->strstart]));
18417 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
18418 bflush = _tr_tally(s, 0, s.window[s.strstart]);
18419 s.lookahead--;
18420 s.strstart++;
18421 if (bflush) {
18422 /*** FLUSH_BLOCK(s, 0); ***/
18423 flush_block_only(s, false);
18424 if (s.strm.avail_out === 0) {
18425 return BS_NEED_MORE;
18426 }
18427 /***/
18428 }
18429 }
18430 s.insert = 0;
18431 if (flush === Z_FINISH) {
18432 /*** FLUSH_BLOCK(s, 1); ***/
18433 flush_block_only(s, true);
18434 if (s.strm.avail_out === 0) {
18435 return BS_FINISH_STARTED;
18436 }
18437 /***/
18438 return BS_FINISH_DONE;
18439 }
18440 if (s.last_lit) {
18441 /*** FLUSH_BLOCK(s, 0); ***/
18442 flush_block_only(s, false);
18443 if (s.strm.avail_out === 0) {
18444 return BS_NEED_MORE;
18445 }
18446 /***/
18447 }
18448 return BS_BLOCK_DONE;
18449}
18450
18451/* Values for max_lazy_match, good_match and max_chain_length, depending on
18452 * the desired pack level (0..9). The values given below have been tuned to
18453 * exclude worst case performance for pathological files. Better values may be
18454 * found for specific files.
18455 */
18456class Config {
18457 constructor(good_length, max_lazy, nice_length, max_chain, func) {
18458 this.good_length = good_length;
18459 this.max_lazy = max_lazy;
18460 this.nice_length = nice_length;
18461 this.max_chain = max_chain;
18462 this.func = func;
18463 }
18464}
18465const configuration_table = [
18466 /* good lazy nice chain */
18467 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
18468 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
18469 new Config(4, 5, 16, 8, deflate_fast), /* 2 */
18470 new Config(4, 6, 32, 32, deflate_fast), /* 3 */
18471
18472 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
18473 new Config(8, 16, 32, 32, deflate_slow), /* 5 */
18474 new Config(8, 16, 128, 128, deflate_slow), /* 6 */
18475 new Config(8, 32, 128, 256, deflate_slow), /* 7 */
18476 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
18477 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
18478];
18479
18480
18481/* ===========================================================================
18482 * Initialize the "longest match" routines for a new zlib stream
18483 */
18484function lm_init(s) {
18485 s.window_size = 2 * s.w_size;
18486
18487 /*** CLEAR_HASH(s); ***/
18488 zero$2(s.head); // Fill with NIL (= 0);
18489
18490 /* Set the default configuration parameters:
18491 */
18492 s.max_lazy_match = configuration_table[s.level].max_lazy;
18493 s.good_match = configuration_table[s.level].good_length;
18494 s.nice_match = configuration_table[s.level].nice_length;
18495 s.max_chain_length = configuration_table[s.level].max_chain;
18496
18497 s.strstart = 0;
18498 s.block_start = 0;
18499 s.lookahead = 0;
18500 s.insert = 0;
18501 s.match_length = s.prev_length = MIN_MATCH$1 - 1;
18502 s.match_available = 0;
18503 s.ins_h = 0;
18504}
18505
18506class DeflateState {
18507 constructor() {
18508 this.strm = null; /* pointer back to this zlib stream */
18509 this.status = 0; /* as the name implies */
18510 this.pending_buf = null; /* output still pending */
18511 this.pending_buf_size = 0; /* size of pending_buf */
18512 this.pending_out = 0; /* next pending byte to output to the stream */
18513 this.pending = 0; /* nb of bytes in the pending buffer */
18514 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
18515 this.gzhead = null; /* gzip header information to write */
18516 this.gzindex = 0; /* where in extra, name, or comment */
18517 this.method = Z_DEFLATED; /* can only be DEFLATED */
18518 this.last_flush = -1; /* value of flush param for previous deflate call */
18519
18520 this.w_size = 0; /* LZ77 window size (32K by default) */
18521 this.w_bits = 0; /* log2(w_size) (8..16) */
18522 this.w_mask = 0; /* w_size - 1 */
18523
18524 this.window = null;
18525 /* Sliding window. Input bytes are read into the second half of the window,
18526 * and move to the first half later to keep a dictionary of at least wSize
18527 * bytes. With this organization, matches are limited to a distance of
18528 * wSize-MAX_MATCH bytes, but this ensures that IO is always
18529 * performed with a length multiple of the block size.
18530 */
18531
18532 this.window_size = 0;
18533 /* Actual size of window: 2*wSize, except when the user input buffer
18534 * is directly used as sliding window.
18535 */
18536
18537 this.prev = null;
18538 /* Link to older string with same hash index. To limit the size of this
18539 * array to 64K, this link is maintained only for the last 32K strings.
18540 * An index in this array is thus a window index modulo 32K.
18541 */
18542
18543 this.head = null; /* Heads of the hash chains or NIL. */
18544
18545 this.ins_h = 0; /* hash index of string to be inserted */
18546 this.hash_size = 0; /* number of elements in hash table */
18547 this.hash_bits = 0; /* log2(hash_size) */
18548 this.hash_mask = 0; /* hash_size-1 */
18549
18550 this.hash_shift = 0;
18551 /* Number of bits by which ins_h must be shifted at each input
18552 * step. It must be such that after MIN_MATCH steps, the oldest
18553 * byte no longer takes part in the hash key, that is:
18554 * hash_shift * MIN_MATCH >= hash_bits
18555 */
18556
18557 this.block_start = 0;
18558 /* Window position at the beginning of the current output block. Gets
18559 * negative when the window is moved backwards.
18560 */
18561
18562 this.match_length = 0; /* length of best match */
18563 this.prev_match = 0; /* previous match */
18564 this.match_available = 0; /* set if previous match exists */
18565 this.strstart = 0; /* start of string to insert */
18566 this.match_start = 0; /* start of matching string */
18567 this.lookahead = 0; /* number of valid bytes ahead in window */
18568
18569 this.prev_length = 0;
18570 /* Length of the best match at previous step. Matches not greater than this
18571 * are discarded. This is used in the lazy match evaluation.
18572 */
18573
18574 this.max_chain_length = 0;
18575 /* To speed up deflation, hash chains are never searched beyond this
18576 * length. A higher limit improves compression ratio but degrades the
18577 * speed.
18578 */
18579
18580 this.max_lazy_match = 0;
18581 /* Attempt to find a better match only when the current match is strictly
18582 * smaller than this value. This mechanism is used only for compression
18583 * levels >= 4.
18584 */
18585 // That's alias to max_lazy_match, don't use directly
18586 //this.max_insert_length = 0;
18587 /* Insert new strings in the hash table only if the match length is not
18588 * greater than this length. This saves time but degrades compression.
18589 * max_insert_length is used only for compression levels <= 3.
18590 */
18591
18592 this.level = 0; /* compression level (1..9) */
18593 this.strategy = 0; /* favor or force Huffman coding*/
18594
18595 this.good_match = 0;
18596 /* Use a faster search when the previous match is longer than this */
18597
18598 this.nice_match = 0; /* Stop searching when current match exceeds this */
18599
18600 /* used by trees.c: */
18601
18602 /* Didn't use ct_data typedef below to suppress compiler warning */
18603
18604 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
18605 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
18606 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
18607
18608 // Use flat array of DOUBLE size, with interleaved fata,
18609 // because JS does not support effective
18610 this.dyn_ltree = new Buf16(HEAP_SIZE$1 * 2);
18611 this.dyn_dtree = new Buf16((2 * D_CODES$1 + 1) * 2);
18612 this.bl_tree = new Buf16((2 * BL_CODES$1 + 1) * 2);
18613 zero$2(this.dyn_ltree);
18614 zero$2(this.dyn_dtree);
18615 zero$2(this.bl_tree);
18616
18617 this.l_desc = null; /* desc. for literal tree */
18618 this.d_desc = null; /* desc. for distance tree */
18619 this.bl_desc = null; /* desc. for bit length tree */
18620
18621 //ush bl_count[MAX_BITS+1];
18622 this.bl_count = new Buf16(MAX_BITS$1 + 1);
18623 /* number of codes at each bit length for an optimal tree */
18624
18625 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
18626 this.heap = new Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */
18627 zero$2(this.heap);
18628
18629 this.heap_len = 0; /* number of elements in the heap */
18630 this.heap_max = 0; /* element of largest frequency */
18631 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
18632 * The same heap array is used to build all trees.
18633 */
18634
18635 this.depth = new Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1];
18636 zero$2(this.depth);
18637 /* Depth of each subtree used as tie breaker for trees of equal frequency
18638 */
18639
18640 this.l_buf = 0; /* buffer index for literals or lengths */
18641
18642 this.lit_bufsize = 0;
18643 /* Size of match buffer for literals/lengths. There are 4 reasons for
18644 * limiting lit_bufsize to 64K:
18645 * - frequencies can be kept in 16 bit counters
18646 * - if compression is not successful for the first block, all input
18647 * data is still in the window so we can still emit a stored block even
18648 * when input comes from standard input. (This can also be done for
18649 * all blocks if lit_bufsize is not greater than 32K.)
18650 * - if compression is not successful for a file smaller than 64K, we can
18651 * even emit a stored file instead of a stored block (saving 5 bytes).
18652 * This is applicable only for zip (not gzip or zlib).
18653 * - creating new Huffman trees less frequently may not provide fast
18654 * adaptation to changes in the input data statistics. (Take for
18655 * example a binary file with poorly compressible code followed by
18656 * a highly compressible string table.) Smaller buffer sizes give
18657 * fast adaptation but have of course the overhead of transmitting
18658 * trees more frequently.
18659 * - I can't count above 4
18660 */
18661
18662 this.last_lit = 0; /* running index in l_buf */
18663
18664 this.d_buf = 0;
18665 /* Buffer index for distances. To simplify the code, d_buf and l_buf have
18666 * the same number of elements. To use different lengths, an extra flag
18667 * array would be necessary.
18668 */
18669
18670 this.opt_len = 0; /* bit length of current block with optimal trees */
18671 this.static_len = 0; /* bit length of current block with static trees */
18672 this.matches = 0; /* number of string matches in current block */
18673 this.insert = 0; /* bytes at end of window left to insert */
18674
18675
18676 this.bi_buf = 0;
18677 /* Output buffer. bits are inserted starting at the bottom (least
18678 * significant bits).
18679 */
18680 this.bi_valid = 0;
18681 /* Number of valid bits in bi_buf. All bits above the last valid bit
18682 * are always zero.
18683 */
18684
18685 // Used for window memory init. We safely ignore it for JS. That makes
18686 // sense only for pointers and memory check tools.
18687 //this.high_water = 0;
18688 /* High water mark offset in window for initialized bytes -- bytes above
18689 * this are set to zero in order to avoid memory check warnings when
18690 * longest match routines access bytes past the input. This is then
18691 * updated to the new high water mark.
18692 */
18693 }
18694}
18695
18696function deflateResetKeep(strm) {
18697 let s;
18698
18699 if (!strm || !strm.state) {
18700 return err(strm, Z_STREAM_ERROR);
18701 }
18702
18703 strm.total_in = strm.total_out = 0;
18704 strm.data_type = Z_UNKNOWN;
18705
18706 s = strm.state;
18707 s.pending = 0;
18708 s.pending_out = 0;
18709
18710 if (s.wrap < 0) {
18711 s.wrap = -s.wrap;
18712 /* was made negative by deflate(..., Z_FINISH); */
18713 }
18714 s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
18715 strm.adler = (s.wrap === 2) ?
18716 0 // crc32(0, Z_NULL, 0)
18717 :
18718 1; // adler32(0, Z_NULL, 0)
18719 s.last_flush = Z_NO_FLUSH;
18720 _tr_init(s);
18721 return Z_OK;
18722}
18723
18724
18725function deflateReset(strm) {
18726 const ret = deflateResetKeep(strm);
18727 if (ret === Z_OK) {
18728 lm_init(strm.state);
18729 }
18730 return ret;
18731}
18732
18733
18734function deflateSetHeader(strm, head) {
18735 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
18736 if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
18737 strm.state.gzhead = head;
18738 return Z_OK;
18739}
18740
18741
18742function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
18743 if (!strm) { // === Z_NULL
18744 return Z_STREAM_ERROR;
18745 }
18746 let wrap = 1;
18747
18748 if (level === Z_DEFAULT_COMPRESSION) {
18749 level = 6;
18750 }
18751
18752 if (windowBits < 0) { /* suppress zlib wrapper */
18753 wrap = 0;
18754 windowBits = -windowBits;
18755 }
18756
18757 else if (windowBits > 15) {
18758 wrap = 2; /* write gzip wrapper instead */
18759 windowBits -= 16;
18760 }
18761
18762
18763 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
18764 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
18765 strategy < 0 || strategy > Z_FIXED) {
18766 return err(strm, Z_STREAM_ERROR);
18767 }
18768
18769
18770 if (windowBits === 8) {
18771 windowBits = 9;
18772 }
18773 /* until 256-byte window bug fixed */
18774
18775 const s = new DeflateState();
18776
18777 strm.state = s;
18778 s.strm = strm;
18779
18780 s.wrap = wrap;
18781 s.gzhead = null;
18782 s.w_bits = windowBits;
18783 s.w_size = 1 << s.w_bits;
18784 s.w_mask = s.w_size - 1;
18785
18786 s.hash_bits = memLevel + 7;
18787 s.hash_size = 1 << s.hash_bits;
18788 s.hash_mask = s.hash_size - 1;
18789 s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1);
18790 s.window = new Buf8(s.w_size * 2);
18791 s.head = new Buf16(s.hash_size);
18792 s.prev = new Buf16(s.w_size);
18793
18794 // Don't need mem init magic for JS.
18795 //s.high_water = 0; /* nothing written to s->window yet */
18796
18797 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
18798
18799 s.pending_buf_size = s.lit_bufsize * 4;
18800
18801 //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
18802 //s->pending_buf = (uchf *) overlay;
18803 s.pending_buf = new Buf8(s.pending_buf_size);
18804
18805 // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
18806 //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
18807 s.d_buf = 1 * s.lit_bufsize;
18808
18809 //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
18810 s.l_buf = (1 + 2) * s.lit_bufsize;
18811
18812 s.level = level;
18813 s.strategy = strategy;
18814 s.method = method;
18815
18816 return deflateReset(strm);
18817}
18818
18819
18820function deflate(strm, flush) {
18821 let old_flush, s;
18822 let beg, val; // for gzip header write only
18823
18824 if (!strm || !strm.state ||
18825 flush > Z_BLOCK || flush < 0) {
18826 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
18827 }
18828
18829 s = strm.state;
18830
18831 if (!strm.output ||
18832 (!strm.input && strm.avail_in !== 0) ||
18833 (s.status === FINISH_STATE && flush !== Z_FINISH)) {
18834 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
18835 }
18836
18837 s.strm = strm; /* just in case */
18838 old_flush = s.last_flush;
18839 s.last_flush = flush;
18840
18841 /* Write the header */
18842 if (s.status === INIT_STATE) {
18843
18844 if (s.wrap === 2) { // GZIP header
18845 strm.adler = 0; //crc32(0L, Z_NULL, 0);
18846 put_byte(s, 31);
18847 put_byte(s, 139);
18848 put_byte(s, 8);
18849 if (!s.gzhead) { // s->gzhead == Z_NULL
18850 put_byte(s, 0);
18851 put_byte(s, 0);
18852 put_byte(s, 0);
18853 put_byte(s, 0);
18854 put_byte(s, 0);
18855 put_byte(s, s.level === 9 ? 2 :
18856 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
18857 4 : 0));
18858 put_byte(s, OS_CODE);
18859 s.status = BUSY_STATE;
18860 }
18861 else {
18862 put_byte(s, (s.gzhead.text ? 1 : 0) +
18863 (s.gzhead.hcrc ? 2 : 0) +
18864 (!s.gzhead.extra ? 0 : 4) +
18865 (!s.gzhead.name ? 0 : 8) +
18866 (!s.gzhead.comment ? 0 : 16)
18867 );
18868 put_byte(s, s.gzhead.time & 0xff);
18869 put_byte(s, (s.gzhead.time >> 8) & 0xff);
18870 put_byte(s, (s.gzhead.time >> 16) & 0xff);
18871 put_byte(s, (s.gzhead.time >> 24) & 0xff);
18872 put_byte(s, s.level === 9 ? 2 :
18873 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
18874 4 : 0));
18875 put_byte(s, s.gzhead.os & 0xff);
18876 if (s.gzhead.extra && s.gzhead.extra.length) {
18877 put_byte(s, s.gzhead.extra.length & 0xff);
18878 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
18879 }
18880 if (s.gzhead.hcrc) {
18881 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
18882 }
18883 s.gzindex = 0;
18884 s.status = EXTRA_STATE;
18885 }
18886 }
18887 else // DEFLATE header
18888 {
18889 let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
18890 let level_flags = -1;
18891
18892 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
18893 level_flags = 0;
18894 } else if (s.level < 6) {
18895 level_flags = 1;
18896 } else if (s.level === 6) {
18897 level_flags = 2;
18898 } else {
18899 level_flags = 3;
18900 }
18901 header |= (level_flags << 6);
18902 if (s.strstart !== 0) { header |= PRESET_DICT; }
18903 header += 31 - (header % 31);
18904
18905 s.status = BUSY_STATE;
18906 putShortMSB(s, header);
18907
18908 /* Save the adler32 of the preset dictionary: */
18909 if (s.strstart !== 0) {
18910 putShortMSB(s, strm.adler >>> 16);
18911 putShortMSB(s, strm.adler & 0xffff);
18912 }
18913 strm.adler = 1; // adler32(0L, Z_NULL, 0);
18914 }
18915 }
18916
18917 //#ifdef GZIP
18918 if (s.status === EXTRA_STATE) {
18919 if (s.gzhead.extra/* != Z_NULL*/) {
18920 beg = s.pending; /* start of bytes to update crc */
18921
18922 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
18923 if (s.pending === s.pending_buf_size) {
18924 if (s.gzhead.hcrc && s.pending > beg) {
18925 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18926 }
18927 flush_pending(strm);
18928 beg = s.pending;
18929 if (s.pending === s.pending_buf_size) {
18930 break;
18931 }
18932 }
18933 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
18934 s.gzindex++;
18935 }
18936 if (s.gzhead.hcrc && s.pending > beg) {
18937 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18938 }
18939 if (s.gzindex === s.gzhead.extra.length) {
18940 s.gzindex = 0;
18941 s.status = NAME_STATE;
18942 }
18943 }
18944 else {
18945 s.status = NAME_STATE;
18946 }
18947 }
18948 if (s.status === NAME_STATE) {
18949 if (s.gzhead.name/* != Z_NULL*/) {
18950 beg = s.pending; /* start of bytes to update crc */
18951 //int val;
18952
18953 do {
18954 if (s.pending === s.pending_buf_size) {
18955 if (s.gzhead.hcrc && s.pending > beg) {
18956 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18957 }
18958 flush_pending(strm);
18959 beg = s.pending;
18960 if (s.pending === s.pending_buf_size) {
18961 val = 1;
18962 break;
18963 }
18964 }
18965 // JS specific: little magic to add zero terminator to end of string
18966 if (s.gzindex < s.gzhead.name.length) {
18967 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
18968 } else {
18969 val = 0;
18970 }
18971 put_byte(s, val);
18972 } while (val !== 0);
18973
18974 if (s.gzhead.hcrc && s.pending > beg) {
18975 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18976 }
18977 if (val === 0) {
18978 s.gzindex = 0;
18979 s.status = COMMENT_STATE;
18980 }
18981 }
18982 else {
18983 s.status = COMMENT_STATE;
18984 }
18985 }
18986 if (s.status === COMMENT_STATE) {
18987 if (s.gzhead.comment/* != Z_NULL*/) {
18988 beg = s.pending; /* start of bytes to update crc */
18989 //int val;
18990
18991 do {
18992 if (s.pending === s.pending_buf_size) {
18993 if (s.gzhead.hcrc && s.pending > beg) {
18994 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18995 }
18996 flush_pending(strm);
18997 beg = s.pending;
18998 if (s.pending === s.pending_buf_size) {
18999 val = 1;
19000 break;
19001 }
19002 }
19003 // JS specific: little magic to add zero terminator to end of string
19004 if (s.gzindex < s.gzhead.comment.length) {
19005 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
19006 } else {
19007 val = 0;
19008 }
19009 put_byte(s, val);
19010 } while (val !== 0);
19011
19012 if (s.gzhead.hcrc && s.pending > beg) {
19013 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
19014 }
19015 if (val === 0) {
19016 s.status = HCRC_STATE;
19017 }
19018 }
19019 else {
19020 s.status = HCRC_STATE;
19021 }
19022 }
19023 if (s.status === HCRC_STATE) {
19024 if (s.gzhead.hcrc) {
19025 if (s.pending + 2 > s.pending_buf_size) {
19026 flush_pending(strm);
19027 }
19028 if (s.pending + 2 <= s.pending_buf_size) {
19029 put_byte(s, strm.adler & 0xff);
19030 put_byte(s, (strm.adler >> 8) & 0xff);
19031 strm.adler = 0; //crc32(0L, Z_NULL, 0);
19032 s.status = BUSY_STATE;
19033 }
19034 }
19035 else {
19036 s.status = BUSY_STATE;
19037 }
19038 }
19039 //#endif
19040
19041 /* Flush as much pending output as possible */
19042 if (s.pending !== 0) {
19043 flush_pending(strm);
19044 if (strm.avail_out === 0) {
19045 /* Since avail_out is 0, deflate will be called again with
19046 * more output space, but possibly with both pending and
19047 * avail_in equal to zero. There won't be anything to do,
19048 * but this is not an error situation so make sure we
19049 * return OK instead of BUF_ERROR at next call of deflate:
19050 */
19051 s.last_flush = -1;
19052 return Z_OK;
19053 }
19054
19055 /* Make sure there is something to do and avoid duplicate consecutive
19056 * flushes. For repeated and useless calls with Z_FINISH, we keep
19057 * returning Z_STREAM_END instead of Z_BUF_ERROR.
19058 */
19059 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
19060 flush !== Z_FINISH) {
19061 return err(strm, Z_BUF_ERROR);
19062 }
19063
19064 /* User must not provide more input after the first FINISH: */
19065 if (s.status === FINISH_STATE && strm.avail_in !== 0) {
19066 return err(strm, Z_BUF_ERROR);
19067 }
19068
19069 /* Start a new block or continue the current one.
19070 */
19071 if (strm.avail_in !== 0 || s.lookahead !== 0 ||
19072 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
19073 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
19074 (s.strategy === Z_RLE ? deflate_rle(s, flush) :
19075 configuration_table[s.level].func(s, flush));
19076
19077 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
19078 s.status = FINISH_STATE;
19079 }
19080 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
19081 if (strm.avail_out === 0) {
19082 s.last_flush = -1;
19083 /* avoid BUF_ERROR next call, see above */
19084 }
19085 return Z_OK;
19086 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
19087 * of deflate should use the same flush parameter to make sure
19088 * that the flush is complete. So we don't have to output an
19089 * empty block here, this will be done at next call. This also
19090 * ensures that for a very small output buffer, we emit at most
19091 * one empty block.
19092 */
19093 }
19094 if (bstate === BS_BLOCK_DONE) {
19095 if (flush === Z_PARTIAL_FLUSH) {
19096 _tr_align(s);
19097 }
19098 else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
19099
19100 _tr_stored_block(s, 0, 0, false);
19101 /* For a full flush, this empty block will be recognized
19102 * as a special marker by inflate_sync().
19103 */
19104 if (flush === Z_FULL_FLUSH) {
19105 /*** CLEAR_HASH(s); ***/ /* forget history */
19106 zero$2(s.head); // Fill with NIL (= 0);
19107
19108 if (s.lookahead === 0) {
19109 s.strstart = 0;
19110 s.block_start = 0;
19111 s.insert = 0;
19112 }
19113 }
19114 }
19115 flush_pending(strm);
19116 if (strm.avail_out === 0) {
19117 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
19118 return Z_OK;
19119 }
19120 }
19121 }
19122 //Assert(strm->avail_out > 0, "bug2");
19123 //if (strm.avail_out <= 0) { throw new Error("bug2");}
19124
19125 if (flush !== Z_FINISH) { return Z_OK; }
19126 if (s.wrap <= 0) { return Z_STREAM_END; }
19127
19128 /* Write the trailer */
19129 if (s.wrap === 2) {
19130 put_byte(s, strm.adler & 0xff);
19131 put_byte(s, (strm.adler >> 8) & 0xff);
19132 put_byte(s, (strm.adler >> 16) & 0xff);
19133 put_byte(s, (strm.adler >> 24) & 0xff);
19134 put_byte(s, strm.total_in & 0xff);
19135 put_byte(s, (strm.total_in >> 8) & 0xff);
19136 put_byte(s, (strm.total_in >> 16) & 0xff);
19137 put_byte(s, (strm.total_in >> 24) & 0xff);
19138 }
19139 else {
19140 putShortMSB(s, strm.adler >>> 16);
19141 putShortMSB(s, strm.adler & 0xffff);
19142 }
19143
19144 flush_pending(strm);
19145 /* If avail_out is zero, the application will call deflate again
19146 * to flush the rest.
19147 */
19148 if (s.wrap > 0) { s.wrap = -s.wrap; }
19149 /* write the trailer only once! */
19150 return s.pending !== 0 ? Z_OK : Z_STREAM_END;
19151}
19152
19153function deflateEnd(strm) {
19154 let status;
19155
19156 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
19157 return Z_STREAM_ERROR;
19158 }
19159
19160 status = strm.state.status;
19161 if (status !== INIT_STATE &&
19162 status !== EXTRA_STATE &&
19163 status !== NAME_STATE &&
19164 status !== COMMENT_STATE &&
19165 status !== HCRC_STATE &&
19166 status !== BUSY_STATE &&
19167 status !== FINISH_STATE
19168 ) {
19169 return err(strm, Z_STREAM_ERROR);
19170 }
19171
19172 strm.state = null;
19173
19174 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
19175}
19176
19177
19178/* =========================================================================
19179 * Initializes the compression dictionary from the given byte
19180 * sequence without producing any compressed output.
19181 */
19182function deflateSetDictionary(strm, dictionary) {
19183 let dictLength = dictionary.length;
19184
19185 let s;
19186 let str, n;
19187 let wrap;
19188 let avail;
19189 let next;
19190 let input;
19191 let tmpDict;
19192
19193 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
19194 return Z_STREAM_ERROR;
19195 }
19196
19197 s = strm.state;
19198 wrap = s.wrap;
19199
19200 if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
19201 return Z_STREAM_ERROR;
19202 }
19203
19204 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
19205 if (wrap === 1) {
19206 /* adler32(strm->adler, dictionary, dictLength); */
19207 strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
19208 }
19209
19210 s.wrap = 0; /* avoid computing Adler-32 in read_buf */
19211
19212 /* if dictionary would fill window, just replace the history */
19213 if (dictLength >= s.w_size) {
19214 if (wrap === 0) { /* already empty otherwise */
19215 /*** CLEAR_HASH(s); ***/
19216 zero$2(s.head); // Fill with NIL (= 0);
19217 s.strstart = 0;
19218 s.block_start = 0;
19219 s.insert = 0;
19220 }
19221 /* use the tail */
19222 // dictionary = dictionary.slice(dictLength - s.w_size);
19223 tmpDict = new Buf8(s.w_size);
19224 arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
19225 dictionary = tmpDict;
19226 dictLength = s.w_size;
19227 }
19228 /* insert dictionary into window and hash */
19229 avail = strm.avail_in;
19230 next = strm.next_in;
19231 input = strm.input;
19232 strm.avail_in = dictLength;
19233 strm.next_in = 0;
19234 strm.input = dictionary;
19235 fill_window(s);
19236 while (s.lookahead >= MIN_MATCH$1) {
19237 str = s.strstart;
19238 n = s.lookahead - (MIN_MATCH$1 - 1);
19239 do {
19240 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
19241 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;
19242
19243 s.prev[str & s.w_mask] = s.head[s.ins_h];
19244
19245 s.head[s.ins_h] = str;
19246 str++;
19247 } while (--n);
19248 s.strstart = str;
19249 s.lookahead = MIN_MATCH$1 - 1;
19250 fill_window(s);
19251 }
19252 s.strstart += s.lookahead;
19253 s.block_start = s.strstart;
19254 s.insert = s.lookahead;
19255 s.lookahead = 0;
19256 s.match_length = s.prev_length = MIN_MATCH$1 - 1;
19257 s.match_available = 0;
19258 strm.next_in = next;
19259 strm.input = input;
19260 strm.avail_in = avail;
19261 s.wrap = wrap;
19262 return Z_OK;
19263}
19264
19265/* Not implemented
19266exports.deflateBound = deflateBound;
19267exports.deflateCopy = deflateCopy;
19268exports.deflateParams = deflateParams;
19269exports.deflatePending = deflatePending;
19270exports.deflatePrime = deflatePrime;
19271exports.deflateTune = deflateTune;
19272*/
19273
19274// String encode/decode helpers
19275
19276try {
19277 String.fromCharCode.apply(null, [ 0 ]);
19278} catch (__) {
19279}
19280try {
19281 String.fromCharCode.apply(null, new Uint8Array(1));
19282} catch (__) {
19283}
19284
19285
19286// Table with utf8 lengths (calculated by first byte of sequence)
19287// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
19288// because max possible codepoint is 0x10ffff
19289const _utf8len = new Buf8(256);
19290for (let q = 0; q < 256; q++) {
19291 _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;
19292}
19293_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
19294
19295
19296// convert string to array (typed, when possible)
19297function string2buf (str) {
19298 let c, c2, m_pos, i, buf_len = 0;
19299 const str_len = str.length;
19300
19301 // count binary size
19302 for (m_pos = 0; m_pos < str_len; m_pos++) {
19303 c = str.charCodeAt(m_pos);
19304 if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
19305 c2 = str.charCodeAt(m_pos + 1);
19306 if ((c2 & 0xfc00) === 0xdc00) {
19307 c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
19308 m_pos++;
19309 }
19310 }
19311 buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
19312 }
19313
19314 // allocate buffer
19315 const buf = new Buf8(buf_len);
19316
19317 // convert
19318 for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
19319 c = str.charCodeAt(m_pos);
19320 if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
19321 c2 = str.charCodeAt(m_pos + 1);
19322 if ((c2 & 0xfc00) === 0xdc00) {
19323 c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
19324 m_pos++;
19325 }
19326 }
19327 if (c < 0x80) {
19328 /* one byte */
19329 buf[i++] = c;
19330 } else if (c < 0x800) {
19331 /* two bytes */
19332 buf[i++] = 0xC0 | c >>> 6;
19333 buf[i++] = 0x80 | c & 0x3f;
19334 } else if (c < 0x10000) {
19335 /* three bytes */
19336 buf[i++] = 0xE0 | c >>> 12;
19337 buf[i++] = 0x80 | c >>> 6 & 0x3f;
19338 buf[i++] = 0x80 | c & 0x3f;
19339 } else {
19340 /* four bytes */
19341 buf[i++] = 0xf0 | c >>> 18;
19342 buf[i++] = 0x80 | c >>> 12 & 0x3f;
19343 buf[i++] = 0x80 | c >>> 6 & 0x3f;
19344 buf[i++] = 0x80 | c & 0x3f;
19345 }
19346 }
19347
19348 return buf;
19349}
19350
19351
19352// Convert binary string (typed, when possible)
19353function binstring2buf (str) {
19354 const buf = new Buf8(str.length);
19355 for (let i = 0, len = buf.length; i < len; i++) {
19356 buf[i] = str.charCodeAt(i);
19357 }
19358 return buf;
19359}
19360
19361// (C) 1995-2013 Jean-loup Gailly and Mark Adler
19362// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
19363//
19364// This software is provided 'as-is', without any express or implied
19365// warranty. In no event will the authors be held liable for any damages
19366// arising from the use of this software.
19367//
19368// Permission is granted to anyone to use this software for any purpose,
19369// including commercial applications, and to alter it and redistribute it
19370// freely, subject to the following restrictions:
19371//
19372// 1. The origin of this software must not be misrepresented; you must not
19373// claim that you wrote the original software. If you use this software
19374// in a product, an acknowledgment in the product documentation would be
19375// appreciated but is not required.
19376// 2. Altered source versions must be plainly marked as such, and must not be
19377// misrepresented as being the original software.
19378// 3. This notice may not be removed or altered from any source distribution.
19379
19380class ZStream {
19381 constructor() {
19382 /* next input byte */
19383 this.input = null; // JS specific, because we have no pointers
19384 this.next_in = 0;
19385 /* number of bytes available at input */
19386 this.avail_in = 0;
19387 /* total number of input bytes read so far */
19388 this.total_in = 0;
19389 /* next output byte should be put there */
19390 this.output = null; // JS specific, because we have no pointers
19391 this.next_out = 0;
19392 /* remaining free space at output */
19393 this.avail_out = 0;
19394 /* total number of bytes output so far */
19395 this.total_out = 0;
19396 /* last error message, NULL if no error */
19397 this.msg = ''/*Z_NULL*/;
19398 /* not visible by applications */
19399 this.state = null;
19400 /* best guess about the data type: binary or text */
19401 this.data_type = 2/*Z_UNKNOWN*/;
19402 /* adler32 value of the uncompressed data */
19403 this.adler = 0;
19404 }
19405}
19406
19407/* ===========================================================================*/
19408
19409
19410/**
19411 * class Deflate
19412 *
19413 * Generic JS-style wrapper for zlib calls. If you don't need
19414 * streaming behaviour - use more simple functions: [[deflate]],
19415 * [[deflateRaw]] and [[gzip]].
19416 **/
19417
19418/* internal
19419 * Deflate.chunks -> Array
19420 *
19421 * Chunks of output data, if [[Deflate#onData]] not overridden.
19422 **/
19423
19424/**
19425 * Deflate.result -> Uint8Array|Array
19426 *
19427 * Compressed result, generated by default [[Deflate#onData]]
19428 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
19429 * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
19430 * push a chunk with explicit flush (call [[Deflate#push]] with
19431 * `Z_SYNC_FLUSH` param).
19432 **/
19433
19434/**
19435 * Deflate.err -> Number
19436 *
19437 * Error code after deflate finished. 0 (Z_OK) on success.
19438 * You will not need it in real life, because deflate errors
19439 * are possible only on wrong options or bad `onData` / `onEnd`
19440 * custom handlers.
19441 **/
19442
19443/**
19444 * Deflate.msg -> String
19445 *
19446 * Error message, if [[Deflate.err]] != 0
19447 **/
19448
19449
19450/**
19451 * new Deflate(options)
19452 * - options (Object): zlib deflate options.
19453 *
19454 * Creates new deflator instance with specified params. Throws exception
19455 * on bad params. Supported options:
19456 *
19457 * - `level`
19458 * - `windowBits`
19459 * - `memLevel`
19460 * - `strategy`
19461 * - `dictionary`
19462 *
19463 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
19464 * for more information on these.
19465 *
19466 * Additional options, for internal needs:
19467 *
19468 * - `chunkSize` - size of generated data chunks (16K by default)
19469 * - `raw` (Boolean) - do raw deflate
19470 * - `gzip` (Boolean) - create gzip wrapper
19471 * - `to` (String) - if equal to 'string', then result will be "binary string"
19472 * (each char code [0..255])
19473 * - `header` (Object) - custom header for gzip
19474 * - `text` (Boolean) - true if compressed data believed to be text
19475 * - `time` (Number) - modification time, unix timestamp
19476 * - `os` (Number) - operation system code
19477 * - `extra` (Array) - array of bytes with extra data (max 65536)
19478 * - `name` (String) - file name (binary string)
19479 * - `comment` (String) - comment (binary string)
19480 * - `hcrc` (Boolean) - true if header crc should be added
19481 *
19482 * ##### Example:
19483 *
19484 * ```javascript
19485 * var pako = void('pako')
19486 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
19487 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
19488 *
19489 * var deflate = new pako.Deflate({ level: 3});
19490 *
19491 * deflate.push(chunk1, false);
19492 * deflate.push(chunk2, true); // true -> last chunk
19493 *
19494 * if (deflate.err) { throw new Error(deflate.err); }
19495 *
19496 * console.log(deflate.result);
19497 * ```
19498 **/
19499
19500class Deflate {
19501 constructor(options) {
19502 this.options = {
19503 level: Z_DEFAULT_COMPRESSION,
19504 method: Z_DEFLATED,
19505 chunkSize: 16384,
19506 windowBits: 15,
19507 memLevel: 8,
19508 strategy: Z_DEFAULT_STRATEGY,
19509 ...(options || {})
19510 };
19511
19512 const opt = this.options;
19513
19514 if (opt.raw && (opt.windowBits > 0)) {
19515 opt.windowBits = -opt.windowBits;
19516 }
19517
19518 else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
19519 opt.windowBits += 16;
19520 }
19521
19522 this.err = 0; // error code, if happens (0 = Z_OK)
19523 this.msg = ''; // error message
19524 this.ended = false; // used to avoid multiple onEnd() calls
19525 this.chunks = []; // chunks of compressed data
19526
19527 this.strm = new ZStream();
19528 this.strm.avail_out = 0;
19529
19530 var status = deflateInit2(
19531 this.strm,
19532 opt.level,
19533 opt.method,
19534 opt.windowBits,
19535 opt.memLevel,
19536 opt.strategy
19537 );
19538
19539 if (status !== Z_OK) {
19540 throw new Error(msg[status]);
19541 }
19542
19543 if (opt.header) {
19544 deflateSetHeader(this.strm, opt.header);
19545 }
19546
19547 if (opt.dictionary) {
19548 let dict;
19549 // Convert data if needed
19550 if (typeof opt.dictionary === 'string') {
19551 // If we need to compress text, change encoding to utf8.
19552 dict = string2buf(opt.dictionary);
19553 } else if (opt.dictionary instanceof ArrayBuffer) {
19554 dict = new Uint8Array(opt.dictionary);
19555 } else {
19556 dict = opt.dictionary;
19557 }
19558
19559 status = deflateSetDictionary(this.strm, dict);
19560
19561 if (status !== Z_OK) {
19562 throw new Error(msg[status]);
19563 }
19564
19565 this._dict_set = true;
19566 }
19567 }
19568
19569 /**
19570 * Deflate#push(data[, mode]) -> Boolean
19571 * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
19572 * converted to utf8 byte sequence.
19573 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
19574 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
19575 *
19576 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
19577 * new compressed chunks. Returns `true` on success. The last data block must have
19578 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
19579 * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
19580 * can use mode Z_SYNC_FLUSH, keeping the compression context.
19581 *
19582 * On fail call [[Deflate#onEnd]] with error code and return false.
19583 *
19584 * We strongly recommend to use `Uint8Array` on input for best speed (output
19585 * array format is detected automatically). Also, don't skip last param and always
19586 * use the same type in your code (boolean or number). That will improve JS speed.
19587 *
19588 * For regular `Array`-s make sure all elements are [0..255].
19589 *
19590 * ##### Example
19591 *
19592 * ```javascript
19593 * push(chunk, false); // push one of data chunks
19594 * ...
19595 * push(chunk, true); // push last chunk
19596 * ```
19597 **/
19598 push(data, mode) {
19599 const { strm, options: { chunkSize } } = this;
19600 var status, _mode;
19601
19602 if (this.ended) { return false; }
19603
19604 _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
19605
19606 // Convert data if needed
19607 if (typeof data === 'string') {
19608 // If we need to compress text, change encoding to utf8.
19609 strm.input = string2buf(data);
19610 } else if (data instanceof ArrayBuffer) {
19611 strm.input = new Uint8Array(data);
19612 } else {
19613 strm.input = data;
19614 }
19615
19616 strm.next_in = 0;
19617 strm.avail_in = strm.input.length;
19618
19619 do {
19620 if (strm.avail_out === 0) {
19621 strm.output = new Buf8(chunkSize);
19622 strm.next_out = 0;
19623 strm.avail_out = chunkSize;
19624 }
19625 status = deflate(strm, _mode); /* no bad return value */
19626
19627 if (status !== Z_STREAM_END && status !== Z_OK) {
19628 this.onEnd(status);
19629 this.ended = true;
19630 return false;
19631 }
19632 if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
19633 this.onData(shrinkBuf(strm.output, strm.next_out));
19634 }
19635 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
19636
19637 // Finalize on the last chunk.
19638 if (_mode === Z_FINISH) {
19639 status = deflateEnd(this.strm);
19640 this.onEnd(status);
19641 this.ended = true;
19642 return status === Z_OK;
19643 }
19644
19645 // callback interim results if Z_SYNC_FLUSH.
19646 if (_mode === Z_SYNC_FLUSH) {
19647 this.onEnd(Z_OK);
19648 strm.avail_out = 0;
19649 return true;
19650 }
19651
19652 return true;
19653 };
19654 /**
19655 * Deflate#onData(chunk) -> Void
19656 * - chunk (Uint8Array|Array|String): output data. Type of array depends
19657 * on js engine support. When string output requested, each chunk
19658 * will be string.
19659 *
19660 * By default, stores data blocks in `chunks[]` property and glue
19661 * those in `onEnd`. Override this handler, if you need another behaviour.
19662 **/
19663 onData(chunk) {
19664 this.chunks.push(chunk);
19665 };
19666
19667 /**
19668 * Deflate#onEnd(status) -> Void
19669 * - status (Number): deflate status. 0 (Z_OK) on success,
19670 * other if not.
19671 *
19672 * Called once after you tell deflate that the input stream is
19673 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
19674 * or if an error happened. By default - join collected chunks,
19675 * free memory and fill `results` / `err` properties.
19676 **/
19677 onEnd(status) {
19678 // On success - join
19679 if (status === Z_OK) {
19680 this.result = flattenChunks(this.chunks);
19681 }
19682 this.chunks = [];
19683 this.err = status;
19684 this.msg = this.strm.msg;
19685 };
19686}
19687
19688// (C) 1995-2013 Jean-loup Gailly and Mark Adler
19689// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
19690//
19691// This software is provided 'as-is', without any express or implied
19692// warranty. In no event will the authors be held liable for any damages
19693// arising from the use of this software.
19694//
19695// Permission is granted to anyone to use this software for any purpose,
19696// including commercial applications, and to alter it and redistribute it
19697// freely, subject to the following restrictions:
19698//
19699// 1. The origin of this software must not be misrepresented; you must not
19700// claim that you wrote the original software. If you use this software
19701// in a product, an acknowledgment in the product documentation would be
19702// appreciated but is not required.
19703// 2. Altered source versions must be plainly marked as such, and must not be
19704// misrepresented as being the original software.
19705// 3. This notice may not be removed or altered from any source distribution.
19706
19707// See state defs from inflate.js
19708const BAD = 30; /* got a data error -- remain here until reset */
19709const TYPE = 12; /* i: waiting for type bits, including last-flag bit */
19710
19711/*
19712 Decode literal, length, and distance codes and write out the resulting
19713 literal and match bytes until either not enough input or output is
19714 available, an end-of-block is encountered, or a data error is encountered.
19715 When large enough input and output buffers are supplied to inflate(), for
19716 example, a 16K input buffer and a 64K output buffer, more than 95% of the
19717 inflate execution time is spent in this routine.
19718
19719 Entry assumptions:
19720
19721 state.mode === LEN
19722 strm.avail_in >= 6
19723 strm.avail_out >= 258
19724 start >= strm.avail_out
19725 state.bits < 8
19726
19727 On return, state.mode is one of:
19728
19729 LEN -- ran out of enough output space or enough available input
19730 TYPE -- reached end of block code, inflate() to interpret next block
19731 BAD -- error in block data
19732
19733 Notes:
19734
19735 - The maximum input bits used by a length/distance pair is 15 bits for the
19736 length code, 5 bits for the length extra, 15 bits for the distance code,
19737 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
19738 Therefore if strm.avail_in >= 6, then there is enough input to avoid
19739 checking for available input while decoding.
19740
19741 - The maximum bytes that a single length/distance pair can output is 258
19742 bytes, which is the maximum length that can be coded. inflate_fast()
19743 requires strm.avail_out >= 258 for each loop to avoid checking for
19744 output space.
19745 */
19746function inflate_fast(strm, start) {
19747 let _in; /* local strm.input */
19748 let _out; /* local strm.output */
19749 // Use `s_window` instead `window`, avoid conflict with instrumentation tools
19750 let hold; /* local strm.hold */
19751 let bits; /* local strm.bits */
19752 let here; /* retrieved table entry */
19753 let op; /* code bits, operation, extra bits, or */
19754 /* window position, window bytes to copy */
19755 let len; /* match length, unused bytes */
19756 let dist; /* match distance */
19757 let from; /* where to copy match from */
19758 let from_source;
19759
19760
19761
19762 /* copy state to local variables */
19763 const state = strm.state;
19764 //here = state.here;
19765 _in = strm.next_in;
19766 const input = strm.input;
19767 const last = _in + (strm.avail_in - 5);
19768 _out = strm.next_out;
19769 const output = strm.output;
19770 const beg = _out - (start - strm.avail_out);
19771 const end = _out + (strm.avail_out - 257);
19772 //#ifdef INFLATE_STRICT
19773 const dmax = state.dmax;
19774 //#endif
19775 const wsize = state.wsize;
19776 const whave = state.whave;
19777 const wnext = state.wnext;
19778 const s_window = state.window;
19779 hold = state.hold;
19780 bits = state.bits;
19781 const lcode = state.lencode;
19782 const dcode = state.distcode;
19783 const lmask = (1 << state.lenbits) - 1;
19784 const dmask = (1 << state.distbits) - 1;
19785
19786
19787 /* decode literals and length/distances until end-of-block or not enough
19788 input data or output space */
19789
19790 top:
19791 do {
19792 if (bits < 15) {
19793 hold += input[_in++] << bits;
19794 bits += 8;
19795 hold += input[_in++] << bits;
19796 bits += 8;
19797 }
19798
19799 here = lcode[hold & lmask];
19800
19801 dolen:
19802 for (;;) { // Goto emulation
19803 op = here >>> 24/*here.bits*/;
19804 hold >>>= op;
19805 bits -= op;
19806 op = here >>> 16 & 0xff/*here.op*/;
19807 if (op === 0) { /* literal */
19808 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
19809 // "inflate: literal '%c'\n" :
19810 // "inflate: literal 0x%02x\n", here.val));
19811 output[_out++] = here & 0xffff/*here.val*/;
19812 } else if (op & 16) { /* length base */
19813 len = here & 0xffff/*here.val*/;
19814 op &= 15; /* number of extra bits */
19815 if (op) {
19816 if (bits < op) {
19817 hold += input[_in++] << bits;
19818 bits += 8;
19819 }
19820 len += hold & (1 << op) - 1;
19821 hold >>>= op;
19822 bits -= op;
19823 }
19824 //Tracevv((stderr, "inflate: length %u\n", len));
19825 if (bits < 15) {
19826 hold += input[_in++] << bits;
19827 bits += 8;
19828 hold += input[_in++] << bits;
19829 bits += 8;
19830 }
19831 here = dcode[hold & dmask];
19832
19833 dodist:
19834 for (;;) { // goto emulation
19835 op = here >>> 24/*here.bits*/;
19836 hold >>>= op;
19837 bits -= op;
19838 op = here >>> 16 & 0xff/*here.op*/;
19839
19840 if (op & 16) { /* distance base */
19841 dist = here & 0xffff/*here.val*/;
19842 op &= 15; /* number of extra bits */
19843 if (bits < op) {
19844 hold += input[_in++] << bits;
19845 bits += 8;
19846 if (bits < op) {
19847 hold += input[_in++] << bits;
19848 bits += 8;
19849 }
19850 }
19851 dist += hold & (1 << op) - 1;
19852 //#ifdef INFLATE_STRICT
19853 if (dist > dmax) {
19854 strm.msg = "invalid distance too far back";
19855 state.mode = BAD;
19856 break top;
19857 }
19858 //#endif
19859 hold >>>= op;
19860 bits -= op;
19861 //Tracevv((stderr, "inflate: distance %u\n", dist));
19862 op = _out - beg; /* max distance in output */
19863 if (dist > op) { /* see if copy from window */
19864 op = dist - op; /* distance back in window */
19865 if (op > whave) {
19866 if (state.sane) {
19867 strm.msg = "invalid distance too far back";
19868 state.mode = BAD;
19869 break top;
19870 }
19871
19872 // (!) This block is disabled in zlib defaults,
19873 // don't enable it for binary compatibility
19874 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
19875 // if (len <= op - whave) {
19876 // do {
19877 // output[_out++] = 0;
19878 // } while (--len);
19879 // continue top;
19880 // }
19881 // len -= op - whave;
19882 // do {
19883 // output[_out++] = 0;
19884 // } while (--op > whave);
19885 // if (op === 0) {
19886 // from = _out - dist;
19887 // do {
19888 // output[_out++] = output[from++];
19889 // } while (--len);
19890 // continue top;
19891 // }
19892 //#endif
19893 }
19894 from = 0; // window index
19895 from_source = s_window;
19896 if (wnext === 0) { /* very common case */
19897 from += wsize - op;
19898 if (op < len) { /* some from window */
19899 len -= op;
19900 do {
19901 output[_out++] = s_window[from++];
19902 } while (--op);
19903 from = _out - dist; /* rest from output */
19904 from_source = output;
19905 }
19906 } else if (wnext < op) { /* wrap around window */
19907 from += wsize + wnext - op;
19908 op -= wnext;
19909 if (op < len) { /* some from end of window */
19910 len -= op;
19911 do {
19912 output[_out++] = s_window[from++];
19913 } while (--op);
19914 from = 0;
19915 if (wnext < len) { /* some from start of window */
19916 op = wnext;
19917 len -= op;
19918 do {
19919 output[_out++] = s_window[from++];
19920 } while (--op);
19921 from = _out - dist; /* rest from output */
19922 from_source = output;
19923 }
19924 }
19925 } else { /* contiguous in window */
19926 from += wnext - op;
19927 if (op < len) { /* some from window */
19928 len -= op;
19929 do {
19930 output[_out++] = s_window[from++];
19931 } while (--op);
19932 from = _out - dist; /* rest from output */
19933 from_source = output;
19934 }
19935 }
19936 while (len > 2) {
19937 output[_out++] = from_source[from++];
19938 output[_out++] = from_source[from++];
19939 output[_out++] = from_source[from++];
19940 len -= 3;
19941 }
19942 if (len) {
19943 output[_out++] = from_source[from++];
19944 if (len > 1) {
19945 output[_out++] = from_source[from++];
19946 }
19947 }
19948 } else {
19949 from = _out - dist; /* copy direct from output */
19950 do { /* minimum length is three */
19951 output[_out++] = output[from++];
19952 output[_out++] = output[from++];
19953 output[_out++] = output[from++];
19954 len -= 3;
19955 } while (len > 2);
19956 if (len) {
19957 output[_out++] = output[from++];
19958 if (len > 1) {
19959 output[_out++] = output[from++];
19960 }
19961 }
19962 }
19963 } else if ((op & 64) === 0) { /* 2nd level distance code */
19964 here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];
19965 continue dodist;
19966 } else {
19967 strm.msg = "invalid distance code";
19968 state.mode = BAD;
19969 break top;
19970 }
19971
19972 break; // need to emulate goto via "continue"
19973 }
19974 } else if ((op & 64) === 0) { /* 2nd level length code */
19975 here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];
19976 continue dolen;
19977 } else if (op & 32) { /* end-of-block */
19978 //Tracevv((stderr, "inflate: end of block\n"));
19979 state.mode = TYPE;
19980 break top;
19981 } else {
19982 strm.msg = "invalid literal/length code";
19983 state.mode = BAD;
19984 break top;
19985 }
19986
19987 break; // need to emulate goto via "continue"
19988 }
19989 } while (_in < last && _out < end);
19990
19991 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
19992 len = bits >> 3;
19993 _in -= len;
19994 bits -= len << 3;
19995 hold &= (1 << bits) - 1;
19996
19997 /* update state and return */
19998 strm.next_in = _in;
19999 strm.next_out = _out;
20000 strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);
20001 strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);
20002 state.hold = hold;
20003 state.bits = bits;
20004 return;
20005}
20006
20007const MAXBITS = 15;
20008const ENOUGH_LENS = 852;
20009const ENOUGH_DISTS = 592;
20010//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
20011
20012const CODES = 0;
20013const LENS = 1;
20014const DISTS = 2;
20015
20016const lbase = [ /* Length codes 257..285 base */
20017 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
20018 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
20019];
20020
20021const lext = [ /* Length codes 257..285 extra */
20022 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
20023 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
20024];
20025
20026const dbase = [ /* Distance codes 0..29 base */
20027 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
20028 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
20029 8193, 12289, 16385, 24577, 0, 0
20030];
20031
20032const dext = [ /* Distance codes 0..29 extra */
20033 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
20034 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
20035 28, 28, 29, 29, 64, 64
20036];
20037
20038function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {
20039 const bits = opts.bits;
20040 //here = opts.here; /* table entry for duplication */
20041
20042 let len = 0; /* a code's length in bits */
20043 let sym = 0; /* index of code symbols */
20044 let min = 0, max = 0; /* minimum and maximum code lengths */
20045 let root = 0; /* number of index bits for root table */
20046 let curr = 0; /* number of index bits for current table */
20047 let drop = 0; /* code bits to drop for sub-table */
20048 let left = 0; /* number of prefix codes available */
20049 let used = 0; /* code entries in table used */
20050 let huff = 0; /* Huffman code */
20051 let incr; /* for incrementing code, index */
20052 let fill; /* index for replicating entries */
20053 let low; /* low bits for current root entry */
20054 let next; /* next available space in table */
20055 let base = null; /* base value table to use */
20056 let base_index = 0;
20057 // var shoextra; /* extra bits table to use */
20058 let end; /* use base and extra for symbol > end */
20059 const count = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
20060 const offs = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
20061 let extra = null;
20062 let extra_index = 0;
20063
20064 let here_bits, here_op, here_val;
20065
20066 /*
20067 Process a set of code lengths to create a canonical Huffman code. The
20068 code lengths are lens[0..codes-1]. Each length corresponds to the
20069 symbols 0..codes-1. The Huffman code is generated by first sorting the
20070 symbols by length from short to long, and retaining the symbol order
20071 for codes with equal lengths. Then the code starts with all zero bits
20072 for the first code of the shortest length, and the codes are integer
20073 increments for the same length, and zeros are appended as the length
20074 increases. For the deflate format, these bits are stored backwards
20075 from their more natural integer increment ordering, and so when the
20076 decoding tables are built in the large loop below, the integer codes
20077 are incremented backwards.
20078
20079 This routine assumes, but does not check, that all of the entries in
20080 lens[] are in the range 0..MAXBITS. The caller must assure this.
20081 1..MAXBITS is interpreted as that code length. zero means that that
20082 symbol does not occur in this code.
20083
20084 The codes are sorted by computing a count of codes for each length,
20085 creating from that a table of starting indices for each length in the
20086 sorted table, and then entering the symbols in order in the sorted
20087 table. The sorted table is work[], with that space being provided by
20088 the caller.
20089
20090 The length counts are used for other purposes as well, i.e. finding
20091 the minimum and maximum length codes, determining if there are any
20092 codes at all, checking for a valid set of lengths, and looking ahead
20093 at length counts to determine sub-table sizes when building the
20094 decoding tables.
20095 */
20096
20097 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
20098 for (len = 0; len <= MAXBITS; len++) {
20099 count[len] = 0;
20100 }
20101 for (sym = 0; sym < codes; sym++) {
20102 count[lens[lens_index + sym]]++;
20103 }
20104
20105 /* bound code lengths, force root to be within code lengths */
20106 root = bits;
20107 for (max = MAXBITS; max >= 1; max--) {
20108 if (count[max] !== 0) {
20109 break;
20110 }
20111 }
20112 if (root > max) {
20113 root = max;
20114 }
20115 if (max === 0) { /* no symbols to code at all */
20116 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
20117 //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
20118 //table.val[opts.table_index++] = 0; //here.val = (var short)0;
20119 table[table_index++] = 1 << 24 | 64 << 16 | 0;
20120
20121
20122 //table.op[opts.table_index] = 64;
20123 //table.bits[opts.table_index] = 1;
20124 //table.val[opts.table_index++] = 0;
20125 table[table_index++] = 1 << 24 | 64 << 16 | 0;
20126
20127 opts.bits = 1;
20128 return 0; /* no symbols, but wait for decoding to report error */
20129 }
20130 for (min = 1; min < max; min++) {
20131 if (count[min] !== 0) {
20132 break;
20133 }
20134 }
20135 if (root < min) {
20136 root = min;
20137 }
20138
20139 /* check for an over-subscribed or incomplete set of lengths */
20140 left = 1;
20141 for (len = 1; len <= MAXBITS; len++) {
20142 left <<= 1;
20143 left -= count[len];
20144 if (left < 0) {
20145 return -1;
20146 } /* over-subscribed */
20147 }
20148 if (left > 0 && (type === CODES || max !== 1)) {
20149 return -1; /* incomplete set */
20150 }
20151
20152 /* generate offsets into symbol table for each length for sorting */
20153 offs[1] = 0;
20154 for (len = 1; len < MAXBITS; len++) {
20155 offs[len + 1] = offs[len] + count[len];
20156 }
20157
20158 /* sort symbols by length, by symbol order within each length */
20159 for (sym = 0; sym < codes; sym++) {
20160 if (lens[lens_index + sym] !== 0) {
20161 work[offs[lens[lens_index + sym]]++] = sym;
20162 }
20163 }
20164
20165 /*
20166 Create and fill in decoding tables. In this loop, the table being
20167 filled is at next and has curr index bits. The code being used is huff
20168 with length len. That code is converted to an index by dropping drop
20169 bits off of the bottom. For codes where len is less than drop + curr,
20170 those top drop + curr - len bits are incremented through all values to
20171 fill the table with replicated entries.
20172
20173 root is the number of index bits for the root table. When len exceeds
20174 root, sub-tables are created pointed to by the root entry with an index
20175 of the low root bits of huff. This is saved in low to check for when a
20176 new sub-table should be started. drop is zero when the root table is
20177 being filled, and drop is root when sub-tables are being filled.
20178
20179 When a new sub-table is needed, it is necessary to look ahead in the
20180 code lengths to determine what size sub-table is needed. The length
20181 counts are used for this, and so count[] is decremented as codes are
20182 entered in the tables.
20183
20184 used keeps track of how many table entries have been allocated from the
20185 provided *table space. It is checked for LENS and DIST tables against
20186 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
20187 the initial root table size constants. See the comments in inftrees.h
20188 for more information.
20189
20190 sym increments through all symbols, and the loop terminates when
20191 all codes of length max, i.e. all codes, have been processed. This
20192 routine permits incomplete codes, so another loop after this one fills
20193 in the rest of the decoding tables with invalid code markers.
20194 */
20195
20196 /* set up for code type */
20197 // poor man optimization - use if-else instead of switch,
20198 // to avoid deopts in old v8
20199 if (type === CODES) {
20200 base = extra = work; /* dummy value--not used */
20201 end = 19;
20202
20203 } else if (type === LENS) {
20204 base = lbase;
20205 base_index -= 257;
20206 extra = lext;
20207 extra_index -= 257;
20208 end = 256;
20209
20210 } else { /* DISTS */
20211 base = dbase;
20212 extra = dext;
20213 end = -1;
20214 }
20215
20216 /* initialize opts for loop */
20217 huff = 0; /* starting code */
20218 sym = 0; /* starting code symbol */
20219 len = min; /* starting code length */
20220 next = table_index; /* current table to fill in */
20221 curr = root; /* current table index bits */
20222 drop = 0; /* current bits to drop from code for index */
20223 low = -1; /* trigger new sub-table when len > root */
20224 used = 1 << root; /* use root table entries */
20225 const mask = used - 1; /* mask for comparing low */
20226
20227 /* check available table space */
20228 if (type === LENS && used > ENOUGH_LENS ||
20229 type === DISTS && used > ENOUGH_DISTS) {
20230 return 1;
20231 }
20232
20233 /* process all codes and make table entries */
20234 for (;;) {
20235 /* create table entry */
20236 here_bits = len - drop;
20237 if (work[sym] < end) {
20238 here_op = 0;
20239 here_val = work[sym];
20240 } else if (work[sym] > end) {
20241 here_op = extra[extra_index + work[sym]];
20242 here_val = base[base_index + work[sym]];
20243 } else {
20244 here_op = 32 + 64; /* end of block */
20245 here_val = 0;
20246 }
20247
20248 /* replicate for those indices with low len bits equal to huff */
20249 incr = 1 << len - drop;
20250 fill = 1 << curr;
20251 min = fill; /* save offset to next table */
20252 do {
20253 fill -= incr;
20254 table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0;
20255 } while (fill !== 0);
20256
20257 /* backwards increment the len-bit code huff */
20258 incr = 1 << len - 1;
20259 while (huff & incr) {
20260 incr >>= 1;
20261 }
20262 if (incr !== 0) {
20263 huff &= incr - 1;
20264 huff += incr;
20265 } else {
20266 huff = 0;
20267 }
20268
20269 /* go to next symbol, update count, len */
20270 sym++;
20271 if (--count[len] === 0) {
20272 if (len === max) {
20273 break;
20274 }
20275 len = lens[lens_index + work[sym]];
20276 }
20277
20278 /* create new sub-table if needed */
20279 if (len > root && (huff & mask) !== low) {
20280 /* if first time, transition to sub-tables */
20281 if (drop === 0) {
20282 drop = root;
20283 }
20284
20285 /* increment past last table */
20286 next += min; /* here min is 1 << curr */
20287
20288 /* determine length of next table */
20289 curr = len - drop;
20290 left = 1 << curr;
20291 while (curr + drop < max) {
20292 left -= count[curr + drop];
20293 if (left <= 0) {
20294 break;
20295 }
20296 curr++;
20297 left <<= 1;
20298 }
20299
20300 /* check for enough space */
20301 used += 1 << curr;
20302 if (type === LENS && used > ENOUGH_LENS ||
20303 type === DISTS && used > ENOUGH_DISTS) {
20304 return 1;
20305 }
20306
20307 /* point entry in root table to sub-table */
20308 low = huff & mask;
20309 /*table.op[low] = curr;
20310 table.bits[low] = root;
20311 table.val[low] = next - opts.table_index;*/
20312 table[low] = root << 24 | curr << 16 | next - table_index |0;
20313 }
20314 }
20315
20316 /* fill in remaining table entry if code is incomplete (guaranteed to have
20317 at most one remaining entry, since if the code is incomplete, the
20318 maximum code length that was allowed to get this far is one bit) */
20319 if (huff !== 0) {
20320 //table.op[next + huff] = 64; /* invalid code marker */
20321 //table.bits[next + huff] = len - drop;
20322 //table.val[next + huff] = 0;
20323 table[next + huff] = len - drop << 24 | 64 << 16 |0;
20324 }
20325
20326 /* set return parameters */
20327 //opts.table_index += used;
20328 opts.bits = root;
20329 return 0;
20330}
20331
20332const CODES$1 = 0;
20333const LENS$1 = 1;
20334const DISTS$1 = 2;
20335
20336/* STATES ====================================================================*/
20337/* ===========================================================================*/
20338
20339
20340const HEAD = 1; /* i: waiting for magic header */
20341const FLAGS = 2; /* i: waiting for method and flags (gzip) */
20342const TIME = 3; /* i: waiting for modification time (gzip) */
20343const OS = 4; /* i: waiting for extra flags and operating system (gzip) */
20344const EXLEN = 5; /* i: waiting for extra length (gzip) */
20345const EXTRA = 6; /* i: waiting for extra bytes (gzip) */
20346const NAME = 7; /* i: waiting for end of file name (gzip) */
20347const COMMENT = 8; /* i: waiting for end of comment (gzip) */
20348const HCRC = 9; /* i: waiting for header crc (gzip) */
20349const DICTID = 10; /* i: waiting for dictionary check value */
20350const DICT = 11; /* waiting for inflateSetDictionary() call */
20351const TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */
20352const TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
20353const STORED = 14; /* i: waiting for stored size (length and complement) */
20354const COPY_ = 15; /* i/o: same as COPY below, but only first time in */
20355const COPY = 16; /* i/o: waiting for input or output to copy stored block */
20356const TABLE = 17; /* i: waiting for dynamic block table lengths */
20357const LENLENS = 18; /* i: waiting for code length code lengths */
20358const CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
20359const LEN_ = 20; /* i: same as LEN below, but only first time in */
20360const LEN = 21; /* i: waiting for length/lit/eob code */
20361const LENEXT = 22; /* i: waiting for length extra bits */
20362const DIST = 23; /* i: waiting for distance code */
20363const DISTEXT = 24; /* i: waiting for distance extra bits */
20364const MATCH = 25; /* o: waiting for output space to copy string */
20365const LIT = 26; /* o: waiting for output space to write literal */
20366const CHECK = 27; /* i: waiting for 32-bit check value */
20367const LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
20368const DONE = 29; /* finished check, done -- remain here until reset */
20369const BAD$1 = 30; /* got a data error -- remain here until reset */
20370//const MEM = 31; /* got an inflate() memory error -- remain here until reset */
20371const SYNC = 32; /* looking for synchronization bytes to restart inflate() */
20372
20373/* ===========================================================================*/
20374
20375
20376
20377const ENOUGH_LENS$1 = 852;
20378const ENOUGH_DISTS$1 = 592;
20379
20380
20381function zswap32(q) {
20382 return (((q >>> 24) & 0xff) +
20383 ((q >>> 8) & 0xff00) +
20384 ((q & 0xff00) << 8) +
20385 ((q & 0xff) << 24));
20386}
20387
20388
20389class InflateState {
20390 constructor() {
20391 this.mode = 0; /* current inflate mode */
20392 this.last = false; /* true if processing last block */
20393 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
20394 this.havedict = false; /* true if dictionary provided */
20395 this.flags = 0; /* gzip header method and flags (0 if zlib) */
20396 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
20397 this.check = 0; /* protected copy of check value */
20398 this.total = 0; /* protected copy of output count */
20399 // TODO: may be {}
20400 this.head = null; /* where to save gzip header information */
20401
20402 /* sliding window */
20403 this.wbits = 0; /* log base 2 of requested window size */
20404 this.wsize = 0; /* window size or zero if not using window */
20405 this.whave = 0; /* valid bytes in the window */
20406 this.wnext = 0; /* window write index */
20407 this.window = null; /* allocated sliding window, if needed */
20408
20409 /* bit accumulator */
20410 this.hold = 0; /* input bit accumulator */
20411 this.bits = 0; /* number of bits in "in" */
20412
20413 /* for string and stored block copying */
20414 this.length = 0; /* literal or length of data to copy */
20415 this.offset = 0; /* distance back to copy string from */
20416
20417 /* for table and code decoding */
20418 this.extra = 0; /* extra bits needed */
20419
20420 /* fixed and dynamic code tables */
20421 this.lencode = null; /* starting table for length/literal codes */
20422 this.distcode = null; /* starting table for distance codes */
20423 this.lenbits = 0; /* index bits for lencode */
20424 this.distbits = 0; /* index bits for distcode */
20425
20426 /* dynamic table building */
20427 this.ncode = 0; /* number of code length code lengths */
20428 this.nlen = 0; /* number of length code lengths */
20429 this.ndist = 0; /* number of distance code lengths */
20430 this.have = 0; /* number of code lengths in lens[] */
20431 this.next = null; /* next available space in codes[] */
20432
20433 this.lens = new Buf16(320); /* temporary storage for code lengths */
20434 this.work = new Buf16(288); /* work area for code table building */
20435
20436 /*
20437 because we don't have pointers in js, we use lencode and distcode directly
20438 as buffers so we don't need codes
20439 */
20440 //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
20441 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
20442 this.distdyn = null; /* dynamic table for distance codes (JS specific) */
20443 this.sane = 0; /* if false, allow invalid distance too far */
20444 this.back = 0; /* bits back of last unprocessed length/lit */
20445 this.was = 0; /* initial length of match */
20446 }
20447}
20448
20449function inflateResetKeep(strm) {
20450 let state;
20451
20452 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
20453 state = strm.state;
20454 strm.total_in = strm.total_out = state.total = 0;
20455 strm.msg = ''; /*Z_NULL*/
20456 if (state.wrap) { /* to support ill-conceived Java test suite */
20457 strm.adler = state.wrap & 1;
20458 }
20459 state.mode = HEAD;
20460 state.last = 0;
20461 state.havedict = 0;
20462 state.dmax = 32768;
20463 state.head = null/*Z_NULL*/;
20464 state.hold = 0;
20465 state.bits = 0;
20466 //state.lencode = state.distcode = state.next = state.codes;
20467 state.lencode = state.lendyn = new Buf32(ENOUGH_LENS$1);
20468 state.distcode = state.distdyn = new Buf32(ENOUGH_DISTS$1);
20469
20470 state.sane = 1;
20471 state.back = -1;
20472 //Tracev((stderr, "inflate: reset\n"));
20473 return Z_OK;
20474}
20475
20476function inflateReset(strm) {
20477 let state;
20478
20479 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
20480 state = strm.state;
20481 state.wsize = 0;
20482 state.whave = 0;
20483 state.wnext = 0;
20484 return inflateResetKeep(strm);
20485
20486}
20487
20488function inflateReset2(strm, windowBits) {
20489 let wrap;
20490 let state;
20491
20492 /* get the state */
20493 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
20494 state = strm.state;
20495
20496 /* extract wrap request from windowBits parameter */
20497 if (windowBits < 0) {
20498 wrap = 0;
20499 windowBits = -windowBits;
20500 }
20501 else {
20502 wrap = (windowBits >> 4) + 1;
20503 if (windowBits < 48) {
20504 windowBits &= 15;
20505 }
20506 }
20507
20508 /* set number of window bits, free window if different */
20509 if (windowBits && (windowBits < 8 || windowBits > 15)) {
20510 return Z_STREAM_ERROR;
20511 }
20512 if (state.window !== null && state.wbits !== windowBits) {
20513 state.window = null;
20514 }
20515
20516 /* update state and reset the rest of it */
20517 state.wrap = wrap;
20518 state.wbits = windowBits;
20519 return inflateReset(strm);
20520}
20521
20522function inflateInit2(strm, windowBits) {
20523 let ret;
20524 let state;
20525
20526 if (!strm) { return Z_STREAM_ERROR; }
20527 //strm.msg = Z_NULL; /* in case we return an error */
20528
20529 state = new InflateState();
20530
20531 //if (state === Z_NULL) return Z_MEM_ERROR;
20532 //Tracev((stderr, "inflate: allocated\n"));
20533 strm.state = state;
20534 state.window = null/*Z_NULL*/;
20535 ret = inflateReset2(strm, windowBits);
20536 if (ret !== Z_OK) {
20537 strm.state = null/*Z_NULL*/;
20538 }
20539 return ret;
20540}
20541
20542
20543/*
20544 Return state with length and distance decoding tables and index sizes set to
20545 fixed code decoding. Normally this returns fixed tables from inffixed.h.
20546 If BUILDFIXED is defined, then instead this routine builds the tables the
20547 first time it's called, and returns those tables the first time and
20548 thereafter. This reduces the size of the code by about 2K bytes, in
20549 exchange for a little execution time. However, BUILDFIXED should not be
20550 used for threaded applications, since the rewriting of the tables and virgin
20551 may not be thread-safe.
20552 */
20553let virgin = true;
20554
20555let lenfix, distfix; // We have no pointers in JS, so keep tables separate
20556
20557function fixedtables(state) {
20558 /* build fixed huffman tables if first call (may not be thread safe) */
20559 if (virgin) {
20560 let sym;
20561
20562 lenfix = new Buf32(512);
20563 distfix = new Buf32(32);
20564
20565 /* literal/length table */
20566 sym = 0;
20567 while (sym < 144) { state.lens[sym++] = 8; }
20568 while (sym < 256) { state.lens[sym++] = 9; }
20569 while (sym < 280) { state.lens[sym++] = 7; }
20570 while (sym < 288) { state.lens[sym++] = 8; }
20571
20572 inflate_table(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
20573
20574 /* distance table */
20575 sym = 0;
20576 while (sym < 32) { state.lens[sym++] = 5; }
20577
20578 inflate_table(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
20579
20580 /* do this just once */
20581 virgin = false;
20582 }
20583
20584 state.lencode = lenfix;
20585 state.lenbits = 9;
20586 state.distcode = distfix;
20587 state.distbits = 5;
20588}
20589
20590
20591/*
20592 Update the window with the last wsize (normally 32K) bytes written before
20593 returning. If window does not exist yet, create it. This is only called
20594 when a window is already in use, or when output has been written during this
20595 inflate call, but the end of the deflate stream has not been reached yet.
20596 It is also called to create a window for dictionary data when a dictionary
20597 is loaded.
20598
20599 Providing output buffers larger than 32K to inflate() should provide a speed
20600 advantage, since only the last 32K of output is copied to the sliding window
20601 upon return from inflate(), and since all distances after the first 32K of
20602 output will fall in the output data, making match copies simpler and faster.
20603 The advantage may be dependent on the size of the processor's data caches.
20604 */
20605function updatewindow(strm, src, end, copy) {
20606 let dist;
20607 const state = strm.state;
20608
20609 /* if it hasn't been done already, allocate space for the window */
20610 if (state.window === null) {
20611 state.wsize = 1 << state.wbits;
20612 state.wnext = 0;
20613 state.whave = 0;
20614
20615 state.window = new Buf8(state.wsize);
20616 }
20617
20618 /* copy state->wsize or less output bytes into the circular window */
20619 if (copy >= state.wsize) {
20620 arraySet(state.window, src, end - state.wsize, state.wsize, 0);
20621 state.wnext = 0;
20622 state.whave = state.wsize;
20623 }
20624 else {
20625 dist = state.wsize - state.wnext;
20626 if (dist > copy) {
20627 dist = copy;
20628 }
20629 //zmemcpy(state->window + state->wnext, end - copy, dist);
20630 arraySet(state.window, src, end - copy, dist, state.wnext);
20631 copy -= dist;
20632 if (copy) {
20633 //zmemcpy(state->window, end - copy, copy);
20634 arraySet(state.window, src, end - copy, copy, 0);
20635 state.wnext = copy;
20636 state.whave = state.wsize;
20637 }
20638 else {
20639 state.wnext += dist;
20640 if (state.wnext === state.wsize) { state.wnext = 0; }
20641 if (state.whave < state.wsize) { state.whave += dist; }
20642 }
20643 }
20644 return 0;
20645}
20646
20647function inflate(strm, flush) {
20648 let state;
20649 let input, output; // input/output buffers
20650 let next; /* next input INDEX */
20651 let put; /* next output INDEX */
20652 let have, left; /* available input and output */
20653 let hold; /* bit buffer */
20654 let bits; /* bits in bit buffer */
20655 let _in, _out; /* save starting available input and output */
20656 let copy; /* number of stored or match bytes to copy */
20657 let from; /* where to copy match bytes from */
20658 let from_source;
20659 let here = 0; /* current decoding table entry */
20660 let here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
20661 //var last; /* parent table entry */
20662 let last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
20663 let len; /* length to copy for repeats, bits to drop */
20664 let ret; /* return code */
20665 let hbuf = new Buf8(4); /* buffer for gzip header crc calculation */
20666 let opts;
20667
20668 let n; // temporary var for NEED_BITS
20669
20670 const order = /* permutation of code lengths */
20671 [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
20672
20673
20674 if (!strm || !strm.state || !strm.output ||
20675 (!strm.input && strm.avail_in !== 0)) {
20676 return Z_STREAM_ERROR;
20677 }
20678
20679 state = strm.state;
20680 if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */
20681
20682
20683 //--- LOAD() ---
20684 put = strm.next_out;
20685 output = strm.output;
20686 left = strm.avail_out;
20687 next = strm.next_in;
20688 input = strm.input;
20689 have = strm.avail_in;
20690 hold = state.hold;
20691 bits = state.bits;
20692 //---
20693
20694 _in = have;
20695 _out = left;
20696 ret = Z_OK;
20697
20698 inf_leave: // goto emulation
20699 for (;;) {
20700 switch (state.mode) {
20701 case HEAD:
20702 if (state.wrap === 0) {
20703 state.mode = TYPEDO;
20704 break;
20705 }
20706 //=== NEEDBITS(16);
20707 while (bits < 16) {
20708 if (have === 0) { break inf_leave; }
20709 have--;
20710 hold += input[next++] << bits;
20711 bits += 8;
20712 }
20713 //===//
20714 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
20715 state.check = 0/*crc32(0L, Z_NULL, 0)*/;
20716 //=== CRC2(state.check, hold);
20717 hbuf[0] = hold & 0xff;
20718 hbuf[1] = (hold >>> 8) & 0xff;
20719 state.check = crc32(state.check, hbuf, 2, 0);
20720 //===//
20721
20722 //=== INITBITS();
20723 hold = 0;
20724 bits = 0;
20725 //===//
20726 state.mode = FLAGS;
20727 break;
20728 }
20729 state.flags = 0; /* expect zlib header */
20730 if (state.head) {
20731 state.head.done = false;
20732 }
20733 if (!(state.wrap & 1) || /* check if zlib header allowed */
20734 (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
20735 strm.msg = 'incorrect header check';
20736 state.mode = BAD$1;
20737 break;
20738 }
20739 if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
20740 strm.msg = 'unknown compression method';
20741 state.mode = BAD$1;
20742 break;
20743 }
20744 //--- DROPBITS(4) ---//
20745 hold >>>= 4;
20746 bits -= 4;
20747 //---//
20748 len = (hold & 0x0f)/*BITS(4)*/ + 8;
20749 if (state.wbits === 0) {
20750 state.wbits = len;
20751 }
20752 else if (len > state.wbits) {
20753 strm.msg = 'invalid window size';
20754 state.mode = BAD$1;
20755 break;
20756 }
20757 state.dmax = 1 << len;
20758 //Tracev((stderr, "inflate: zlib header ok\n"));
20759 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
20760 state.mode = hold & 0x200 ? DICTID : TYPE$1;
20761 //=== INITBITS();
20762 hold = 0;
20763 bits = 0;
20764 //===//
20765 break;
20766 case FLAGS:
20767 //=== NEEDBITS(16); */
20768 while (bits < 16) {
20769 if (have === 0) { break inf_leave; }
20770 have--;
20771 hold += input[next++] << bits;
20772 bits += 8;
20773 }
20774 //===//
20775 state.flags = hold;
20776 if ((state.flags & 0xff) !== Z_DEFLATED) {
20777 strm.msg = 'unknown compression method';
20778 state.mode = BAD$1;
20779 break;
20780 }
20781 if (state.flags & 0xe000) {
20782 strm.msg = 'unknown header flags set';
20783 state.mode = BAD$1;
20784 break;
20785 }
20786 if (state.head) {
20787 state.head.text = ((hold >> 8) & 1);
20788 }
20789 if (state.flags & 0x0200) {
20790 //=== CRC2(state.check, hold);
20791 hbuf[0] = hold & 0xff;
20792 hbuf[1] = (hold >>> 8) & 0xff;
20793 state.check = crc32(state.check, hbuf, 2, 0);
20794 //===//
20795 }
20796 //=== INITBITS();
20797 hold = 0;
20798 bits = 0;
20799 //===//
20800 state.mode = TIME;
20801 /* falls through */
20802 case TIME:
20803 //=== NEEDBITS(32); */
20804 while (bits < 32) {
20805 if (have === 0) { break inf_leave; }
20806 have--;
20807 hold += input[next++] << bits;
20808 bits += 8;
20809 }
20810 //===//
20811 if (state.head) {
20812 state.head.time = hold;
20813 }
20814 if (state.flags & 0x0200) {
20815 //=== CRC4(state.check, hold)
20816 hbuf[0] = hold & 0xff;
20817 hbuf[1] = (hold >>> 8) & 0xff;
20818 hbuf[2] = (hold >>> 16) & 0xff;
20819 hbuf[3] = (hold >>> 24) & 0xff;
20820 state.check = crc32(state.check, hbuf, 4, 0);
20821 //===
20822 }
20823 //=== INITBITS();
20824 hold = 0;
20825 bits = 0;
20826 //===//
20827 state.mode = OS;
20828 /* falls through */
20829 case OS:
20830 //=== NEEDBITS(16); */
20831 while (bits < 16) {
20832 if (have === 0) { break inf_leave; }
20833 have--;
20834 hold += input[next++] << bits;
20835 bits += 8;
20836 }
20837 //===//
20838 if (state.head) {
20839 state.head.xflags = (hold & 0xff);
20840 state.head.os = (hold >> 8);
20841 }
20842 if (state.flags & 0x0200) {
20843 //=== CRC2(state.check, hold);
20844 hbuf[0] = hold & 0xff;
20845 hbuf[1] = (hold >>> 8) & 0xff;
20846 state.check = crc32(state.check, hbuf, 2, 0);
20847 //===//
20848 }
20849 //=== INITBITS();
20850 hold = 0;
20851 bits = 0;
20852 //===//
20853 state.mode = EXLEN;
20854 /* falls through */
20855 case EXLEN:
20856 if (state.flags & 0x0400) {
20857 //=== NEEDBITS(16); */
20858 while (bits < 16) {
20859 if (have === 0) { break inf_leave; }
20860 have--;
20861 hold += input[next++] << bits;
20862 bits += 8;
20863 }
20864 //===//
20865 state.length = hold;
20866 if (state.head) {
20867 state.head.extra_len = hold;
20868 }
20869 if (state.flags & 0x0200) {
20870 //=== CRC2(state.check, hold);
20871 hbuf[0] = hold & 0xff;
20872 hbuf[1] = (hold >>> 8) & 0xff;
20873 state.check = crc32(state.check, hbuf, 2, 0);
20874 //===//
20875 }
20876 //=== INITBITS();
20877 hold = 0;
20878 bits = 0;
20879 //===//
20880 }
20881 else if (state.head) {
20882 state.head.extra = null/*Z_NULL*/;
20883 }
20884 state.mode = EXTRA;
20885 /* falls through */
20886 case EXTRA:
20887 if (state.flags & 0x0400) {
20888 copy = state.length;
20889 if (copy > have) { copy = have; }
20890 if (copy) {
20891 if (state.head) {
20892 len = state.head.extra_len - state.length;
20893 if (!state.head.extra) {
20894 // Use untyped array for more convenient processing later
20895 state.head.extra = new Array(state.head.extra_len);
20896 }
20897 arraySet(
20898 state.head.extra,
20899 input,
20900 next,
20901 // extra field is limited to 65536 bytes
20902 // - no need for additional size check
20903 copy,
20904 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
20905 len
20906 );
20907 //zmemcpy(state.head.extra + len, next,
20908 // len + copy > state.head.extra_max ?
20909 // state.head.extra_max - len : copy);
20910 }
20911 if (state.flags & 0x0200) {
20912 state.check = crc32(state.check, input, copy, next);
20913 }
20914 have -= copy;
20915 next += copy;
20916 state.length -= copy;
20917 }
20918 if (state.length) { break inf_leave; }
20919 }
20920 state.length = 0;
20921 state.mode = NAME;
20922 /* falls through */
20923 case NAME:
20924 if (state.flags & 0x0800) {
20925 if (have === 0) { break inf_leave; }
20926 copy = 0;
20927 do {
20928 // TODO: 2 or 1 bytes?
20929 len = input[next + copy++];
20930 /* use constant limit because in js we should not preallocate memory */
20931 if (state.head && len &&
20932 (state.length < 65536 /*state.head.name_max*/)) {
20933 state.head.name += String.fromCharCode(len);
20934 }
20935 } while (len && copy < have);
20936
20937 if (state.flags & 0x0200) {
20938 state.check = crc32(state.check, input, copy, next);
20939 }
20940 have -= copy;
20941 next += copy;
20942 if (len) { break inf_leave; }
20943 }
20944 else if (state.head) {
20945 state.head.name = null;
20946 }
20947 state.length = 0;
20948 state.mode = COMMENT;
20949 /* falls through */
20950 case COMMENT:
20951 if (state.flags & 0x1000) {
20952 if (have === 0) { break inf_leave; }
20953 copy = 0;
20954 do {
20955 len = input[next + copy++];
20956 /* use constant limit because in js we should not preallocate memory */
20957 if (state.head && len &&
20958 (state.length < 65536 /*state.head.comm_max*/)) {
20959 state.head.comment += String.fromCharCode(len);
20960 }
20961 } while (len && copy < have);
20962 if (state.flags & 0x0200) {
20963 state.check = crc32(state.check, input, copy, next);
20964 }
20965 have -= copy;
20966 next += copy;
20967 if (len) { break inf_leave; }
20968 }
20969 else if (state.head) {
20970 state.head.comment = null;
20971 }
20972 state.mode = HCRC;
20973 /* falls through */
20974 case HCRC:
20975 if (state.flags & 0x0200) {
20976 //=== NEEDBITS(16); */
20977 while (bits < 16) {
20978 if (have === 0) { break inf_leave; }
20979 have--;
20980 hold += input[next++] << bits;
20981 bits += 8;
20982 }
20983 //===//
20984 if (hold !== (state.check & 0xffff)) {
20985 strm.msg = 'header crc mismatch';
20986 state.mode = BAD$1;
20987 break;
20988 }
20989 //=== INITBITS();
20990 hold = 0;
20991 bits = 0;
20992 //===//
20993 }
20994 if (state.head) {
20995 state.head.hcrc = ((state.flags >> 9) & 1);
20996 state.head.done = true;
20997 }
20998 strm.adler = state.check = 0;
20999 state.mode = TYPE$1;
21000 break;
21001 case DICTID:
21002 //=== NEEDBITS(32); */
21003 while (bits < 32) {
21004 if (have === 0) { break inf_leave; }
21005 have--;
21006 hold += input[next++] << bits;
21007 bits += 8;
21008 }
21009 //===//
21010 strm.adler = state.check = zswap32(hold);
21011 //=== INITBITS();
21012 hold = 0;
21013 bits = 0;
21014 //===//
21015 state.mode = DICT;
21016 /* falls through */
21017 case DICT:
21018 if (state.havedict === 0) {
21019 //--- RESTORE() ---
21020 strm.next_out = put;
21021 strm.avail_out = left;
21022 strm.next_in = next;
21023 strm.avail_in = have;
21024 state.hold = hold;
21025 state.bits = bits;
21026 //---
21027 return Z_NEED_DICT;
21028 }
21029 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
21030 state.mode = TYPE$1;
21031 /* falls through */
21032 case TYPE$1:
21033 if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
21034 /* falls through */
21035 case TYPEDO:
21036 if (state.last) {
21037 //--- BYTEBITS() ---//
21038 hold >>>= bits & 7;
21039 bits -= bits & 7;
21040 //---//
21041 state.mode = CHECK;
21042 break;
21043 }
21044 //=== NEEDBITS(3); */
21045 while (bits < 3) {
21046 if (have === 0) { break inf_leave; }
21047 have--;
21048 hold += input[next++] << bits;
21049 bits += 8;
21050 }
21051 //===//
21052 state.last = (hold & 0x01)/*BITS(1)*/;
21053 //--- DROPBITS(1) ---//
21054 hold >>>= 1;
21055 bits -= 1;
21056 //---//
21057
21058 switch ((hold & 0x03)/*BITS(2)*/) {
21059 case 0: /* stored block */
21060 //Tracev((stderr, "inflate: stored block%s\n",
21061 // state.last ? " (last)" : ""));
21062 state.mode = STORED;
21063 break;
21064 case 1: /* fixed block */
21065 fixedtables(state);
21066 //Tracev((stderr, "inflate: fixed codes block%s\n",
21067 // state.last ? " (last)" : ""));
21068 state.mode = LEN_; /* decode codes */
21069 if (flush === Z_TREES) {
21070 //--- DROPBITS(2) ---//
21071 hold >>>= 2;
21072 bits -= 2;
21073 //---//
21074 break inf_leave;
21075 }
21076 break;
21077 case 2: /* dynamic block */
21078 //Tracev((stderr, "inflate: dynamic codes block%s\n",
21079 // state.last ? " (last)" : ""));
21080 state.mode = TABLE;
21081 break;
21082 case 3:
21083 strm.msg = 'invalid block type';
21084 state.mode = BAD$1;
21085 }
21086 //--- DROPBITS(2) ---//
21087 hold >>>= 2;
21088 bits -= 2;
21089 //---//
21090 break;
21091 case STORED:
21092 //--- BYTEBITS() ---// /* go to byte boundary */
21093 hold >>>= bits & 7;
21094 bits -= bits & 7;
21095 //---//
21096 //=== NEEDBITS(32); */
21097 while (bits < 32) {
21098 if (have === 0) { break inf_leave; }
21099 have--;
21100 hold += input[next++] << bits;
21101 bits += 8;
21102 }
21103 //===//
21104 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
21105 strm.msg = 'invalid stored block lengths';
21106 state.mode = BAD$1;
21107 break;
21108 }
21109 state.length = hold & 0xffff;
21110 //Tracev((stderr, "inflate: stored length %u\n",
21111 // state.length));
21112 //=== INITBITS();
21113 hold = 0;
21114 bits = 0;
21115 //===//
21116 state.mode = COPY_;
21117 if (flush === Z_TREES) { break inf_leave; }
21118 /* falls through */
21119 case COPY_:
21120 state.mode = COPY;
21121 /* falls through */
21122 case COPY:
21123 copy = state.length;
21124 if (copy) {
21125 if (copy > have) { copy = have; }
21126 if (copy > left) { copy = left; }
21127 if (copy === 0) { break inf_leave; }
21128 //--- zmemcpy(put, next, copy); ---
21129 arraySet(output, input, next, copy, put);
21130 //---//
21131 have -= copy;
21132 next += copy;
21133 left -= copy;
21134 put += copy;
21135 state.length -= copy;
21136 break;
21137 }
21138 //Tracev((stderr, "inflate: stored end\n"));
21139 state.mode = TYPE$1;
21140 break;
21141 case TABLE:
21142 //=== NEEDBITS(14); */
21143 while (bits < 14) {
21144 if (have === 0) { break inf_leave; }
21145 have--;
21146 hold += input[next++] << bits;
21147 bits += 8;
21148 }
21149 //===//
21150 state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
21151 //--- DROPBITS(5) ---//
21152 hold >>>= 5;
21153 bits -= 5;
21154 //---//
21155 state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
21156 //--- DROPBITS(5) ---//
21157 hold >>>= 5;
21158 bits -= 5;
21159 //---//
21160 state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
21161 //--- DROPBITS(4) ---//
21162 hold >>>= 4;
21163 bits -= 4;
21164 //---//
21165//#ifndef PKZIP_BUG_WORKAROUND
21166 if (state.nlen > 286 || state.ndist > 30) {
21167 strm.msg = 'too many length or distance symbols';
21168 state.mode = BAD$1;
21169 break;
21170 }
21171//#endif
21172 //Tracev((stderr, "inflate: table sizes ok\n"));
21173 state.have = 0;
21174 state.mode = LENLENS;
21175 /* falls through */
21176 case LENLENS:
21177 while (state.have < state.ncode) {
21178 //=== NEEDBITS(3);
21179 while (bits < 3) {
21180 if (have === 0) { break inf_leave; }
21181 have--;
21182 hold += input[next++] << bits;
21183 bits += 8;
21184 }
21185 //===//
21186 state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
21187 //--- DROPBITS(3) ---//
21188 hold >>>= 3;
21189 bits -= 3;
21190 //---//
21191 }
21192 while (state.have < 19) {
21193 state.lens[order[state.have++]] = 0;
21194 }
21195 // We have separate tables & no pointers. 2 commented lines below not needed.
21196 //state.next = state.codes;
21197 //state.lencode = state.next;
21198 // Switch to use dynamic table
21199 state.lencode = state.lendyn;
21200 state.lenbits = 7;
21201
21202 opts = { bits: state.lenbits };
21203 ret = inflate_table(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts);
21204 state.lenbits = opts.bits;
21205
21206 if (ret) {
21207 strm.msg = 'invalid code lengths set';
21208 state.mode = BAD$1;
21209 break;
21210 }
21211 //Tracev((stderr, "inflate: code lengths ok\n"));
21212 state.have = 0;
21213 state.mode = CODELENS;
21214 /* falls through */
21215 case CODELENS:
21216 while (state.have < state.nlen + state.ndist) {
21217 for (;;) {
21218 here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
21219 here_bits = here >>> 24;
21220 here_op = (here >>> 16) & 0xff;
21221 here_val = here & 0xffff;
21222
21223 if ((here_bits) <= bits) { break; }
21224 //--- PULLBYTE() ---//
21225 if (have === 0) { break inf_leave; }
21226 have--;
21227 hold += input[next++] << bits;
21228 bits += 8;
21229 //---//
21230 }
21231 if (here_val < 16) {
21232 //--- DROPBITS(here.bits) ---//
21233 hold >>>= here_bits;
21234 bits -= here_bits;
21235 //---//
21236 state.lens[state.have++] = here_val;
21237 }
21238 else {
21239 if (here_val === 16) {
21240 //=== NEEDBITS(here.bits + 2);
21241 n = here_bits + 2;
21242 while (bits < n) {
21243 if (have === 0) { break inf_leave; }
21244 have--;
21245 hold += input[next++] << bits;
21246 bits += 8;
21247 }
21248 //===//
21249 //--- DROPBITS(here.bits) ---//
21250 hold >>>= here_bits;
21251 bits -= here_bits;
21252 //---//
21253 if (state.have === 0) {
21254 strm.msg = 'invalid bit length repeat';
21255 state.mode = BAD$1;
21256 break;
21257 }
21258 len = state.lens[state.have - 1];
21259 copy = 3 + (hold & 0x03);//BITS(2);
21260 //--- DROPBITS(2) ---//
21261 hold >>>= 2;
21262 bits -= 2;
21263 //---//
21264 }
21265 else if (here_val === 17) {
21266 //=== NEEDBITS(here.bits + 3);
21267 n = here_bits + 3;
21268 while (bits < n) {
21269 if (have === 0) { break inf_leave; }
21270 have--;
21271 hold += input[next++] << bits;
21272 bits += 8;
21273 }
21274 //===//
21275 //--- DROPBITS(here.bits) ---//
21276 hold >>>= here_bits;
21277 bits -= here_bits;
21278 //---//
21279 len = 0;
21280 copy = 3 + (hold & 0x07);//BITS(3);
21281 //--- DROPBITS(3) ---//
21282 hold >>>= 3;
21283 bits -= 3;
21284 //---//
21285 }
21286 else {
21287 //=== NEEDBITS(here.bits + 7);
21288 n = here_bits + 7;
21289 while (bits < n) {
21290 if (have === 0) { break inf_leave; }
21291 have--;
21292 hold += input[next++] << bits;
21293 bits += 8;
21294 }
21295 //===//
21296 //--- DROPBITS(here.bits) ---//
21297 hold >>>= here_bits;
21298 bits -= here_bits;
21299 //---//
21300 len = 0;
21301 copy = 11 + (hold & 0x7f);//BITS(7);
21302 //--- DROPBITS(7) ---//
21303 hold >>>= 7;
21304 bits -= 7;
21305 //---//
21306 }
21307 if (state.have + copy > state.nlen + state.ndist) {
21308 strm.msg = 'invalid bit length repeat';
21309 state.mode = BAD$1;
21310 break;
21311 }
21312 while (copy--) {
21313 state.lens[state.have++] = len;
21314 }
21315 }
21316 }
21317
21318 /* handle error breaks in while */
21319 if (state.mode === BAD$1) { break; }
21320
21321 /* check for end-of-block code (better have one) */
21322 if (state.lens[256] === 0) {
21323 strm.msg = 'invalid code -- missing end-of-block';
21324 state.mode = BAD$1;
21325 break;
21326 }
21327
21328 /* build code tables -- note: do not change the lenbits or distbits
21329 values here (9 and 6) without reading the comments in inftrees.h
21330 concerning the ENOUGH constants, which depend on those values */
21331 state.lenbits = 9;
21332
21333 opts = { bits: state.lenbits };
21334 ret = inflate_table(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
21335 // We have separate tables & no pointers. 2 commented lines below not needed.
21336 // state.next_index = opts.table_index;
21337 state.lenbits = opts.bits;
21338 // state.lencode = state.next;
21339
21340 if (ret) {
21341 strm.msg = 'invalid literal/lengths set';
21342 state.mode = BAD$1;
21343 break;
21344 }
21345
21346 state.distbits = 6;
21347 //state.distcode.copy(state.codes);
21348 // Switch to use dynamic table
21349 state.distcode = state.distdyn;
21350 opts = { bits: state.distbits };
21351 ret = inflate_table(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
21352 // We have separate tables & no pointers. 2 commented lines below not needed.
21353 // state.next_index = opts.table_index;
21354 state.distbits = opts.bits;
21355 // state.distcode = state.next;
21356
21357 if (ret) {
21358 strm.msg = 'invalid distances set';
21359 state.mode = BAD$1;
21360 break;
21361 }
21362 //Tracev((stderr, 'inflate: codes ok\n'));
21363 state.mode = LEN_;
21364 if (flush === Z_TREES) { break inf_leave; }
21365 /* falls through */
21366 case LEN_:
21367 state.mode = LEN;
21368 /* falls through */
21369 case LEN:
21370 if (have >= 6 && left >= 258) {
21371 //--- RESTORE() ---
21372 strm.next_out = put;
21373 strm.avail_out = left;
21374 strm.next_in = next;
21375 strm.avail_in = have;
21376 state.hold = hold;
21377 state.bits = bits;
21378 //---
21379 inflate_fast(strm, _out);
21380 //--- LOAD() ---
21381 put = strm.next_out;
21382 output = strm.output;
21383 left = strm.avail_out;
21384 next = strm.next_in;
21385 input = strm.input;
21386 have = strm.avail_in;
21387 hold = state.hold;
21388 bits = state.bits;
21389 //---
21390
21391 if (state.mode === TYPE$1) {
21392 state.back = -1;
21393 }
21394 break;
21395 }
21396 state.back = 0;
21397 for (;;) {
21398 here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
21399 here_bits = here >>> 24;
21400 here_op = (here >>> 16) & 0xff;
21401 here_val = here & 0xffff;
21402
21403 if (here_bits <= bits) { break; }
21404 //--- PULLBYTE() ---//
21405 if (have === 0) { break inf_leave; }
21406 have--;
21407 hold += input[next++] << bits;
21408 bits += 8;
21409 //---//
21410 }
21411 if (here_op && (here_op & 0xf0) === 0) {
21412 last_bits = here_bits;
21413 last_op = here_op;
21414 last_val = here_val;
21415 for (;;) {
21416 here = state.lencode[last_val +
21417 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
21418 here_bits = here >>> 24;
21419 here_op = (here >>> 16) & 0xff;
21420 here_val = here & 0xffff;
21421
21422 if ((last_bits + here_bits) <= bits) { break; }
21423 //--- PULLBYTE() ---//
21424 if (have === 0) { break inf_leave; }
21425 have--;
21426 hold += input[next++] << bits;
21427 bits += 8;
21428 //---//
21429 }
21430 //--- DROPBITS(last.bits) ---//
21431 hold >>>= last_bits;
21432 bits -= last_bits;
21433 //---//
21434 state.back += last_bits;
21435 }
21436 //--- DROPBITS(here.bits) ---//
21437 hold >>>= here_bits;
21438 bits -= here_bits;
21439 //---//
21440 state.back += here_bits;
21441 state.length = here_val;
21442 if (here_op === 0) {
21443 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
21444 // "inflate: literal '%c'\n" :
21445 // "inflate: literal 0x%02x\n", here.val));
21446 state.mode = LIT;
21447 break;
21448 }
21449 if (here_op & 32) {
21450 //Tracevv((stderr, "inflate: end of block\n"));
21451 state.back = -1;
21452 state.mode = TYPE$1;
21453 break;
21454 }
21455 if (here_op & 64) {
21456 strm.msg = 'invalid literal/length code';
21457 state.mode = BAD$1;
21458 break;
21459 }
21460 state.extra = here_op & 15;
21461 state.mode = LENEXT;
21462 /* falls through */
21463 case LENEXT:
21464 if (state.extra) {
21465 //=== NEEDBITS(state.extra);
21466 n = state.extra;
21467 while (bits < n) {
21468 if (have === 0) { break inf_leave; }
21469 have--;
21470 hold += input[next++] << bits;
21471 bits += 8;
21472 }
21473 //===//
21474 state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
21475 //--- DROPBITS(state.extra) ---//
21476 hold >>>= state.extra;
21477 bits -= state.extra;
21478 //---//
21479 state.back += state.extra;
21480 }
21481 //Tracevv((stderr, "inflate: length %u\n", state.length));
21482 state.was = state.length;
21483 state.mode = DIST;
21484 /* falls through */
21485 case DIST:
21486 for (;;) {
21487 here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
21488 here_bits = here >>> 24;
21489 here_op = (here >>> 16) & 0xff;
21490 here_val = here & 0xffff;
21491
21492 if ((here_bits) <= bits) { break; }
21493 //--- PULLBYTE() ---//
21494 if (have === 0) { break inf_leave; }
21495 have--;
21496 hold += input[next++] << bits;
21497 bits += 8;
21498 //---//
21499 }
21500 if ((here_op & 0xf0) === 0) {
21501 last_bits = here_bits;
21502 last_op = here_op;
21503 last_val = here_val;
21504 for (;;) {
21505 here = state.distcode[last_val +
21506 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
21507 here_bits = here >>> 24;
21508 here_op = (here >>> 16) & 0xff;
21509 here_val = here & 0xffff;
21510
21511 if ((last_bits + here_bits) <= bits) { break; }
21512 //--- PULLBYTE() ---//
21513 if (have === 0) { break inf_leave; }
21514 have--;
21515 hold += input[next++] << bits;
21516 bits += 8;
21517 //---//
21518 }
21519 //--- DROPBITS(last.bits) ---//
21520 hold >>>= last_bits;
21521 bits -= last_bits;
21522 //---//
21523 state.back += last_bits;
21524 }
21525 //--- DROPBITS(here.bits) ---//
21526 hold >>>= here_bits;
21527 bits -= here_bits;
21528 //---//
21529 state.back += here_bits;
21530 if (here_op & 64) {
21531 strm.msg = 'invalid distance code';
21532 state.mode = BAD$1;
21533 break;
21534 }
21535 state.offset = here_val;
21536 state.extra = (here_op) & 15;
21537 state.mode = DISTEXT;
21538 /* falls through */
21539 case DISTEXT:
21540 if (state.extra) {
21541 //=== NEEDBITS(state.extra);
21542 n = state.extra;
21543 while (bits < n) {
21544 if (have === 0) { break inf_leave; }
21545 have--;
21546 hold += input[next++] << bits;
21547 bits += 8;
21548 }
21549 //===//
21550 state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
21551 //--- DROPBITS(state.extra) ---//
21552 hold >>>= state.extra;
21553 bits -= state.extra;
21554 //---//
21555 state.back += state.extra;
21556 }
21557//#ifdef INFLATE_STRICT
21558 if (state.offset > state.dmax) {
21559 strm.msg = 'invalid distance too far back';
21560 state.mode = BAD$1;
21561 break;
21562 }
21563//#endif
21564 //Tracevv((stderr, "inflate: distance %u\n", state.offset));
21565 state.mode = MATCH;
21566 /* falls through */
21567 case MATCH:
21568 if (left === 0) { break inf_leave; }
21569 copy = _out - left;
21570 if (state.offset > copy) { /* copy from window */
21571 copy = state.offset - copy;
21572 if (copy > state.whave) {
21573 if (state.sane) {
21574 strm.msg = 'invalid distance too far back';
21575 state.mode = BAD$1;
21576 break;
21577 }
21578// (!) This block is disabled in zlib defaults,
21579// don't enable it for binary compatibility
21580//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
21581// Trace((stderr, "inflate.c too far\n"));
21582// copy -= state.whave;
21583// if (copy > state.length) { copy = state.length; }
21584// if (copy > left) { copy = left; }
21585// left -= copy;
21586// state.length -= copy;
21587// do {
21588// output[put++] = 0;
21589// } while (--copy);
21590// if (state.length === 0) { state.mode = LEN; }
21591// break;
21592//#endif
21593 }
21594 if (copy > state.wnext) {
21595 copy -= state.wnext;
21596 from = state.wsize - copy;
21597 }
21598 else {
21599 from = state.wnext - copy;
21600 }
21601 if (copy > state.length) { copy = state.length; }
21602 from_source = state.window;
21603 }
21604 else { /* copy from output */
21605 from_source = output;
21606 from = put - state.offset;
21607 copy = state.length;
21608 }
21609 if (copy > left) { copy = left; }
21610 left -= copy;
21611 state.length -= copy;
21612 do {
21613 output[put++] = from_source[from++];
21614 } while (--copy);
21615 if (state.length === 0) { state.mode = LEN; }
21616 break;
21617 case LIT:
21618 if (left === 0) { break inf_leave; }
21619 output[put++] = state.length;
21620 left--;
21621 state.mode = LEN;
21622 break;
21623 case CHECK:
21624 if (state.wrap) {
21625 //=== NEEDBITS(32);
21626 while (bits < 32) {
21627 if (have === 0) { break inf_leave; }
21628 have--;
21629 // Use '|' instead of '+' to make sure that result is signed
21630 hold |= input[next++] << bits;
21631 bits += 8;
21632 }
21633 //===//
21634 _out -= left;
21635 strm.total_out += _out;
21636 state.total += _out;
21637 if (_out) {
21638 strm.adler = state.check =
21639 /*UPDATE(state.check, put - _out, _out);*/
21640 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
21641
21642 }
21643 _out = left;
21644 // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
21645 if ((state.flags ? hold : zswap32(hold)) !== state.check) {
21646 strm.msg = 'incorrect data check';
21647 state.mode = BAD$1;
21648 break;
21649 }
21650 //=== INITBITS();
21651 hold = 0;
21652 bits = 0;
21653 //===//
21654 //Tracev((stderr, "inflate: check matches trailer\n"));
21655 }
21656 state.mode = LENGTH;
21657 /* falls through */
21658 case LENGTH:
21659 if (state.wrap && state.flags) {
21660 //=== NEEDBITS(32);
21661 while (bits < 32) {
21662 if (have === 0) { break inf_leave; }
21663 have--;
21664 hold += input[next++] << bits;
21665 bits += 8;
21666 }
21667 //===//
21668 if (hold !== (state.total & 0xffffffff)) {
21669 strm.msg = 'incorrect length check';
21670 state.mode = BAD$1;
21671 break;
21672 }
21673 //=== INITBITS();
21674 hold = 0;
21675 bits = 0;
21676 //===//
21677 //Tracev((stderr, "inflate: length matches trailer\n"));
21678 }
21679 state.mode = DONE;
21680 /* falls through */
21681 case DONE:
21682 ret = Z_STREAM_END;
21683 break inf_leave;
21684 case BAD$1:
21685 ret = Z_DATA_ERROR;
21686 break inf_leave;
21687 // case MEM:
21688 // return Z_MEM_ERROR;
21689 case SYNC:
21690 /* falls through */
21691 default:
21692 return Z_STREAM_ERROR;
21693 }
21694 }
21695
21696 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
21697
21698 /*
21699 Return from inflate(), updating the total counts and the check value.
21700 If there was no progress during the inflate() call, return a buffer
21701 error. Call updatewindow() to create and/or update the window state.
21702 Note: a memory error from inflate() is non-recoverable.
21703 */
21704
21705 //--- RESTORE() ---
21706 strm.next_out = put;
21707 strm.avail_out = left;
21708 strm.next_in = next;
21709 strm.avail_in = have;
21710 state.hold = hold;
21711 state.bits = bits;
21712 //---
21713
21714 if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 &&
21715 (state.mode < CHECK || flush !== Z_FINISH))) {
21716 if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;
21717 }
21718 _in -= strm.avail_in;
21719 _out -= strm.avail_out;
21720 strm.total_in += _in;
21721 strm.total_out += _out;
21722 state.total += _out;
21723 if (state.wrap && _out) {
21724 strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
21725 (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
21726 }
21727 strm.data_type = state.bits + (state.last ? 64 : 0) +
21728 (state.mode === TYPE$1 ? 128 : 0) +
21729 (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
21730 if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
21731 ret = Z_BUF_ERROR;
21732 }
21733 return ret;
21734}
21735
21736function inflateEnd(strm) {
21737
21738 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
21739 return Z_STREAM_ERROR;
21740 }
21741
21742 const state = strm.state;
21743 if (state.window) {
21744 state.window = null;
21745 }
21746 strm.state = null;
21747 return Z_OK;
21748}
21749
21750function inflateGetHeader(strm, head) {
21751 let state;
21752
21753 /* check state */
21754 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
21755 state = strm.state;
21756 if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
21757
21758 /* save header structure */
21759 state.head = head;
21760 head.done = false;
21761 return Z_OK;
21762}
21763
21764function inflateSetDictionary(strm, dictionary) {
21765 const dictLength = dictionary.length;
21766
21767 let state;
21768 let dictid;
21769
21770 /* check state */
21771 if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
21772 state = strm.state;
21773
21774 if (state.wrap !== 0 && state.mode !== DICT) {
21775 return Z_STREAM_ERROR;
21776 }
21777
21778 /* check for correct dictionary identifier */
21779 if (state.mode === DICT) {
21780 dictid = 1; /* adler32(0, null, 0)*/
21781 /* dictid = adler32(dictid, dictionary, dictLength); */
21782 dictid = adler32(dictid, dictionary, dictLength, 0);
21783 if (dictid !== state.check) {
21784 return Z_DATA_ERROR;
21785 }
21786 }
21787 /* copy dictionary to window using updatewindow(), which will amend the
21788 existing dictionary if appropriate */
21789 updatewindow(strm, dictionary, dictLength, dictLength);
21790 // if (ret) {
21791 // state.mode = MEM;
21792 // return Z_MEM_ERROR;
21793 // }
21794 state.havedict = 1;
21795 // Tracev((stderr, "inflate: dictionary set\n"));
21796 return Z_OK;
21797}
21798
21799/* Not implemented
21800exports.inflateCopy = inflateCopy;
21801exports.inflateGetDictionary = inflateGetDictionary;
21802exports.inflateMark = inflateMark;
21803exports.inflatePrime = inflatePrime;
21804exports.inflateSync = inflateSync;
21805exports.inflateSyncPoint = inflateSyncPoint;
21806exports.inflateUndermine = inflateUndermine;
21807*/
21808
21809// (C) 1995-2013 Jean-loup Gailly and Mark Adler
21810// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
21811//
21812// This software is provided 'as-is', without any express or implied
21813// warranty. In no event will the authors be held liable for any damages
21814// arising from the use of this software.
21815//
21816// Permission is granted to anyone to use this software for any purpose,
21817// including commercial applications, and to alter it and redistribute it
21818// freely, subject to the following restrictions:
21819//
21820// 1. The origin of this software must not be misrepresented; you must not
21821// claim that you wrote the original software. If you use this software
21822// in a product, an acknowledgment in the product documentation would be
21823// appreciated but is not required.
21824// 2. Altered source versions must be plainly marked as such, and must not be
21825// misrepresented as being the original software.
21826// 3. This notice may not be removed or altered from any source distribution.
21827
21828class GZheader {
21829 constructor() {
21830 /* true if compressed data believed to be text */
21831 this.text = 0;
21832 /* modification time */
21833 this.time = 0;
21834 /* extra flags (not used when writing a gzip file) */
21835 this.xflags = 0;
21836 /* operating system */
21837 this.os = 0;
21838 /* pointer to extra field or Z_NULL if none */
21839 this.extra = null;
21840 /* extra field length (valid if extra != Z_NULL) */
21841 this.extra_len = 0; // Actually, we don't need it in JS,
21842 // but leave for few code modifications
21843
21844 //
21845 // Setup limits is not necessary because in js we should not preallocate memory
21846 // for inflate use constant limit in 65536 bytes
21847 //
21848
21849 /* space at extra (only when reading header) */
21850 // this.extra_max = 0;
21851 /* pointer to zero-terminated file name or Z_NULL */
21852 this.name = '';
21853 /* space at name (only when reading header) */
21854 // this.name_max = 0;
21855 /* pointer to zero-terminated comment or Z_NULL */
21856 this.comment = '';
21857 /* space at comment (only when reading header) */
21858 // this.comm_max = 0;
21859 /* true if there was or will be a header crc */
21860 this.hcrc = 0;
21861 /* true when done reading gzip header (not used when writing a gzip file) */
21862 this.done = false;
21863 }
21864}
21865
21866/**
21867 * class Inflate
21868 *
21869 * Generic JS-style wrapper for zlib calls. If you don't need
21870 * streaming behaviour - use more simple functions: [[inflate]]
21871 * and [[inflateRaw]].
21872 **/
21873
21874/* internal
21875 * inflate.chunks -> Array
21876 *
21877 * Chunks of output data, if [[Inflate#onData]] not overridden.
21878 **/
21879
21880/**
21881 * Inflate.result -> Uint8Array|Array|String
21882 *
21883 * Uncompressed result, generated by default [[Inflate#onData]]
21884 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
21885 * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
21886 * push a chunk with explicit flush (call [[Inflate#push]] with
21887 * `Z_SYNC_FLUSH` param).
21888 **/
21889
21890/**
21891 * Inflate.err -> Number
21892 *
21893 * Error code after inflate finished. 0 (Z_OK) on success.
21894 * Should be checked if broken data possible.
21895 **/
21896
21897/**
21898 * Inflate.msg -> String
21899 *
21900 * Error message, if [[Inflate.err]] != 0
21901 **/
21902
21903
21904/**
21905 * new Inflate(options)
21906 * - options (Object): zlib inflate options.
21907 *
21908 * Creates new inflator instance with specified params. Throws exception
21909 * on bad params. Supported options:
21910 *
21911 * - `windowBits`
21912 * - `dictionary`
21913 *
21914 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
21915 * for more information on these.
21916 *
21917 * Additional options, for internal needs:
21918 *
21919 * - `chunkSize` - size of generated data chunks (16K by default)
21920 * - `raw` (Boolean) - do raw inflate
21921 * - `to` (String) - if equal to 'string', then result will be converted
21922 * from utf8 to utf16 (javascript) string. When string output requested,
21923 * chunk length can differ from `chunkSize`, depending on content.
21924 *
21925 * By default, when no options set, autodetect deflate/gzip data format via
21926 * wrapper header.
21927 *
21928 * ##### Example:
21929 *
21930 * ```javascript
21931 * var pako = void('pako')
21932 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
21933 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
21934 *
21935 * var inflate = new pako.Inflate({ level: 3});
21936 *
21937 * inflate.push(chunk1, false);
21938 * inflate.push(chunk2, true); // true -> last chunk
21939 *
21940 * if (inflate.err) { throw new Error(inflate.err); }
21941 *
21942 * console.log(inflate.result);
21943 * ```
21944 **/
21945class Inflate {
21946 constructor(options) {
21947 this.options = {
21948 chunkSize: 16384,
21949 windowBits: 0,
21950 ...(options || {})
21951 };
21952
21953 const opt = this.options;
21954
21955 // Force window size for `raw` data, if not set directly,
21956 // because we have no header for autodetect.
21957 if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
21958 opt.windowBits = -opt.windowBits;
21959 if (opt.windowBits === 0) { opt.windowBits = -15; }
21960 }
21961
21962 // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
21963 if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
21964 !(options && options.windowBits)) {
21965 opt.windowBits += 32;
21966 }
21967
21968 // Gzip header has no info about windows size, we can do autodetect only
21969 // for deflate. So, if window size not set, force it to max when gzip possible
21970 if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
21971 // bit 3 (16) -> gzipped data
21972 // bit 4 (32) -> autodetect gzip/deflate
21973 if ((opt.windowBits & 15) === 0) {
21974 opt.windowBits |= 15;
21975 }
21976 }
21977
21978 this.err = 0; // error code, if happens (0 = Z_OK)
21979 this.msg = ''; // error message
21980 this.ended = false; // used to avoid multiple onEnd() calls
21981 this.chunks = []; // chunks of compressed data
21982
21983 this.strm = new ZStream();
21984 this.strm.avail_out = 0;
21985
21986 let status = inflateInit2(
21987 this.strm,
21988 opt.windowBits
21989 );
21990
21991 if (status !== Z_OK) {
21992 throw new Error(msg[status]);
21993 }
21994
21995 this.header = new GZheader();
21996
21997 inflateGetHeader(this.strm, this.header);
21998
21999 // Setup dictionary
22000 if (opt.dictionary) {
22001 // Convert data if needed
22002 if (typeof opt.dictionary === 'string') {
22003 opt.dictionary = string2buf(opt.dictionary);
22004 } else if (opt.dictionary instanceof ArrayBuffer) {
22005 opt.dictionary = new Uint8Array(opt.dictionary);
22006 }
22007 if (opt.raw) { //In raw mode we need to set the dictionary early
22008 status = inflateSetDictionary(this.strm, opt.dictionary);
22009 if (status !== Z_OK) {
22010 throw new Error(msg[status]);
22011 }
22012 }
22013 }
22014 }
22015 /**
22016 * Inflate#push(data[, mode]) -> Boolean
22017 * - data (Uint8Array|Array|ArrayBuffer|String): input data
22018 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
22019 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
22020 *
22021 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
22022 * new output chunks. Returns `true` on success. The last data block must have
22023 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
22024 * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
22025 * can use mode Z_SYNC_FLUSH, keeping the decompression context.
22026 *
22027 * On fail call [[Inflate#onEnd]] with error code and return false.
22028 *
22029 * We strongly recommend to use `Uint8Array` on input for best speed (output
22030 * format is detected automatically). Also, don't skip last param and always
22031 * use the same type in your code (boolean or number). That will improve JS speed.
22032 *
22033 * For regular `Array`-s make sure all elements are [0..255].
22034 *
22035 * ##### Example
22036 *
22037 * ```javascript
22038 * push(chunk, false); // push one of data chunks
22039 * ...
22040 * push(chunk, true); // push last chunk
22041 * ```
22042 **/
22043 push(data, mode) {
22044 const { strm, options: { chunkSize, dictionary } } = this;
22045 let status, _mode;
22046
22047 // Flag to properly process Z_BUF_ERROR on testing inflate call
22048 // when we check that all output data was flushed.
22049 let allowBufError = false;
22050
22051 if (this.ended) { return false; }
22052 _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
22053
22054 // Convert data if needed
22055 if (typeof data === 'string') {
22056 // Only binary strings can be decompressed on practice
22057 strm.input = binstring2buf(data);
22058 } else if (data instanceof ArrayBuffer) {
22059 strm.input = new Uint8Array(data);
22060 } else {
22061 strm.input = data;
22062 }
22063
22064 strm.next_in = 0;
22065 strm.avail_in = strm.input.length;
22066
22067 do {
22068 if (strm.avail_out === 0) {
22069 strm.output = new Buf8(chunkSize);
22070 strm.next_out = 0;
22071 strm.avail_out = chunkSize;
22072 }
22073
22074 status = inflate(strm, Z_NO_FLUSH); /* no bad return value */
22075
22076 if (status === Z_NEED_DICT && dictionary) {
22077 status = inflateSetDictionary(this.strm, dictionary);
22078 }
22079
22080 if (status === Z_BUF_ERROR && allowBufError === true) {
22081 status = Z_OK;
22082 allowBufError = false;
22083 }
22084
22085 if (status !== Z_STREAM_END && status !== Z_OK) {
22086 this.onEnd(status);
22087 this.ended = true;
22088 return false;
22089 }
22090
22091 if (strm.next_out) {
22092 if (strm.avail_out === 0 || status === Z_STREAM_END || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
22093 this.onData(shrinkBuf(strm.output, strm.next_out));
22094 }
22095 }
22096
22097 // When no more input data, we should check that internal inflate buffers
22098 // are flushed. The only way to do it when avail_out = 0 - run one more
22099 // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
22100 // Here we set flag to process this error properly.
22101 //
22102 // NOTE. Deflate does not return error in this case and does not needs such
22103 // logic.
22104 if (strm.avail_in === 0 && strm.avail_out === 0) {
22105 allowBufError = true;
22106 }
22107
22108 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
22109
22110 if (status === Z_STREAM_END) {
22111 _mode = Z_FINISH;
22112 }
22113
22114 // Finalize on the last chunk.
22115 if (_mode === Z_FINISH) {
22116 status = inflateEnd(this.strm);
22117 this.onEnd(status);
22118 this.ended = true;
22119 return status === Z_OK;
22120 }
22121
22122 // callback interim results if Z_SYNC_FLUSH.
22123 if (_mode === Z_SYNC_FLUSH) {
22124 this.onEnd(Z_OK);
22125 strm.avail_out = 0;
22126 return true;
22127 }
22128
22129 return true;
22130 };
22131
22132 /**
22133 * Inflate#onData(chunk) -> Void
22134 * - chunk (Uint8Array|Array|String): output data. Type of array depends
22135 * on js engine support. When string output requested, each chunk
22136 * will be string.
22137 *
22138 * By default, stores data blocks in `chunks[]` property and glue
22139 * those in `onEnd`. Override this handler, if you need another behaviour.
22140 **/
22141 onData(chunk) {
22142 this.chunks.push(chunk);
22143 };
22144
22145
22146
22147 /**
22148 * Inflate#onEnd(status) -> Void
22149 * - status (Number): inflate status. 0 (Z_OK) on success,
22150 * other if not.
22151 *
22152 * Called either after you tell inflate that the input stream is
22153 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
22154 * or if an error happened. By default - join collected chunks,
22155 * free memory and fill `results` / `err` properties.
22156 **/
22157 onEnd(status) {
22158 // On success - join
22159 if (status === Z_OK) {
22160 this.result = flattenChunks(this.chunks);
22161 }
22162 this.chunks = [];
22163 this.err = status;
22164 this.msg = this.strm.msg;
22165 };
22166}
22167
22168/*
22169node-bzip - a pure-javascript Node.JS module for decoding bzip2 data
22170
22171Copyright (C) 2012 Eli Skeggs
22172
22173This library is free software; you can redistribute it and/or
22174modify it under the terms of the GNU Lesser General Public
22175License as published by the Free Software Foundation; either
22176version 2.1 of the License, or (at your option) any later version.
22177
22178This library is distributed in the hope that it will be useful,
22179but WITHOUT ANY WARRANTY; without even the implied warranty of
22180MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22181Lesser General Public License for more details.
22182
22183You should have received a copy of the GNU Lesser General Public
22184License along with this library; if not, see
22185http://www.gnu.org/licenses/lgpl-2.1.html
22186
22187Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).
22188
22189Based on micro-bunzip by Rob Landley (rob@landley.net).
22190
22191Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
22192which also acknowledges contributions by Mike Burrows, David Wheeler,
22193Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
22194Robert Sedgewick, and Jon L. Bentley.
22195*/
22196
22197var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];
22198
22199// offset in bytes
22200var BitReader = function(stream) {
22201 this.stream = stream;
22202 this.bitOffset = 0;
22203 this.curByte = 0;
22204 this.hasByte = false;
22205};
22206
22207BitReader.prototype._ensureByte = function() {
22208 if (!this.hasByte) {
22209 this.curByte = this.stream.readByte();
22210 this.hasByte = true;
22211 }
22212};
22213
22214// reads bits from the buffer
22215BitReader.prototype.read = function(bits) {
22216 var result = 0;
22217 while (bits > 0) {
22218 this._ensureByte();
22219 var remaining = 8 - this.bitOffset;
22220 // if we're in a byte
22221 if (bits >= remaining) {
22222 result <<= remaining;
22223 result |= BITMASK[remaining] & this.curByte;
22224 this.hasByte = false;
22225 this.bitOffset = 0;
22226 bits -= remaining;
22227 } else {
22228 result <<= bits;
22229 var shift = remaining - bits;
22230 result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;
22231 this.bitOffset += bits;
22232 bits = 0;
22233 }
22234 }
22235 return result;
22236};
22237
22238// seek to an arbitrary point in the buffer (expressed in bits)
22239BitReader.prototype.seek = function(pos) {
22240 var n_bit = pos % 8;
22241 var n_byte = (pos - n_bit) / 8;
22242 this.bitOffset = n_bit;
22243 this.stream.seek(n_byte);
22244 this.hasByte = false;
22245};
22246
22247// reads 6 bytes worth of data using the read method
22248BitReader.prototype.pi = function() {
22249 var buf = new Uint8Array(6), i;
22250 for (i = 0; i < buf.length; i++) {
22251 buf[i] = this.read(8);
22252 }
22253 return bufToHex(buf);
22254};
22255
22256function bufToHex(buf) {
22257 return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');
22258}
22259
22260var bitreader = BitReader;
22261
22262/* very simple input/output stream interface */
22263var Stream = function() {
22264};
22265
22266// input streams //////////////
22267/** Returns the next byte, or -1 for EOF. */
22268Stream.prototype.readByte = function() {
22269 throw new Error("abstract method readByte() not implemented");
22270};
22271/** Attempts to fill the buffer; returns number of bytes read, or
22272 * -1 for EOF. */
22273Stream.prototype.read = function(buffer, bufOffset, length) {
22274 var bytesRead = 0;
22275 while (bytesRead < length) {
22276 var c = this.readByte();
22277 if (c < 0) { // EOF
22278 return (bytesRead===0) ? -1 : bytesRead;
22279 }
22280 buffer[bufOffset++] = c;
22281 bytesRead++;
22282 }
22283 return bytesRead;
22284};
22285Stream.prototype.seek = function(new_pos) {
22286 throw new Error("abstract method seek() not implemented");
22287};
22288
22289// output streams ///////////
22290Stream.prototype.writeByte = function(_byte) {
22291 throw new Error("abstract method readByte() not implemented");
22292};
22293Stream.prototype.write = function(buffer, bufOffset, length) {
22294 var i;
22295 for (i=0; i<length; i++) {
22296 this.writeByte(buffer[bufOffset++]);
22297 }
22298 return length;
22299};
22300Stream.prototype.flush = function() {
22301};
22302
22303var stream = Stream;
22304
22305/* CRC32, used in Bzip2 implementation.
22306 * This is a port of CRC32.java from the jbzip2 implementation at
22307 * https://code.google.com/p/jbzip2
22308 * which is:
22309 * Copyright (c) 2011 Matthew Francis
22310 *
22311 * Permission is hereby granted, free of charge, to any person
22312 * obtaining a copy of this software and associated documentation
22313 * files (the "Software"), to deal in the Software without
22314 * restriction, including without limitation the rights to use,
22315 * copy, modify, merge, publish, distribute, sublicense, and/or sell
22316 * copies of the Software, and to permit persons to whom the
22317 * Software is furnished to do so, subject to the following
22318 * conditions:
22319 *
22320 * The above copyright notice and this permission notice shall be
22321 * included in all copies or substantial portions of the Software.
22322 *
22323 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22324 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
22325 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22326 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22327 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
22328 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22329 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22330 * OTHER DEALINGS IN THE SOFTWARE.
22331 * This JavaScript implementation is:
22332 * Copyright (c) 2013 C. Scott Ananian
22333 * with the same licensing terms as Matthew Francis' original implementation.
22334 */
22335var crc32$1 = (function() {
22336
22337 /**
22338 * A static CRC lookup table
22339 */
22340 var crc32Lookup = new Uint32Array([
22341 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
22342 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
22343 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
22344 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
22345 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
22346 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
22347 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
22348 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
22349 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
22350 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
22351 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
22352 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
22353 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
22354 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
22355 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
22356 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
22357 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
22358 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
22359 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
22360 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
22361 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
22362 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
22363 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
22364 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
22365 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
22366 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
22367 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
22368 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
22369 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
22370 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
22371 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
22372 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
22373 ]);
22374
22375 var CRC32 = function() {
22376 /**
22377 * The current CRC
22378 */
22379 var crc = 0xffffffff;
22380
22381 /**
22382 * @return The current CRC
22383 */
22384 this.getCRC = function() {
22385 return (~crc) >>> 0; // return an unsigned value
22386 };
22387
22388 /**
22389 * Update the CRC with a single byte
22390 * @param value The value to update the CRC with
22391 */
22392 this.updateCRC = function(value) {
22393 crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];
22394 };
22395
22396 /**
22397 * Update the CRC with a sequence of identical bytes
22398 * @param value The value to update the CRC with
22399 * @param count The number of bytes
22400 */
22401 this.updateCRCRun = function(value, count) {
22402 while (count-- > 0) {
22403 crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];
22404 }
22405 };
22406 };
22407 return CRC32;
22408})();
22409
22410/*
22411seek-bzip - a pure-javascript module for seeking within bzip2 data
22412
22413Copyright (C) 2013 C. Scott Ananian
22414Copyright (C) 2012 Eli Skeggs
22415Copyright (C) 2011 Kevin Kwok
22416
22417This library is free software; you can redistribute it and/or
22418modify it under the terms of the GNU Lesser General Public
22419License as published by the Free Software Foundation; either
22420version 2.1 of the License, or (at your option) any later version.
22421
22422This library is distributed in the hope that it will be useful,
22423but WITHOUT ANY WARRANTY; without even the implied warranty of
22424MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22425Lesser General Public License for more details.
22426
22427You should have received a copy of the GNU Lesser General Public
22428License along with this library; if not, see
22429http://www.gnu.org/licenses/lgpl-2.1.html
22430
22431Adapted from node-bzip, copyright 2012 Eli Skeggs.
22432Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).
22433
22434Based on micro-bunzip by Rob Landley (rob@landley.net).
22435
22436Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
22437which also acknowledges contributions by Mike Burrows, David Wheeler,
22438Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
22439Robert Sedgewick, and Jon L. Bentley.
22440*/
22441
22442
22443
22444
22445
22446var MAX_HUFCODE_BITS = 20;
22447var MAX_SYMBOLS = 258;
22448var SYMBOL_RUNA = 0;
22449var SYMBOL_RUNB = 1;
22450var MIN_GROUPS = 2;
22451var MAX_GROUPS = 6;
22452var GROUP_SIZE = 50;
22453
22454var WHOLEPI = "314159265359";
22455var SQRTPI = "177245385090";
22456
22457var mtf = function(array, index) {
22458 var src = array[index], i;
22459 for (i = index; i > 0; i--) {
22460 array[i] = array[i-1];
22461 }
22462 array[0] = src;
22463 return src;
22464};
22465
22466var Err = {
22467 OK: 0,
22468 LAST_BLOCK: -1,
22469 NOT_BZIP_DATA: -2,
22470 UNEXPECTED_INPUT_EOF: -3,
22471 UNEXPECTED_OUTPUT_EOF: -4,
22472 DATA_ERROR: -5,
22473 OUT_OF_MEMORY: -6,
22474 OBSOLETE_INPUT: -7,
22475 END_OF_BLOCK: -8
22476};
22477var ErrorMessages = {};
22478ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum";
22479ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data";
22480ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF";
22481ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF";
22482ErrorMessages[Err.DATA_ERROR] = "Data error";
22483ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory";
22484ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported.";
22485
22486var _throw = function(status, optDetail) {
22487 var msg = ErrorMessages[status] || 'unknown error';
22488 if (optDetail) { msg += ': '+optDetail; }
22489 var e = new TypeError(msg);
22490 e.errorCode = status;
22491 throw e;
22492};
22493
22494var Bunzip = function(inputStream, outputStream) {
22495 this.writePos = this.writeCurrent = this.writeCount = 0;
22496
22497 this._start_bunzip(inputStream, outputStream);
22498};
22499Bunzip.prototype._init_block = function() {
22500 var moreBlocks = this._get_next_block();
22501 if ( !moreBlocks ) {
22502 this.writeCount = -1;
22503 return false; /* no more blocks */
22504 }
22505 this.blockCRC = new crc32$1();
22506 return true;
22507};
22508/* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */
22509Bunzip.prototype._start_bunzip = function(inputStream, outputStream) {
22510 /* Ensure that file starts with "BZh['1'-'9']." */
22511 var buf = new Uint8Array(4);
22512 if (inputStream.read(buf, 0, 4) !== 4 ||
22513 String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')
22514 _throw(Err.NOT_BZIP_DATA, 'bad magic');
22515
22516 var level = buf[3] - 0x30;
22517 if (level < 1 || level > 9)
22518 _throw(Err.NOT_BZIP_DATA, 'level out of range');
22519
22520 this.reader = new bitreader(inputStream);
22521
22522 /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of
22523 uncompressed data. Allocate intermediate buffer for block. */
22524 this.dbufSize = 100000 * level;
22525 this.nextoutput = 0;
22526 this.outputStream = outputStream;
22527 this.streamCRC = 0;
22528};
22529Bunzip.prototype._get_next_block = function() {
22530 var i, j, k;
22531 var reader = this.reader;
22532 // this is get_next_block() function from micro-bunzip:
22533 /* Read in header signature and CRC, then validate signature.
22534 (last block signature means CRC is for whole file, return now) */
22535 var h = reader.pi();
22536 if (h === SQRTPI) { // last block
22537 return false; /* no more blocks */
22538 }
22539 if (h !== WHOLEPI)
22540 _throw(Err.NOT_BZIP_DATA);
22541 this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)
22542 this.streamCRC = (this.targetBlockCRC ^
22543 ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;
22544 /* We can add support for blockRandomised if anybody complains. There was
22545 some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
22546 it didn't actually work. */
22547 if (reader.read(1))
22548 _throw(Err.OBSOLETE_INPUT);
22549 var origPointer = reader.read(24);
22550 if (origPointer > this.dbufSize)
22551 _throw(Err.DATA_ERROR, 'initial position out of bounds');
22552 /* mapping table: if some byte values are never used (encoding things
22553 like ascii text), the compression code removes the gaps to have fewer
22554 symbols to deal with, and writes a sparse bitfield indicating which
22555 values were present. We make a translation table to convert the symbols
22556 back to the corresponding bytes. */
22557 var t = reader.read(16);
22558 var symToByte = new Uint8Array(256), symTotal = 0;
22559 for (i = 0; i < 16; i++) {
22560 if (t & (1 << (0xF - i))) {
22561 var o = i * 16;
22562 k = reader.read(16);
22563 for (j = 0; j < 16; j++)
22564 if (k & (1 << (0xF - j)))
22565 symToByte[symTotal++] = o + j;
22566 }
22567 }
22568
22569 /* How many different huffman coding groups does this block use? */
22570 var groupCount = reader.read(3);
22571 if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)
22572 _throw(Err.DATA_ERROR);
22573 /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding
22574 group. Read in the group selector list, which is stored as MTF encoded
22575 bit runs. (MTF=Move To Front, as each value is used it's moved to the
22576 start of the list.) */
22577 var nSelectors = reader.read(15);
22578 if (nSelectors === 0)
22579 _throw(Err.DATA_ERROR);
22580
22581 var mtfSymbol = new Uint8Array(256);
22582 for (i = 0; i < groupCount; i++)
22583 mtfSymbol[i] = i;
22584
22585 var selectors = new Uint8Array(nSelectors); // was 32768...
22586
22587 for (i = 0; i < nSelectors; i++) {
22588 /* Get next value */
22589 for (j = 0; reader.read(1); j++)
22590 if (j >= groupCount) _throw(Err.DATA_ERROR);
22591 /* Decode MTF to get the next selector */
22592 selectors[i] = mtf(mtfSymbol, j);
22593 }
22594
22595 /* Read the huffman coding tables for each group, which code for symTotal
22596 literal symbols, plus two run symbols (RUNA, RUNB) */
22597 var symCount = symTotal + 2;
22598 var groups = [], hufGroup;
22599 for (j = 0; j < groupCount; j++) {
22600 var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);
22601 /* Read huffman code lengths for each symbol. They're stored in
22602 a way similar to mtf; record a starting value for the first symbol,
22603 and an offset from the previous value for everys symbol after that. */
22604 t = reader.read(5); // lengths
22605 for (i = 0; i < symCount; i++) {
22606 for (;;) {
22607 if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);
22608 /* If first bit is 0, stop. Else second bit indicates whether
22609 to increment or decrement the value. */
22610 if(!reader.read(1))
22611 break;
22612 if(!reader.read(1))
22613 t++;
22614 else
22615 t--;
22616 }
22617 length[i] = t;
22618 }
22619
22620 /* Find largest and smallest lengths in this group */
22621 var minLen, maxLen;
22622 minLen = maxLen = length[0];
22623 for (i = 1; i < symCount; i++) {
22624 if (length[i] > maxLen)
22625 maxLen = length[i];
22626 else if (length[i] < minLen)
22627 minLen = length[i];
22628 }
22629
22630 /* Calculate permute[], base[], and limit[] tables from length[].
22631 *
22632 * permute[] is the lookup table for converting huffman coded symbols
22633 * into decoded symbols. base[] is the amount to subtract from the
22634 * value of a huffman symbol of a given length when using permute[].
22635 *
22636 * limit[] indicates the largest numerical value a symbol with a given
22637 * number of bits can have. This is how the huffman codes can vary in
22638 * length: each code with a value>limit[length] needs another bit.
22639 */
22640 hufGroup = {};
22641 groups.push(hufGroup);
22642 hufGroup.permute = new Uint16Array(MAX_SYMBOLS);
22643 hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);
22644 hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);
22645 hufGroup.minLen = minLen;
22646 hufGroup.maxLen = maxLen;
22647 /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */
22648 var pp = 0;
22649 for (i = minLen; i <= maxLen; i++) {
22650 temp[i] = hufGroup.limit[i] = 0;
22651 for (t = 0; t < symCount; t++)
22652 if (length[t] === i)
22653 hufGroup.permute[pp++] = t;
22654 }
22655 /* Count symbols coded for at each bit length */
22656 for (i = 0; i < symCount; i++)
22657 temp[length[i]]++;
22658 /* Calculate limit[] (the largest symbol-coding value at each bit
22659 * length, which is (previous limit<<1)+symbols at this level), and
22660 * base[] (number of symbols to ignore at each bit length, which is
22661 * limit minus the cumulative count of symbols coded for already). */
22662 pp = t = 0;
22663 for (i = minLen; i < maxLen; i++) {
22664 pp += temp[i];
22665 /* We read the largest possible symbol size and then unget bits
22666 after determining how many we need, and those extra bits could
22667 be set to anything. (They're noise from future symbols.) At
22668 each level we're really only interested in the first few bits,
22669 so here we set all the trailing to-be-ignored bits to 1 so they
22670 don't affect the value>limit[length] comparison. */
22671 hufGroup.limit[i] = pp - 1;
22672 pp <<= 1;
22673 t += temp[i];
22674 hufGroup.base[i + 1] = pp - t;
22675 }
22676 hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */
22677 hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;
22678 hufGroup.base[minLen] = 0;
22679 }
22680 /* We've finished reading and digesting the block header. Now read this
22681 block's huffman coded symbols from the file and undo the huffman coding
22682 and run length encoding, saving the result into dbuf[dbufCount++]=uc */
22683
22684 /* Initialize symbol occurrence counters and symbol Move To Front table */
22685 var byteCount = new Uint32Array(256);
22686 for (i = 0; i < 256; i++)
22687 mtfSymbol[i] = i;
22688 /* Loop through compressed symbols. */
22689 var runPos = 0, dbufCount = 0, selector = 0, uc;
22690 var dbuf = this.dbuf = new Uint32Array(this.dbufSize);
22691 symCount = 0;
22692 for (;;) {
22693 /* Determine which huffman coding group to use. */
22694 if (!(symCount--)) {
22695 symCount = GROUP_SIZE - 1;
22696 if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }
22697 hufGroup = groups[selectors[selector++]];
22698 }
22699 /* Read next huffman-coded symbol. */
22700 i = hufGroup.minLen;
22701 j = reader.read(i);
22702 for (;;i++) {
22703 if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }
22704 if (j <= hufGroup.limit[i])
22705 break;
22706 j = (j << 1) | reader.read(1);
22707 }
22708 /* Huffman decode value to get nextSym (with bounds checking) */
22709 j -= hufGroup.base[i];
22710 if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }
22711 var nextSym = hufGroup.permute[j];
22712 /* We have now decoded the symbol, which indicates either a new literal
22713 byte, or a repeated run of the most recent literal byte. First,
22714 check if nextSym indicates a repeated run, and if so loop collecting
22715 how many times to repeat the last literal. */
22716 if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {
22717 /* If this is the start of a new run, zero out counter */
22718 if (!runPos){
22719 runPos = 1;
22720 t = 0;
22721 }
22722 /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
22723 each bit position, add 1 or 2 instead. For example,
22724 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
22725 You can make any bit pattern that way using 1 less symbol than
22726 the basic or 0/1 method (except all bits 0, which would use no
22727 symbols, but a run of length 0 doesn't mean anything in this
22728 context). Thus space is saved. */
22729 if (nextSym === SYMBOL_RUNA)
22730 t += runPos;
22731 else
22732 t += 2 * runPos;
22733 runPos <<= 1;
22734 continue;
22735 }
22736 /* When we hit the first non-run symbol after a run, we now know
22737 how many times to repeat the last literal, so append that many
22738 copies to our buffer of decoded symbols (dbuf) now. (The last
22739 literal used is the one at the head of the mtfSymbol array.) */
22740 if (runPos){
22741 runPos = 0;
22742 if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }
22743 uc = symToByte[mtfSymbol[0]];
22744 byteCount[uc] += t;
22745 while (t--)
22746 dbuf[dbufCount++] = uc;
22747 }
22748 /* Is this the terminating symbol? */
22749 if (nextSym > symTotal)
22750 break;
22751 /* At this point, nextSym indicates a new literal character. Subtract
22752 one to get the position in the MTF array at which this literal is
22753 currently to be found. (Note that the result can't be -1 or 0,
22754 because 0 and 1 are RUNA and RUNB. But another instance of the
22755 first symbol in the mtf array, position 0, would have been handled
22756 as part of a run above. Therefore 1 unused mtf position minus
22757 2 non-literal nextSym values equals -1.) */
22758 if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }
22759 i = nextSym - 1;
22760 uc = mtf(mtfSymbol, i);
22761 uc = symToByte[uc];
22762 /* We have our literal byte. Save it into dbuf. */
22763 byteCount[uc]++;
22764 dbuf[dbufCount++] = uc;
22765 }
22766 /* At this point, we've read all the huffman-coded symbols (and repeated
22767 runs) for this block from the input stream, and decoded them into the
22768 intermediate buffer. There are dbufCount many decoded bytes in dbuf[].
22769 Now undo the Burrows-Wheeler transform on dbuf.
22770 See http://dogma.net/markn/articles/bwt/bwt.htm
22771 */
22772 if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }
22773 /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
22774 j = 0;
22775 for (i = 0; i < 256; i++) {
22776 k = j + byteCount[i];
22777 byteCount[i] = j;
22778 j = k;
22779 }
22780 /* Figure out what order dbuf would be in if we sorted it. */
22781 for (i = 0; i < dbufCount; i++) {
22782 uc = dbuf[i] & 0xff;
22783 dbuf[byteCount[uc]] |= (i << 8);
22784 byteCount[uc]++;
22785 }
22786 /* Decode first byte by hand to initialize "previous" byte. Note that it
22787 doesn't get output, and if the first three characters are identical
22788 it doesn't qualify as a run (hence writeRunCountdown=5). */
22789 var pos = 0, current = 0, run = 0;
22790 if (dbufCount) {
22791 pos = dbuf[origPointer];
22792 current = (pos & 0xff);
22793 pos >>= 8;
22794 run = -1;
22795 }
22796 this.writePos = pos;
22797 this.writeCurrent = current;
22798 this.writeCount = dbufCount;
22799 this.writeRun = run;
22800
22801 return true; /* more blocks to come */
22802};
22803/* Undo burrows-wheeler transform on intermediate buffer to produce output.
22804 If start_bunzip was initialized with out_fd=-1, then up to len bytes of
22805 data are written to outbuf. Return value is number of bytes written or
22806 error (all errors are negative numbers). If out_fd!=-1, outbuf and len
22807 are ignored, data is written to out_fd and return is RETVAL_OK or error.
22808*/
22809Bunzip.prototype._read_bunzip = function(outputBuffer, len) {
22810 var copies, previous, outbyte;
22811 /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully
22812 decoded, which results in this returning RETVAL_LAST_BLOCK, also
22813 equal to -1... Confusing, I'm returning 0 here to indicate no
22814 bytes written into the buffer */
22815 if (this.writeCount < 0) { return 0; }
22816 var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;
22817 var dbufCount = this.writeCount; this.outputsize;
22818 var run = this.writeRun;
22819
22820 while (dbufCount) {
22821 dbufCount--;
22822 previous = current;
22823 pos = dbuf[pos];
22824 current = pos & 0xff;
22825 pos >>= 8;
22826 if (run++ === 3){
22827 copies = current;
22828 outbyte = previous;
22829 current = -1;
22830 } else {
22831 copies = 1;
22832 outbyte = current;
22833 }
22834 this.blockCRC.updateCRCRun(outbyte, copies);
22835 while (copies--) {
22836 this.outputStream.writeByte(outbyte);
22837 this.nextoutput++;
22838 }
22839 if (current != previous)
22840 run = 0;
22841 }
22842 this.writeCount = dbufCount;
22843 // check CRC
22844 if (this.blockCRC.getCRC() !== this.targetBlockCRC) {
22845 _throw(Err.DATA_ERROR, "Bad block CRC "+
22846 "(got "+this.blockCRC.getCRC().toString(16)+
22847 " expected "+this.targetBlockCRC.toString(16)+")");
22848 }
22849 return this.nextoutput;
22850};
22851
22852var coerceInputStream = function(input) {
22853 if ('readByte' in input) { return input; }
22854 var inputStream = new stream();
22855 inputStream.pos = 0;
22856 inputStream.readByte = function() { return input[this.pos++]; };
22857 inputStream.seek = function(pos) { this.pos = pos; };
22858 inputStream.eof = function() { return this.pos >= input.length; };
22859 return inputStream;
22860};
22861var coerceOutputStream = function(output) {
22862 var outputStream = new stream();
22863 var resizeOk = true;
22864 if (output) {
22865 if (typeof(output)==='number') {
22866 outputStream.buffer = new Uint8Array(output);
22867 resizeOk = false;
22868 } else if ('writeByte' in output) {
22869 return output;
22870 } else {
22871 outputStream.buffer = output;
22872 resizeOk = false;
22873 }
22874 } else {
22875 outputStream.buffer = new Uint8Array(16384);
22876 }
22877 outputStream.pos = 0;
22878 outputStream.writeByte = function(_byte) {
22879 if (resizeOk && this.pos >= this.buffer.length) {
22880 var newBuffer = new Uint8Array(this.buffer.length*2);
22881 newBuffer.set(this.buffer);
22882 this.buffer = newBuffer;
22883 }
22884 this.buffer[this.pos++] = _byte;
22885 };
22886 outputStream.getBuffer = function() {
22887 // trim buffer
22888 if (this.pos !== this.buffer.length) {
22889 if (!resizeOk)
22890 throw new TypeError('outputsize does not match decoded input');
22891 var newBuffer = new Uint8Array(this.pos);
22892 newBuffer.set(this.buffer.subarray(0, this.pos));
22893 this.buffer = newBuffer;
22894 }
22895 return this.buffer;
22896 };
22897 outputStream._coerced = true;
22898 return outputStream;
22899};
22900
22901/* Static helper functions */
22902// 'input' can be a stream or a buffer
22903// 'output' can be a stream or a buffer or a number (buffer size)
22904const decode$2 = function(input, output, multistream) {
22905 // make a stream from a buffer, if necessary
22906 var inputStream = coerceInputStream(input);
22907 var outputStream = coerceOutputStream(output);
22908
22909 var bz = new Bunzip(inputStream, outputStream);
22910 while (true) {
22911 if ('eof' in inputStream && inputStream.eof()) break;
22912 if (bz._init_block()) {
22913 bz._read_bunzip();
22914 } else {
22915 var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)
22916 if (targetStreamCRC !== bz.streamCRC) {
22917 _throw(Err.DATA_ERROR, "Bad stream CRC "+
22918 "(got "+bz.streamCRC.toString(16)+
22919 " expected "+targetStreamCRC.toString(16)+")");
22920 }
22921 if (multistream &&
22922 'eof' in inputStream &&
22923 !inputStream.eof()) {
22924 // note that start_bunzip will also resync the bit reader to next byte
22925 bz._start_bunzip(inputStream, outputStream);
22926 } else break;
22927 }
22928 }
22929 if ('getBuffer' in outputStream)
22930 return outputStream.getBuffer();
22931};
22932const decodeBlock = function(input, pos, output) {
22933 // make a stream from a buffer, if necessary
22934 var inputStream = coerceInputStream(input);
22935 var outputStream = coerceOutputStream(output);
22936 var bz = new Bunzip(inputStream, outputStream);
22937 bz.reader.seek(pos);
22938 /* Fill the decode buffer for the block */
22939 var moreBlocks = bz._get_next_block();
22940 if (moreBlocks) {
22941 /* Init the CRC for writing */
22942 bz.blockCRC = new crc32$1();
22943
22944 /* Zero this so the current byte from before the seek is not written */
22945 bz.writeCopies = 0;
22946
22947 /* Decompress the block and write to stdout */
22948 bz._read_bunzip();
22949 // XXX keep writing?
22950 }
22951 if ('getBuffer' in outputStream)
22952 return outputStream.getBuffer();
22953};
22954/* Reads bzip2 file from stream or buffer `input`, and invoke
22955 * `callback(position, size)` once for each bzip2 block,
22956 * where position gives the starting position (in *bits*)
22957 * and size gives uncompressed size of the block (in *bytes*). */
22958const table = function(input, callback, multistream) {
22959 // make a stream from a buffer, if necessary
22960 var inputStream = new stream();
22961 inputStream.delegate = coerceInputStream(input);
22962 inputStream.pos = 0;
22963 inputStream.readByte = function() {
22964 this.pos++;
22965 return this.delegate.readByte();
22966 };
22967 if (inputStream.delegate.eof) {
22968 inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);
22969 }
22970 var outputStream = new stream();
22971 outputStream.pos = 0;
22972 outputStream.writeByte = function() { this.pos++; };
22973
22974 var bz = new Bunzip(inputStream, outputStream);
22975 var blockSize = bz.dbufSize;
22976 while (true) {
22977 if ('eof' in inputStream && inputStream.eof()) break;
22978
22979 var position = inputStream.pos*8 + bz.reader.bitOffset;
22980 if (bz.reader.hasByte) { position -= 8; }
22981
22982 if (bz._init_block()) {
22983 var start = outputStream.pos;
22984 bz._read_bunzip();
22985 callback(position, outputStream.pos - start);
22986 } else {
22987 bz.reader.read(32); // (but we ignore the crc)
22988 if (multistream &&
22989 'eof' in inputStream &&
22990 !inputStream.eof()) {
22991 // note that start_bunzip will also resync the bit reader to next byte
22992 bz._start_bunzip(inputStream, outputStream);
22993 console.assert(bz.dbufSize === blockSize,
22994 "shouldn't change block size within multistream file");
22995 } else break;
22996 }
22997 }
22998};
22999
23000var lib = {
23001 Bunzip,
23002 Stream: stream,
23003 Err,
23004 decode: decode$2,
23005 decodeBlock,
23006 table
23007};
23008var lib_4 = lib.decode;
23009
23010// GPG4Browsers - An OpenPGP implementation in javascript
23011
23012/**
23013 * Implementation of the Literal Data Packet (Tag 11)
23014 *
23015 * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:
23016 * A Literal Data packet contains the body of a message; data that is not to be
23017 * further interpreted.
23018 */
23019class LiteralDataPacket {
23020 static get tag() {
23021 return enums.packet.literalData;
23022 }
23023
23024 /**
23025 * @param {Date} date - The creation date of the literal package
23026 */
23027 constructor(date = new Date()) {
23028 this.format = enums.literal.utf8; // default format for literal data packets
23029 this.date = util.normalizeDate(date);
23030 this.text = null; // textual data representation
23031 this.data = null; // literal data representation
23032 this.filename = '';
23033 }
23034
23035 /**
23036 * Set the packet data to a javascript native string, end of line
23037 * will be normalized to \r\n and by default text is converted to UTF8
23038 * @param {String | ReadableStream<String>} text - Any native javascript string
23039 * @param {enums.literal} [format] - The format of the string of bytes
23040 */
23041 setText(text, format = enums.literal.utf8) {
23042 this.format = format;
23043 this.text = text;
23044 this.data = null;
23045 }
23046
23047 /**
23048 * Returns literal data packets as native JavaScript string
23049 * with normalized end of line to \n
23050 * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again
23051 * @returns {String | ReadableStream<String>} Literal data as text.
23052 */
23053 getText(clone = false) {
23054 if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read
23055 this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));
23056 }
23057 return this.text;
23058 }
23059
23060 /**
23061 * Set the packet data to value represented by the provided string of bytes.
23062 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - The string of bytes
23063 * @param {enums.literal} format - The format of the string of bytes
23064 */
23065 setBytes(bytes, format) {
23066 this.format = format;
23067 this.data = bytes;
23068 this.text = null;
23069 }
23070
23071
23072 /**
23073 * Get the byte sequence representing the literal packet data
23074 * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again
23075 * @returns {Uint8Array | ReadableStream<Uint8Array>} A sequence of bytes.
23076 */
23077 getBytes(clone = false) {
23078 if (this.data === null) {
23079 // encode UTF8 and normalize EOL to \r\n
23080 this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));
23081 }
23082 if (clone) {
23083 return passiveClone(this.data);
23084 }
23085 return this.data;
23086 }
23087
23088
23089 /**
23090 * Sets the filename of the literal packet data
23091 * @param {String} filename - Any native javascript string
23092 */
23093 setFilename(filename) {
23094 this.filename = filename;
23095 }
23096
23097
23098 /**
23099 * Get the filename of the literal packet data
23100 * @returns {String} Filename.
23101 */
23102 getFilename() {
23103 return this.filename;
23104 }
23105
23106 /**
23107 * Parsing function for a literal data packet (tag 11).
23108 *
23109 * @param {Uint8Array | ReadableStream<Uint8Array>} input - Payload of a tag 11 packet
23110 * @returns {Promise<LiteralDataPacket>} Object representation.
23111 * @async
23112 */
23113 async read(bytes) {
23114 await parse(bytes, async reader => {
23115 // - A one-octet field that describes how the data is formatted.
23116 const format = await reader.readByte(); // enums.literal
23117
23118 const filename_len = await reader.readByte();
23119 this.filename = util.decodeUTF8(await reader.readBytes(filename_len));
23120
23121 this.date = util.readDate(await reader.readBytes(4));
23122
23123 let data = reader.remainder();
23124 if (isArrayStream(data)) data = await readToEnd(data);
23125 this.setBytes(data, format);
23126 });
23127 }
23128
23129 /**
23130 * Creates a Uint8Array representation of the packet, excluding the data
23131 *
23132 * @returns {Uint8Array} Uint8Array representation of the packet.
23133 */
23134 writeHeader() {
23135 const filename = util.encodeUTF8(this.filename);
23136 const filename_length = new Uint8Array([filename.length]);
23137
23138 const format = new Uint8Array([this.format]);
23139 const date = util.writeDate(this.date);
23140
23141 return util.concatUint8Array([format, filename_length, filename, date]);
23142 }
23143
23144 /**
23145 * Creates a Uint8Array representation of the packet
23146 *
23147 * @returns {Uint8Array | ReadableStream<Uint8Array>} Uint8Array representation of the packet.
23148 */
23149 write() {
23150 const header = this.writeHeader();
23151 const data = this.getBytes();
23152
23153 return util.concat([header, data]);
23154 }
23155}
23156
23157// GPG4Browsers - An OpenPGP implementation in javascript
23158
23159// Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.
23160const verified = Symbol('verified');
23161
23162// GPG puts the Issuer and Signature subpackets in the unhashed area.
23163// Tampering with those invalidates the signature, so we still trust them and parse them.
23164// All other unhashed subpackets are ignored.
23165const allowedUnhashedSubpackets = new Set([
23166 enums.signatureSubpacket.issuer,
23167 enums.signatureSubpacket.issuerFingerprint,
23168 enums.signatureSubpacket.embeddedSignature
23169]);
23170
23171/**
23172 * Implementation of the Signature Packet (Tag 2)
23173 *
23174 * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:
23175 * A Signature packet describes a binding between some public key and
23176 * some data. The most common signatures are a signature of a file or a
23177 * block of text, and a signature that is a certification of a User ID.
23178 */
23179class SignaturePacket {
23180 static get tag() {
23181 return enums.packet.signature;
23182 }
23183
23184 constructor() {
23185 this.version = null;
23186 /** @type {enums.signature} */
23187 this.signatureType = null;
23188 /** @type {enums.hash} */
23189 this.hashAlgorithm = null;
23190 /** @type {enums.publicKey} */
23191 this.publicKeyAlgorithm = null;
23192
23193 this.signatureData = null;
23194 this.unhashedSubpackets = [];
23195 this.signedHashValue = null;
23196
23197 this.created = null;
23198 this.signatureExpirationTime = null;
23199 this.signatureNeverExpires = true;
23200 this.exportable = null;
23201 this.trustLevel = null;
23202 this.trustAmount = null;
23203 this.regularExpression = null;
23204 this.revocable = null;
23205 this.keyExpirationTime = null;
23206 this.keyNeverExpires = null;
23207 this.preferredSymmetricAlgorithms = null;
23208 this.revocationKeyClass = null;
23209 this.revocationKeyAlgorithm = null;
23210 this.revocationKeyFingerprint = null;
23211 this.issuerKeyID = new KeyID();
23212 this.rawNotations = [];
23213 this.notations = {};
23214 this.preferredHashAlgorithms = null;
23215 this.preferredCompressionAlgorithms = null;
23216 this.keyServerPreferences = null;
23217 this.preferredKeyServer = null;
23218 this.isPrimaryUserID = null;
23219 this.policyURI = null;
23220 this.keyFlags = null;
23221 this.signersUserID = null;
23222 this.reasonForRevocationFlag = null;
23223 this.reasonForRevocationString = null;
23224 this.features = null;
23225 this.signatureTargetPublicKeyAlgorithm = null;
23226 this.signatureTargetHashAlgorithm = null;
23227 this.signatureTargetHash = null;
23228 this.embeddedSignature = null;
23229 this.issuerKeyVersion = null;
23230 this.issuerFingerprint = null;
23231 this.preferredAEADAlgorithms = null;
23232
23233 this.revoked = null;
23234 this[verified] = null;
23235 }
23236
23237 /**
23238 * parsing function for a signature packet (tag 2).
23239 * @param {String} bytes - Payload of a tag 2 packet
23240 * @returns {SignaturePacket} Object representation.
23241 */
23242 read(bytes) {
23243 let i = 0;
23244 this.version = bytes[i++];
23245
23246 if (this.version !== 4 && this.version !== 5) {
23247 throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);
23248 }
23249
23250 this.signatureType = bytes[i++];
23251 this.publicKeyAlgorithm = bytes[i++];
23252 this.hashAlgorithm = bytes[i++];
23253
23254 // hashed subpackets
23255 i += this.readSubPackets(bytes.subarray(i, bytes.length), true);
23256 if (!this.created) {
23257 throw new Error('Missing signature creation time subpacket.');
23258 }
23259
23260 // A V4 signature hashes the packet body
23261 // starting from its first field, the version number, through the end
23262 // of the hashed subpacket data. Thus, the fields hashed are the
23263 // signature version, the signature type, the public-key algorithm, the
23264 // hash algorithm, the hashed subpacket length, and the hashed
23265 // subpacket body.
23266 this.signatureData = bytes.subarray(0, i);
23267
23268 // unhashed subpackets
23269 i += this.readSubPackets(bytes.subarray(i, bytes.length), false);
23270
23271 // Two-octet field holding left 16 bits of signed hash value.
23272 this.signedHashValue = bytes.subarray(i, i + 2);
23273 i += 2;
23274
23275 this.params = mod.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length));
23276 }
23277
23278 /**
23279 * @returns {Uint8Array | ReadableStream<Uint8Array>}
23280 */
23281 writeParams() {
23282 if (this.params instanceof Promise) {
23283 return fromAsync(
23284 async () => mod.serializeParams(this.publicKeyAlgorithm, await this.params)
23285 );
23286 }
23287 return mod.serializeParams(this.publicKeyAlgorithm, this.params);
23288 }
23289
23290 write() {
23291 const arr = [];
23292 arr.push(this.signatureData);
23293 arr.push(this.writeUnhashedSubPackets());
23294 arr.push(this.signedHashValue);
23295 arr.push(this.writeParams());
23296 return util.concat(arr);
23297 }
23298
23299 /**
23300 * Signs provided data. This needs to be done prior to serialization.
23301 * @param {SecretKeyPacket} key - Private key used to sign the message.
23302 * @param {Object} data - Contains packets to be signed.
23303 * @param {Date} [date] - The signature creation time.
23304 * @param {Boolean} [detached] - Whether to create a detached signature
23305 * @throws {Error} if signing failed
23306 * @async
23307 */
23308 async sign(key, data, date = new Date(), detached = false) {
23309 if (key.version === 5) {
23310 this.version = 5;
23311 } else {
23312 this.version = 4;
23313 }
23314 const arr = [new Uint8Array([this.version, this.signatureType, this.publicKeyAlgorithm, this.hashAlgorithm])];
23315
23316 this.created = util.normalizeDate(date);
23317 this.issuerKeyVersion = key.version;
23318 this.issuerFingerprint = key.getFingerprintBytes();
23319 this.issuerKeyID = key.getKeyID();
23320
23321 // Add hashed subpackets
23322 arr.push(this.writeHashedSubPackets());
23323
23324 // Remove unhashed subpackets, in case some allowed unhashed
23325 // subpackets existed, in order not to duplicate them (in both
23326 // the hashed and unhashed subpackets) when re-signing.
23327 this.unhashedSubpackets = [];
23328
23329 this.signatureData = util.concat(arr);
23330
23331 const toHash = this.toHash(this.signatureType, data, detached);
23332 const hash = await this.hash(this.signatureType, data, toHash, detached);
23333
23334 this.signedHashValue = slice(clone(hash), 0, 2);
23335 const signed = async () => mod.signature.sign(
23336 this.publicKeyAlgorithm, this.hashAlgorithm, key.publicParams, key.privateParams, toHash, await readToEnd(hash)
23337 );
23338 if (util.isStream(hash)) {
23339 this.params = signed();
23340 } else {
23341 this.params = await signed();
23342
23343 // Store the fact that this signature is valid, e.g. for when we call `await
23344 // getLatestValidSignature(this.revocationSignatures, key, data)` later.
23345 // Note that this only holds up if the key and data passed to verify are the
23346 // same as the ones passed to sign.
23347 this[verified] = true;
23348 }
23349 }
23350
23351 /**
23352 * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets
23353 * @returns {Uint8Array} Subpacket data.
23354 */
23355 writeHashedSubPackets() {
23356 const sub = enums.signatureSubpacket;
23357 const arr = [];
23358 let bytes;
23359 if (this.created === null) {
23360 throw new Error('Missing signature creation time');
23361 }
23362 arr.push(writeSubPacket(sub.signatureCreationTime, true, util.writeDate(this.created)));
23363 if (this.signatureExpirationTime !== null) {
23364 arr.push(writeSubPacket(sub.signatureExpirationTime, true, util.writeNumber(this.signatureExpirationTime, 4)));
23365 }
23366 if (this.exportable !== null) {
23367 arr.push(writeSubPacket(sub.exportableCertification, true, new Uint8Array([this.exportable ? 1 : 0])));
23368 }
23369 if (this.trustLevel !== null) {
23370 bytes = new Uint8Array([this.trustLevel, this.trustAmount]);
23371 arr.push(writeSubPacket(sub.trustSignature, true, bytes));
23372 }
23373 if (this.regularExpression !== null) {
23374 arr.push(writeSubPacket(sub.regularExpression, true, this.regularExpression));
23375 }
23376 if (this.revocable !== null) {
23377 arr.push(writeSubPacket(sub.revocable, true, new Uint8Array([this.revocable ? 1 : 0])));
23378 }
23379 if (this.keyExpirationTime !== null) {
23380 arr.push(writeSubPacket(sub.keyExpirationTime, true, util.writeNumber(this.keyExpirationTime, 4)));
23381 }
23382 if (this.preferredSymmetricAlgorithms !== null) {
23383 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));
23384 arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, false, bytes));
23385 }
23386 if (this.revocationKeyClass !== null) {
23387 bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);
23388 bytes = util.concat([bytes, this.revocationKeyFingerprint]);
23389 arr.push(writeSubPacket(sub.revocationKey, false, bytes));
23390 }
23391 if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) {
23392 // If the version of [the] key is greater than 4, this subpacket
23393 // MUST NOT be included in the signature.
23394 arr.push(writeSubPacket(sub.issuer, true, this.issuerKeyID.write()));
23395 }
23396 this.rawNotations.forEach(({ name, value, humanReadable, critical }) => {
23397 bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];
23398 const encodedName = util.encodeUTF8(name);
23399 // 2 octets of name length
23400 bytes.push(util.writeNumber(encodedName.length, 2));
23401 // 2 octets of value length
23402 bytes.push(util.writeNumber(value.length, 2));
23403 bytes.push(encodedName);
23404 bytes.push(value);
23405 bytes = util.concat(bytes);
23406 arr.push(writeSubPacket(sub.notationData, critical, bytes));
23407 });
23408 if (this.preferredHashAlgorithms !== null) {
23409 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));
23410 arr.push(writeSubPacket(sub.preferredHashAlgorithms, false, bytes));
23411 }
23412 if (this.preferredCompressionAlgorithms !== null) {
23413 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));
23414 arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, false, bytes));
23415 }
23416 if (this.keyServerPreferences !== null) {
23417 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));
23418 arr.push(writeSubPacket(sub.keyServerPreferences, false, bytes));
23419 }
23420 if (this.preferredKeyServer !== null) {
23421 arr.push(writeSubPacket(sub.preferredKeyServer, false, util.encodeUTF8(this.preferredKeyServer)));
23422 }
23423 if (this.isPrimaryUserID !== null) {
23424 arr.push(writeSubPacket(sub.primaryUserID, false, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));
23425 }
23426 if (this.policyURI !== null) {
23427 arr.push(writeSubPacket(sub.policyURI, false, util.encodeUTF8(this.policyURI)));
23428 }
23429 if (this.keyFlags !== null) {
23430 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));
23431 arr.push(writeSubPacket(sub.keyFlags, true, bytes));
23432 }
23433 if (this.signersUserID !== null) {
23434 arr.push(writeSubPacket(sub.signersUserID, false, util.encodeUTF8(this.signersUserID)));
23435 }
23436 if (this.reasonForRevocationFlag !== null) {
23437 bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);
23438 arr.push(writeSubPacket(sub.reasonForRevocation, true, bytes));
23439 }
23440 if (this.features !== null) {
23441 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));
23442 arr.push(writeSubPacket(sub.features, false, bytes));
23443 }
23444 if (this.signatureTargetPublicKeyAlgorithm !== null) {
23445 bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];
23446 bytes.push(util.stringToUint8Array(this.signatureTargetHash));
23447 bytes = util.concat(bytes);
23448 arr.push(writeSubPacket(sub.signatureTarget, true, bytes));
23449 }
23450 if (this.embeddedSignature !== null) {
23451 arr.push(writeSubPacket(sub.embeddedSignature, true, this.embeddedSignature.write()));
23452 }
23453 if (this.issuerFingerprint !== null) {
23454 bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];
23455 bytes = util.concat(bytes);
23456 arr.push(writeSubPacket(sub.issuerFingerprint, this.version === 5, bytes));
23457 }
23458 if (this.preferredAEADAlgorithms !== null) {
23459 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));
23460 arr.push(writeSubPacket(sub.preferredAEADAlgorithms, false, bytes));
23461 }
23462
23463 const result = util.concat(arr);
23464 const length = util.writeNumber(result.length, 2);
23465
23466 return util.concat([length, result]);
23467 }
23468
23469 /**
23470 * Creates an Uint8Array containing the unhashed subpackets
23471 * @returns {Uint8Array} Subpacket data.
23472 */
23473 writeUnhashedSubPackets() {
23474 const arr = [];
23475 this.unhashedSubpackets.forEach(data => {
23476 arr.push(writeSimpleLength(data.length));
23477 arr.push(data);
23478 });
23479
23480 const result = util.concat(arr);
23481 const length = util.writeNumber(result.length, 2);
23482
23483 return util.concat([length, result]);
23484 }
23485
23486 // V4 signature sub packets
23487 readSubPacket(bytes, hashed = true) {
23488 let mypos = 0;
23489
23490 // The leftmost bit denotes a "critical" packet
23491 const critical = !!(bytes[mypos] & 0x80);
23492 const type = bytes[mypos] & 0x7F;
23493
23494 if (!hashed) {
23495 this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length));
23496 if (!allowedUnhashedSubpackets.has(type)) {
23497 return;
23498 }
23499 }
23500
23501 mypos++;
23502
23503 // subpacket type
23504 switch (type) {
23505 case enums.signatureSubpacket.signatureCreationTime:
23506 // Signature Creation Time
23507 this.created = util.readDate(bytes.subarray(mypos, bytes.length));
23508 break;
23509 case enums.signatureSubpacket.signatureExpirationTime: {
23510 // Signature Expiration Time in seconds
23511 const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));
23512
23513 this.signatureNeverExpires = seconds === 0;
23514 this.signatureExpirationTime = seconds;
23515
23516 break;
23517 }
23518 case enums.signatureSubpacket.exportableCertification:
23519 // Exportable Certification
23520 this.exportable = bytes[mypos++] === 1;
23521 break;
23522 case enums.signatureSubpacket.trustSignature:
23523 // Trust Signature
23524 this.trustLevel = bytes[mypos++];
23525 this.trustAmount = bytes[mypos++];
23526 break;
23527 case enums.signatureSubpacket.regularExpression:
23528 // Regular Expression
23529 this.regularExpression = bytes[mypos];
23530 break;
23531 case enums.signatureSubpacket.revocable:
23532 // Revocable
23533 this.revocable = bytes[mypos++] === 1;
23534 break;
23535 case enums.signatureSubpacket.keyExpirationTime: {
23536 // Key Expiration Time in seconds
23537 const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));
23538
23539 this.keyExpirationTime = seconds;
23540 this.keyNeverExpires = seconds === 0;
23541
23542 break;
23543 }
23544 case enums.signatureSubpacket.preferredSymmetricAlgorithms:
23545 // Preferred Symmetric Algorithms
23546 this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23547 break;
23548 case enums.signatureSubpacket.revocationKey:
23549 // Revocation Key
23550 // (1 octet of class, 1 octet of public-key algorithm ID, 20
23551 // octets of
23552 // fingerprint)
23553 this.revocationKeyClass = bytes[mypos++];
23554 this.revocationKeyAlgorithm = bytes[mypos++];
23555 this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);
23556 break;
23557
23558 case enums.signatureSubpacket.issuer:
23559 // Issuer
23560 this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));
23561 break;
23562
23563 case enums.signatureSubpacket.notationData: {
23564 // Notation Data
23565 const humanReadable = !!(bytes[mypos] & 0x80);
23566
23567 // We extract key/value tuple from the byte stream.
23568 mypos += 4;
23569 const m = util.readNumber(bytes.subarray(mypos, mypos + 2));
23570 mypos += 2;
23571 const n = util.readNumber(bytes.subarray(mypos, mypos + 2));
23572 mypos += 2;
23573
23574 const name = util.decodeUTF8(bytes.subarray(mypos, mypos + m));
23575 const value = bytes.subarray(mypos + m, mypos + m + n);
23576
23577 this.rawNotations.push({ name, humanReadable, value, critical });
23578
23579 if (humanReadable) {
23580 this.notations[name] = util.decodeUTF8(value);
23581 }
23582 break;
23583 }
23584 case enums.signatureSubpacket.preferredHashAlgorithms:
23585 // Preferred Hash Algorithms
23586 this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23587 break;
23588 case enums.signatureSubpacket.preferredCompressionAlgorithms:
23589 // Preferred Compression Algorithms
23590 this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23591 break;
23592 case enums.signatureSubpacket.keyServerPreferences:
23593 // Key Server Preferences
23594 this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];
23595 break;
23596 case enums.signatureSubpacket.preferredKeyServer:
23597 // Preferred Key Server
23598 this.preferredKeyServer = util.decodeUTF8(bytes.subarray(mypos, bytes.length));
23599 break;
23600 case enums.signatureSubpacket.primaryUserID:
23601 // Primary User ID
23602 this.isPrimaryUserID = bytes[mypos++] !== 0;
23603 break;
23604 case enums.signatureSubpacket.policyURI:
23605 // Policy URI
23606 this.policyURI = util.decodeUTF8(bytes.subarray(mypos, bytes.length));
23607 break;
23608 case enums.signatureSubpacket.keyFlags:
23609 // Key Flags
23610 this.keyFlags = [...bytes.subarray(mypos, bytes.length)];
23611 break;
23612 case enums.signatureSubpacket.signersUserID:
23613 // Signer's User ID
23614 this.signersUserID = util.decodeUTF8(bytes.subarray(mypos, bytes.length));
23615 break;
23616 case enums.signatureSubpacket.reasonForRevocation:
23617 // Reason for Revocation
23618 this.reasonForRevocationFlag = bytes[mypos++];
23619 this.reasonForRevocationString = util.decodeUTF8(bytes.subarray(mypos, bytes.length));
23620 break;
23621 case enums.signatureSubpacket.features:
23622 // Features
23623 this.features = [...bytes.subarray(mypos, bytes.length)];
23624 break;
23625 case enums.signatureSubpacket.signatureTarget: {
23626 // Signature Target
23627 // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)
23628 this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];
23629 this.signatureTargetHashAlgorithm = bytes[mypos++];
23630
23631 const len = mod.getHashByteLength(this.signatureTargetHashAlgorithm);
23632
23633 this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));
23634 break;
23635 }
23636 case enums.signatureSubpacket.embeddedSignature:
23637 // Embedded Signature
23638 this.embeddedSignature = new SignaturePacket();
23639 this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));
23640 break;
23641 case enums.signatureSubpacket.issuerFingerprint:
23642 // Issuer Fingerprint
23643 this.issuerKeyVersion = bytes[mypos++];
23644 this.issuerFingerprint = bytes.subarray(mypos, bytes.length);
23645 if (this.issuerKeyVersion === 5) {
23646 this.issuerKeyID.read(this.issuerFingerprint);
23647 } else {
23648 this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));
23649 }
23650 break;
23651 case enums.signatureSubpacket.preferredAEADAlgorithms:
23652 // Preferred AEAD Algorithms
23653 this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23654 break;
23655 default: {
23656 const err = new Error(`Unknown signature subpacket type ${type}`);
23657 if (critical) {
23658 throw err;
23659 } else {
23660 util.printDebug(err);
23661 }
23662 }
23663 }
23664 }
23665
23666 readSubPackets(bytes, trusted = true, config) {
23667 // Two-octet scalar octet count for following subpacket data.
23668 const subpacketLength = util.readNumber(bytes.subarray(0, 2));
23669
23670 let i = 2;
23671
23672 // subpacket data set (zero or more subpackets)
23673 while (i < 2 + subpacketLength) {
23674 const len = readSimpleLength(bytes.subarray(i, bytes.length));
23675 i += len.offset;
23676
23677 this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);
23678
23679 i += len.len;
23680 }
23681
23682 return i;
23683 }
23684
23685 // Produces data to produce signature on
23686 toSign(type, data) {
23687 const t = enums.signature;
23688
23689 switch (type) {
23690 case t.binary:
23691 if (data.text !== null) {
23692 return util.encodeUTF8(data.getText(true));
23693 }
23694 return data.getBytes(true);
23695
23696 case t.text: {
23697 const bytes = data.getBytes(true);
23698 // normalize EOL to \r\n
23699 return util.canonicalizeEOL(bytes);
23700 }
23701 case t.standalone:
23702 return new Uint8Array(0);
23703
23704 case t.certGeneric:
23705 case t.certPersona:
23706 case t.certCasual:
23707 case t.certPositive:
23708 case t.certRevocation: {
23709 let packet;
23710 let tag;
23711
23712 if (data.userID) {
23713 tag = 0xB4;
23714 packet = data.userID;
23715 } else if (data.userAttribute) {
23716 tag = 0xD1;
23717 packet = data.userAttribute;
23718 } else {
23719 throw new Error('Either a userID or userAttribute packet needs to be ' +
23720 'supplied for certification.');
23721 }
23722
23723 const bytes = packet.write();
23724
23725 return util.concat([this.toSign(t.key, data),
23726 new Uint8Array([tag]),
23727 util.writeNumber(bytes.length, 4),
23728 bytes]);
23729 }
23730 case t.subkeyBinding:
23731 case t.subkeyRevocation:
23732 case t.keyBinding:
23733 return util.concat([this.toSign(t.key, data), this.toSign(t.key, {
23734 key: data.bind
23735 })]);
23736
23737 case t.key:
23738 if (data.key === undefined) {
23739 throw new Error('Key packet is required for this signature.');
23740 }
23741 return data.key.writeForHash(this.version);
23742
23743 case t.keyRevocation:
23744 return this.toSign(t.key, data);
23745 case t.timestamp:
23746 return new Uint8Array(0);
23747 case t.thirdParty:
23748 throw new Error('Not implemented');
23749 default:
23750 throw new Error('Unknown signature type.');
23751 }
23752 }
23753
23754 calculateTrailer(data, detached) {
23755 let length = 0;
23756 return transform(clone(this.signatureData), value => {
23757 length += value.length;
23758 }, () => {
23759 const arr = [];
23760 if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {
23761 if (detached) {
23762 arr.push(new Uint8Array(6));
23763 } else {
23764 arr.push(data.writeHeader());
23765 }
23766 }
23767 arr.push(new Uint8Array([this.version, 0xFF]));
23768 if (this.version === 5) {
23769 arr.push(new Uint8Array(4));
23770 }
23771 arr.push(util.writeNumber(length, 4));
23772 // For v5, this should really be writeNumber(length, 8) rather than the
23773 // hardcoded 4 zero bytes above
23774 return util.concat(arr);
23775 });
23776 }
23777
23778 toHash(signatureType, data, detached = false) {
23779 const bytes = this.toSign(signatureType, data);
23780
23781 return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]);
23782 }
23783
23784 async hash(signatureType, data, toHash, detached = false) {
23785 if (!toHash) toHash = this.toHash(signatureType, data, detached);
23786 return mod.hash.digest(this.hashAlgorithm, toHash);
23787 }
23788
23789 /**
23790 * verifies the signature packet. Note: not all signature types are implemented
23791 * @param {PublicSubkeyPacket|PublicKeyPacket|
23792 * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature
23793 * @param {module:enums.signature} signatureType - Expected signature type
23794 * @param {Uint8Array|Object} data - Data which on the signature applies
23795 * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration
23796 * @param {Boolean} [detached] - Whether to verify a detached signature
23797 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23798 * @throws {Error} if signature validation failed
23799 * @async
23800 */
23801 async verify(key, signatureType, data, date = new Date(), detached = false, config$1 = config) {
23802 if (!this.issuerKeyID.equals(key.getKeyID())) {
23803 throw new Error('Signature was not issued by the given public key');
23804 }
23805 if (this.publicKeyAlgorithm !== key.algorithm) {
23806 throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');
23807 }
23808
23809 const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;
23810 // Cryptographic validity is cached after one successful verification.
23811 // However, for message signatures, we always re-verify, since the passed `data` can change
23812 const skipVerify = this[verified] && !isMessageSignature;
23813 if (!skipVerify) {
23814 let toHash;
23815 let hash;
23816 if (this.hashed) {
23817 hash = await this.hashed;
23818 } else {
23819 toHash = this.toHash(signatureType, data, detached);
23820 hash = await this.hash(signatureType, data, toHash);
23821 }
23822 hash = await readToEnd(hash);
23823 if (this.signedHashValue[0] !== hash[0] ||
23824 this.signedHashValue[1] !== hash[1]) {
23825 throw new Error('Signed digest did not match');
23826 }
23827
23828 this.params = await this.params;
23829
23830 this[verified] = await mod.signature.verify(
23831 this.publicKeyAlgorithm, this.hashAlgorithm, this.params, key.publicParams,
23832 toHash, hash
23833 );
23834
23835 if (!this[verified]) {
23836 throw new Error('Signature verification failed');
23837 }
23838 }
23839
23840 const normDate = util.normalizeDate(date);
23841 if (normDate && this.created > normDate) {
23842 throw new Error('Signature creation time is in the future');
23843 }
23844 if (normDate && normDate >= this.getExpirationTime()) {
23845 throw new Error('Signature is expired');
23846 }
23847 if (config$1.rejectHashAlgorithms.has(this.hashAlgorithm)) {
23848 throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());
23849 }
23850 if (config$1.rejectMessageHashAlgorithms.has(this.hashAlgorithm) &&
23851 [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {
23852 throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, this.hashAlgorithm).toUpperCase());
23853 }
23854 this.rawNotations.forEach(({ name, critical }) => {
23855 if (critical && (config$1.knownNotations.indexOf(name) < 0)) {
23856 throw new Error(`Unknown critical notation: ${name}`);
23857 }
23858 });
23859 if (this.revocationKeyClass !== null) {
23860 throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');
23861 }
23862 }
23863
23864 /**
23865 * Verifies signature expiration date
23866 * @param {Date} [date] - Use the given date for verification instead of the current time
23867 * @returns {Boolean} True if expired.
23868 */
23869 isExpired(date = new Date()) {
23870 const normDate = util.normalizeDate(date);
23871 if (normDate !== null) {
23872 return !(this.created <= normDate && normDate < this.getExpirationTime());
23873 }
23874 return false;
23875 }
23876
23877 /**
23878 * Returns the expiration time of the signature or Infinity if signature does not expire
23879 * @returns {Date | Infinity} Expiration time.
23880 */
23881 getExpirationTime() {
23882 return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);
23883 }
23884}
23885
23886/**
23887 * Creates a Uint8Array representation of a sub signature packet
23888 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}
23889 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}
23890 * @param {Integer} type - Subpacket signature type.
23891 * @param {Boolean} critical - Whether the subpacket should be critical.
23892 * @param {String} data - Data to be included
23893 * @returns {Uint8Array} The signature subpacket.
23894 * @private
23895 */
23896function writeSubPacket(type, critical, data) {
23897 const arr = [];
23898 arr.push(writeSimpleLength(data.length + 1));
23899 arr.push(new Uint8Array([(critical ? 0x80 : 0) | type]));
23900 arr.push(data);
23901 return util.concat(arr);
23902}
23903
23904// GPG4Browsers - An OpenPGP implementation in javascript
23905
23906const VERSION = 3;
23907
23908/**
23909 * Implementation of the One-Pass Signature Packets (Tag 4)
23910 *
23911 * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:
23912 * The One-Pass Signature packet precedes the signed data and contains
23913 * enough information to allow the receiver to begin calculating any
23914 * hashes needed to verify the signature. It allows the Signature
23915 * packet to be placed at the end of the message, so that the signer
23916 * can compute the entire signed message in one pass.
23917 */
23918class OnePassSignaturePacket {
23919 static get tag() {
23920 return enums.packet.onePassSignature;
23921 }
23922
23923 constructor() {
23924 /** A one-octet version number. The current version is 3. */
23925 this.version = null;
23926 /**
23927 * A one-octet signature type.
23928 * Signature types are described in
23929 * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.
23930 * @type {enums.signature}
23931
23932 */
23933 this.signatureType = null;
23934 /**
23935 * A one-octet number describing the hash algorithm used.
23936 * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}
23937 * @type {enums.hash}
23938 */
23939 this.hashAlgorithm = null;
23940 /**
23941 * A one-octet number describing the public-key algorithm used.
23942 * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}
23943 * @type {enums.publicKey}
23944 */
23945 this.publicKeyAlgorithm = null;
23946 /** An eight-octet number holding the Key ID of the signing key. */
23947 this.issuerKeyID = null;
23948 /**
23949 * A one-octet number holding a flag showing whether the signature is nested.
23950 * A zero value indicates that the next packet is another One-Pass Signature packet
23951 * that describes another signature to be applied to the same message data.
23952 */
23953 this.flags = null;
23954 }
23955
23956 /**
23957 * parsing function for a one-pass signature packet (tag 4).
23958 * @param {Uint8Array} bytes - Payload of a tag 4 packet
23959 * @returns {OnePassSignaturePacket} Object representation.
23960 */
23961 read(bytes) {
23962 let mypos = 0;
23963 // A one-octet version number. The current version is 3.
23964 this.version = bytes[mypos++];
23965 if (this.version !== VERSION) {
23966 throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);
23967 }
23968
23969 // A one-octet signature type. Signature types are described in
23970 // Section 5.2.1.
23971 this.signatureType = bytes[mypos++];
23972
23973 // A one-octet number describing the hash algorithm used.
23974 this.hashAlgorithm = bytes[mypos++];
23975
23976 // A one-octet number describing the public-key algorithm used.
23977 this.publicKeyAlgorithm = bytes[mypos++];
23978
23979 // An eight-octet number holding the Key ID of the signing key.
23980 this.issuerKeyID = new KeyID();
23981 this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));
23982 mypos += 8;
23983
23984 // A one-octet number holding a flag showing whether the signature
23985 // is nested. A zero value indicates that the next packet is
23986 // another One-Pass Signature packet that describes another
23987 // signature to be applied to the same message data.
23988 this.flags = bytes[mypos++];
23989 return this;
23990 }
23991
23992 /**
23993 * creates a string representation of a one-pass signature packet
23994 * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.
23995 */
23996 write() {
23997 const start = new Uint8Array([VERSION, this.signatureType, this.hashAlgorithm, this.publicKeyAlgorithm]);
23998
23999 const end = new Uint8Array([this.flags]);
24000
24001 return util.concatUint8Array([start, this.issuerKeyID.write(), end]);
24002 }
24003
24004 calculateTrailer(...args) {
24005 return fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));
24006 }
24007
24008 async verify() {
24009 const correspondingSig = await this.correspondingSig;
24010 if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {
24011 throw new Error('Corresponding signature packet missing');
24012 }
24013 if (
24014 correspondingSig.signatureType !== this.signatureType ||
24015 correspondingSig.hashAlgorithm !== this.hashAlgorithm ||
24016 correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||
24017 !correspondingSig.issuerKeyID.equals(this.issuerKeyID)
24018 ) {
24019 throw new Error('Corresponding signature packet does not match one-pass signature packet');
24020 }
24021 correspondingSig.hashed = this.hashed;
24022 return correspondingSig.verify.apply(correspondingSig, arguments);
24023 }
24024}
24025
24026OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;
24027OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;
24028OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;
24029
24030/**
24031 * Instantiate a new packet given its tag
24032 * @function newPacketFromTag
24033 * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}
24034 * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
24035 * @returns {Object} New packet object with type based on tag
24036 * @throws {Error|UnsupportedError} for disallowed or unknown packets
24037 */
24038function newPacketFromTag(tag, allowedPackets) {
24039 if (!allowedPackets[tag]) {
24040 // distinguish between disallowed packets and unknown ones
24041 let packetType;
24042 try {
24043 packetType = enums.read(enums.packet, tag);
24044 } catch (e) {
24045 throw new UnsupportedError(`Unknown packet type with tag: ${tag}`);
24046 }
24047 throw new Error(`Packet not allowed in this context: ${packetType}`);
24048 }
24049 return new allowedPackets[tag]();
24050}
24051
24052/**
24053 * This class represents a list of openpgp packets.
24054 * Take care when iterating over it - the packets themselves
24055 * are stored as numerical indices.
24056 * @extends Array
24057 */
24058class PacketList extends Array {
24059 /**
24060 * Parses the given binary data and returns a list of packets.
24061 * Equivalent to calling `read` on an empty PacketList instance.
24062 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - binary data to parse
24063 * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
24064 * @param {Object} [config] - full configuration, defaults to openpgp.config
24065 * @returns {PacketList} parsed list of packets
24066 * @throws on parsing errors
24067 * @async
24068 */
24069 static async fromBinary(bytes, allowedPackets, config$1 = config) {
24070 const packets = new PacketList();
24071 await packets.read(bytes, allowedPackets, config$1);
24072 return packets;
24073 }
24074
24075 /**
24076 * Reads a stream of binary data and interprets it as a list of packets.
24077 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - binary data to parse
24078 * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
24079 * @param {Object} [config] - full configuration, defaults to openpgp.config
24080 * @throws on parsing errors
24081 * @async
24082 */
24083 async read(bytes, allowedPackets, config$1 = config) {
24084 if (config$1.additionalAllowedPackets.length) {
24085 allowedPackets = { ...allowedPackets, ...util.constructAllowedPackets(config$1.additionalAllowedPackets) };
24086 }
24087 this.stream = transformPair(bytes, async (readable, writable) => {
24088 const writer = getWriter(writable);
24089 try {
24090 while (true) {
24091 await writer.ready;
24092 const done = await readPackets(readable, async parsed => {
24093 try {
24094 if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust) {
24095 // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed:
24096 // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145
24097 // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10
24098 return;
24099 }
24100 const packet = newPacketFromTag(parsed.tag, allowedPackets);
24101 packet.packets = new PacketList();
24102 packet.fromStream = util.isStream(parsed.packet);
24103 await packet.read(parsed.packet, config$1);
24104 await writer.write(packet);
24105 } catch (e) {
24106 const throwUnsupportedError = !config$1.ignoreUnsupportedPackets && e instanceof UnsupportedError;
24107 const throwMalformedError = !config$1.ignoreMalformedPackets && !(e instanceof UnsupportedError);
24108 if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) {
24109 // The packets that support streaming are the ones that contain message data.
24110 // Those are also the ones we want to be more strict about and throw on parse errors
24111 // (since we likely cannot process the message without these packets anyway).
24112 await writer.abort(e);
24113 } else {
24114 const unparsedPacket = new UnparseablePacket(parsed.tag, parsed.packet);
24115 await writer.write(unparsedPacket);
24116 }
24117 util.printDebugError(e);
24118 }
24119 });
24120 if (done) {
24121 await writer.ready;
24122 await writer.close();
24123 return;
24124 }
24125 }
24126 } catch (e) {
24127 await writer.abort(e);
24128 }
24129 });
24130
24131 // Wait until first few packets have been read
24132 const reader = getReader(this.stream);
24133 while (true) {
24134 const { done, value } = await reader.read();
24135 if (!done) {
24136 this.push(value);
24137 } else {
24138 this.stream = null;
24139 }
24140 if (done || supportsStreaming(value.constructor.tag)) {
24141 break;
24142 }
24143 }
24144 reader.releaseLock();
24145 }
24146
24147 /**
24148 * Creates a binary representation of openpgp objects contained within the
24149 * class instance.
24150 * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.
24151 */
24152 write() {
24153 const arr = [];
24154
24155 for (let i = 0; i < this.length; i++) {
24156 const tag = this[i] instanceof UnparseablePacket ? this[i].tag : this[i].constructor.tag;
24157 const packetbytes = this[i].write();
24158 if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {
24159 let buffer = [];
24160 let bufferLength = 0;
24161 const minLength = 512;
24162 arr.push(writeTag(tag));
24163 arr.push(transform(packetbytes, value => {
24164 buffer.push(value);
24165 bufferLength += value.length;
24166 if (bufferLength >= minLength) {
24167 const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);
24168 const chunkSize = 2 ** powerOf2;
24169 const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));
24170 buffer = [bufferConcat.subarray(1 + chunkSize)];
24171 bufferLength = buffer[0].length;
24172 return bufferConcat.subarray(0, 1 + chunkSize);
24173 }
24174 }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));
24175 } else {
24176 if (util.isStream(packetbytes)) {
24177 let length = 0;
24178 arr.push(transform(clone(packetbytes), value => {
24179 length += value.length;
24180 }, () => writeHeader(tag, length)));
24181 } else {
24182 arr.push(writeHeader(tag, packetbytes.length));
24183 }
24184 arr.push(packetbytes);
24185 }
24186 }
24187
24188 return util.concat(arr);
24189 }
24190
24191 /**
24192 * Creates a new PacketList with all packets matching the given tag(s)
24193 * @param {...module:enums.packet} tags - packet tags to look for
24194 * @returns {PacketList}
24195 */
24196 filterByTag(...tags) {
24197 const filtered = new PacketList();
24198
24199 const handle = tag => packetType => tag === packetType;
24200
24201 for (let i = 0; i < this.length; i++) {
24202 if (tags.some(handle(this[i].constructor.tag))) {
24203 filtered.push(this[i]);
24204 }
24205 }
24206
24207 return filtered;
24208 }
24209
24210 /**
24211 * Traverses packet list and returns first packet with matching tag
24212 * @param {module:enums.packet} tag - The packet tag
24213 * @returns {Packet|undefined}
24214 */
24215 findPacket(tag) {
24216 return this.find(packet => packet.constructor.tag === tag);
24217 }
24218
24219 /**
24220 * Find indices of packets with the given tag(s)
24221 * @param {...module:enums.packet} tags - packet tags to look for
24222 * @returns {Integer[]} packet indices
24223 */
24224 indexOfTag(...tags) {
24225 const tagIndex = [];
24226 const that = this;
24227
24228 const handle = tag => packetType => tag === packetType;
24229
24230 for (let i = 0; i < this.length; i++) {
24231 if (tags.some(handle(that[i].constructor.tag))) {
24232 tagIndex.push(i);
24233 }
24234 }
24235 return tagIndex;
24236 }
24237}
24238
24239// GPG4Browsers - An OpenPGP implementation in javascript
24240
24241// A Compressed Data packet can contain the following packet types
24242const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([
24243 LiteralDataPacket,
24244 OnePassSignaturePacket,
24245 SignaturePacket
24246]);
24247
24248/**
24249 * Implementation of the Compressed Data Packet (Tag 8)
24250 *
24251 * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:
24252 * The Compressed Data packet contains compressed data. Typically,
24253 * this packet is found as the contents of an encrypted packet, or following
24254 * a Signature or One-Pass Signature packet, and contains a literal data packet.
24255 */
24256class CompressedDataPacket {
24257 static get tag() {
24258 return enums.packet.compressedData;
24259 }
24260
24261 /**
24262 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24263 */
24264 constructor(config$1 = config) {
24265 /**
24266 * List of packets
24267 * @type {PacketList}
24268 */
24269 this.packets = null;
24270 /**
24271 * Compression algorithm
24272 * @type {enums.compression}
24273 */
24274 this.algorithm = config$1.preferredCompressionAlgorithm;
24275
24276 /**
24277 * Compressed packet data
24278 * @type {Uint8Array | ReadableStream<Uint8Array>}
24279 */
24280 this.compressed = null;
24281
24282 /**
24283 * zip/zlib compression level, between 1 and 9
24284 */
24285 this.deflateLevel = config$1.deflateLevel;
24286 }
24287
24288 /**
24289 * Parsing function for the packet.
24290 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - Payload of a tag 8 packet
24291 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24292 */
24293 async read(bytes, config$1 = config) {
24294 await parse(bytes, async reader => {
24295
24296 // One octet that gives the algorithm used to compress the packet.
24297 this.algorithm = await reader.readByte();
24298
24299 // Compressed data, which makes up the remainder of the packet.
24300 this.compressed = reader.remainder();
24301
24302 await this.decompress(config$1);
24303 });
24304 }
24305
24306
24307 /**
24308 * Return the compressed packet.
24309 * @returns {Uint8Array | ReadableStream<Uint8Array>} Binary compressed packet.
24310 */
24311 write() {
24312 if (this.compressed === null) {
24313 this.compress();
24314 }
24315
24316 return util.concat([new Uint8Array([this.algorithm]), this.compressed]);
24317 }
24318
24319
24320 /**
24321 * Decompression method for decompressing the compressed data
24322 * read by read_packet
24323 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24324 */
24325 async decompress(config$1 = config) {
24326 const compressionName = enums.read(enums.compression, this.algorithm);
24327 const decompressionFn = decompress_fns[compressionName];
24328 if (!decompressionFn) {
24329 throw new Error(`${compressionName} decompression not supported`);
24330 }
24331
24332 this.packets = await PacketList.fromBinary(decompressionFn(this.compressed), allowedPackets, config$1);
24333 }
24334
24335 /**
24336 * Compress the packet data (member decompressedData)
24337 */
24338 compress() {
24339 const compressionName = enums.read(enums.compression, this.algorithm);
24340 const compressionFn = compress_fns[compressionName];
24341 if (!compressionFn) {
24342 throw new Error(`${compressionName} compression not supported`);
24343 }
24344
24345 this.compressed = compressionFn(this.packets.write(), this.deflateLevel);
24346 }
24347}
24348
24349//////////////////////////
24350// //
24351// Helper functions //
24352// //
24353//////////////////////////
24354
24355
24356const nodeZlib = util.getNodeZlib();
24357
24358function uncompressed(data) {
24359 return data;
24360}
24361
24362function node_zlib(func, create, options = {}) {
24363 return function (data) {
24364 if (!util.isStream(data) || isArrayStream(data)) {
24365 return fromAsync(() => readToEnd(data).then(data => {
24366 return new Promise((resolve, reject) => {
24367 func(data, options, (err, result) => {
24368 if (err) return reject(err);
24369 resolve(result);
24370 });
24371 });
24372 }));
24373 }
24374 return nodeToWeb(webToNode(data).pipe(create(options)));
24375 };
24376}
24377
24378function pako_zlib(constructor, options = {}) {
24379 return function(data) {
24380 const obj = new constructor(options);
24381 return transform(data, value => {
24382 if (value.length) {
24383 obj.push(value, Z_SYNC_FLUSH);
24384 return obj.result;
24385 }
24386 }, () => {
24387 if (constructor === Deflate) {
24388 obj.push([], Z_FINISH);
24389 return obj.result;
24390 }
24391 });
24392 };
24393}
24394
24395function bzip2(func) {
24396 return function(data) {
24397 return fromAsync(async () => func(await readToEnd(data)));
24398 };
24399}
24400
24401const compress_fns = nodeZlib ? {
24402 zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflateRaw, nodeZlib.createDeflateRaw, { level })(compressed),
24403 zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflate, nodeZlib.createDeflate, { level })(compressed)
24404} : {
24405 zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed),
24406 zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed)
24407};
24408
24409const decompress_fns = nodeZlib ? {
24410 uncompressed: uncompressed,
24411 zip: /*#__PURE__*/ node_zlib(nodeZlib.inflateRaw, nodeZlib.createInflateRaw),
24412 zlib: /*#__PURE__*/ node_zlib(nodeZlib.inflate, nodeZlib.createInflate),
24413 bzip2: /*#__PURE__*/ bzip2(lib_4)
24414} : {
24415 uncompressed: uncompressed,
24416 zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }),
24417 zlib: /*#__PURE__*/ pako_zlib(Inflate),
24418 bzip2: /*#__PURE__*/ bzip2(lib_4)
24419};
24420
24421// GPG4Browsers - An OpenPGP implementation in javascript
24422
24423// A SEIP packet can contain the following packet types
24424const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([
24425 LiteralDataPacket,
24426 CompressedDataPacket,
24427 OnePassSignaturePacket,
24428 SignaturePacket
24429]);
24430
24431const VERSION$1 = 1; // A one-octet version number of the data packet.
24432
24433/**
24434 * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)
24435 *
24436 * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:
24437 * The Symmetrically Encrypted Integrity Protected Data packet is
24438 * a variant of the Symmetrically Encrypted Data packet. It is a new feature
24439 * created for OpenPGP that addresses the problem of detecting a modification to
24440 * encrypted data. It is used in combination with a Modification Detection Code
24441 * packet.
24442 */
24443class SymEncryptedIntegrityProtectedDataPacket {
24444 static get tag() {
24445 return enums.packet.symEncryptedIntegrityProtectedData;
24446 }
24447
24448 constructor() {
24449 this.version = VERSION$1;
24450 this.encrypted = null;
24451 this.packets = null;
24452 }
24453
24454 async read(bytes) {
24455 await parse(bytes, async reader => {
24456 const version = await reader.readByte();
24457 // - A one-octet version number. The only currently defined value is 1.
24458 if (version !== VERSION$1) {
24459 throw new UnsupportedError(`Version ${version} of the SEIP packet is unsupported.`);
24460 }
24461
24462 // - Encrypted data, the output of the selected symmetric-key cipher
24463 // operating in Cipher Feedback mode with shift amount equal to the
24464 // block size of the cipher (CFB-n where n is the block size).
24465 this.encrypted = reader.remainder();
24466 });
24467 }
24468
24469 write() {
24470 return util.concat([new Uint8Array([VERSION$1]), this.encrypted]);
24471 }
24472
24473 /**
24474 * Encrypt the payload in the packet.
24475 * @param {enums.symmetric} sessionKeyAlgorithm - The symmetric encryption algorithm to use
24476 * @param {Uint8Array} key - The key of cipher blocksize length to be used
24477 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24478 * @returns {Promise<Boolean>}
24479 * @throws {Error} on encryption failure
24480 * @async
24481 */
24482 async encrypt(sessionKeyAlgorithm, key, config$1 = config) {
24483 const { blockSize } = mod.getCipher(sessionKeyAlgorithm);
24484
24485 let bytes = this.packets.write();
24486 if (isArrayStream(bytes)) bytes = await readToEnd(bytes);
24487 const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm);
24488 const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet
24489
24490 const tohash = util.concat([prefix, bytes, mdc]);
24491 const hash = await mod.hash.sha1(passiveClone(tohash));
24492 const plaintext = util.concat([tohash, hash]);
24493
24494 this.encrypted = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(blockSize), config$1);
24495 return true;
24496 }
24497
24498 /**
24499 * Decrypts the encrypted data contained in the packet.
24500 * @param {enums.symmetric} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used
24501 * @param {Uint8Array} key - The key of cipher blocksize length to be used
24502 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24503 * @returns {Promise<Boolean>}
24504 * @throws {Error} on decryption failure
24505 * @async
24506 */
24507 async decrypt(sessionKeyAlgorithm, key, config$1 = config) {
24508 const { blockSize } = mod.getCipher(sessionKeyAlgorithm);
24509 let encrypted = clone(this.encrypted);
24510 if (isArrayStream(encrypted)) encrypted = await readToEnd(encrypted);
24511 const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(blockSize));
24512
24513 // there must be a modification detection code packet as the
24514 // last packet and everything gets hashed except the hash itself
24515 const realHash = slice(passiveClone(decrypted), -20);
24516 const tohash = slice(decrypted, 0, -20);
24517 const verifyHash = Promise.all([
24518 readToEnd(await mod.hash.sha1(passiveClone(tohash))),
24519 readToEnd(realHash)
24520 ]).then(([hash, mdc]) => {
24521 if (!util.equalsUint8Array(hash, mdc)) {
24522 throw new Error('Modification detected.');
24523 }
24524 return new Uint8Array();
24525 });
24526 const bytes = slice(tohash, blockSize + 2); // Remove random prefix
24527 let packetbytes = slice(bytes, 0, -2); // Remove MDC packet
24528 packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]);
24529 if (!util.isStream(encrypted) || !config$1.allowUnauthenticatedStream) {
24530 packetbytes = await readToEnd(packetbytes);
24531 }
24532 this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$1, config$1);
24533 return true;
24534 }
24535}
24536
24537// OpenPGP.js - An OpenPGP implementation in javascript
24538
24539// An AEAD-encrypted Data packet can contain the following packet types
24540const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([
24541 LiteralDataPacket,
24542 CompressedDataPacket,
24543 OnePassSignaturePacket,
24544 SignaturePacket
24545]);
24546
24547const VERSION$2 = 1; // A one-octet version number of the data packet.
24548
24549/**
24550 * Implementation of the Symmetrically Encrypted Authenticated Encryption with
24551 * Additional Data (AEAD) Protected Data Packet
24552 *
24553 * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:
24554 * AEAD Protected Data Packet
24555 */
24556class AEADEncryptedDataPacket {
24557 static get tag() {
24558 return enums.packet.aeadEncryptedData;
24559 }
24560
24561 constructor() {
24562 this.version = VERSION$2;
24563 /** @type {enums.symmetric} */
24564 this.cipherAlgorithm = null;
24565 /** @type {enums.aead} */
24566 this.aeadAlgorithm = enums.aead.eax;
24567 this.chunkSizeByte = null;
24568 this.iv = null;
24569 this.encrypted = null;
24570 this.packets = null;
24571 }
24572
24573 /**
24574 * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
24575 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes
24576 * @throws {Error} on parsing failure
24577 */
24578 async read(bytes) {
24579 await parse(bytes, async reader => {
24580 const version = await reader.readByte();
24581 if (version !== VERSION$2) { // The only currently defined value is 1.
24582 throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);
24583 }
24584 this.cipherAlgorithm = await reader.readByte();
24585 this.aeadAlgorithm = await reader.readByte();
24586 this.chunkSizeByte = await reader.readByte();
24587
24588 const mode = mod.getAEADMode(this.aeadAlgorithm);
24589 this.iv = await reader.readBytes(mode.ivLength);
24590 this.encrypted = reader.remainder();
24591 });
24592 }
24593
24594 /**
24595 * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
24596 * @returns {Uint8Array | ReadableStream<Uint8Array>} The encrypted payload.
24597 */
24598 write() {
24599 return util.concat([new Uint8Array([this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte]), this.iv, this.encrypted]);
24600 }
24601
24602 /**
24603 * Decrypt the encrypted payload.
24604 * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm
24605 * @param {Uint8Array} key - The session key used to encrypt the payload
24606 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24607 * @throws {Error} if decryption was not successful
24608 * @async
24609 */
24610 async decrypt(sessionKeyAlgorithm, key, config$1 = config) {
24611 this.packets = await PacketList.fromBinary(
24612 await this.crypt('decrypt', key, clone(this.encrypted)),
24613 allowedPackets$2,
24614 config$1
24615 );
24616 }
24617
24618 /**
24619 * Encrypt the packet payload.
24620 * @param {enums.symmetric} sessionKeyAlgorithm - The session key's cipher algorithm
24621 * @param {Uint8Array} key - The session key used to encrypt the payload
24622 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24623 * @throws {Error} if encryption was not successful
24624 * @async
24625 */
24626 async encrypt(sessionKeyAlgorithm, key, config$1 = config) {
24627 this.cipherAlgorithm = sessionKeyAlgorithm;
24628
24629 const { ivLength } = mod.getAEADMode(this.aeadAlgorithm);
24630 this.iv = mod.random.getRandomBytes(ivLength); // generate new random IV
24631 this.chunkSizeByte = config$1.aeadChunkSizeByte;
24632 const data = this.packets.write();
24633 this.encrypted = await this.crypt('encrypt', key, data);
24634 }
24635
24636 /**
24637 * En/decrypt the payload.
24638 * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt
24639 * @param {Uint8Array} key - The session key used to en/decrypt the payload
24640 * @param {Uint8Array | ReadableStream<Uint8Array>} data - The data to en/decrypt
24641 * @returns {Promise<Uint8Array | ReadableStream<Uint8Array>>}
24642 * @async
24643 */
24644 async crypt(fn, key, data) {
24645 const mode = mod.getAEADMode(this.aeadAlgorithm);
24646 const modeInstance = await mode(this.cipherAlgorithm, key);
24647 const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;
24648 const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;
24649 const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))
24650 const adataBuffer = new ArrayBuffer(21);
24651 const adataArray = new Uint8Array(adataBuffer, 0, 13);
24652 const adataTagArray = new Uint8Array(adataBuffer);
24653 const adataView = new DataView(adataBuffer);
24654 const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);
24655 adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgorithm, this.aeadAlgorithm, this.chunkSizeByte], 0);
24656 let chunkIndex = 0;
24657 let latestPromise = Promise.resolve();
24658 let cryptedBytes = 0;
24659 let queuedBytes = 0;
24660 const iv = this.iv;
24661 return transformPair(data, async (readable, writable) => {
24662 if (util.isStream(readable) !== 'array') {
24663 const buffer = new TransformStream({}, {
24664 highWaterMark: util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6),
24665 size: array => array.length
24666 });
24667 pipe(buffer.readable, writable);
24668 writable = buffer.writable;
24669 }
24670 const reader = getReader(readable);
24671 const writer = getWriter(writable);
24672 try {
24673 while (true) {
24674 let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();
24675 const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);
24676 chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);
24677 let cryptedPromise;
24678 let done;
24679 if (!chunkIndex || chunk.length) {
24680 reader.unshift(finalChunk);
24681 cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray);
24682 queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;
24683 } else {
24684 // After the last chunk, we either encrypt a final, empty
24685 // data chunk to get the final authentication tag or
24686 // validate that final authentication tag.
24687 adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...)
24688 cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray);
24689 queuedBytes += tagLengthIfEncrypting;
24690 done = true;
24691 }
24692 cryptedBytes += chunk.length - tagLengthIfDecrypting;
24693 // eslint-disable-next-line no-loop-func
24694 latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {
24695 await writer.ready;
24696 await writer.write(crypted);
24697 queuedBytes -= crypted.length;
24698 }).catch(err => writer.abort(err));
24699 if (done || queuedBytes > writer.desiredSize) {
24700 await latestPromise; // Respect backpressure
24701 }
24702 if (!done) {
24703 adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)
24704 } else {
24705 await writer.close();
24706 break;
24707 }
24708 }
24709 } catch (e) {
24710 await writer.abort(e);
24711 }
24712 });
24713 }
24714}
24715
24716// GPG4Browsers - An OpenPGP implementation in javascript
24717
24718const VERSION$3 = 3;
24719
24720/**
24721 * Public-Key Encrypted Session Key Packets (Tag 1)
24722 *
24723 * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:
24724 * A Public-Key Encrypted Session Key packet holds the session key
24725 * used to encrypt a message. Zero or more Public-Key Encrypted Session Key
24726 * packets and/or Symmetric-Key Encrypted Session Key packets may precede a
24727 * Symmetrically Encrypted Data Packet, which holds an encrypted message. The
24728 * message is encrypted with the session key, and the session key is itself
24729 * encrypted and stored in the Encrypted Session Key packet(s). The
24730 * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted
24731 * Session Key packet for each OpenPGP key to which the message is encrypted.
24732 * The recipient of the message finds a session key that is encrypted to their
24733 * public key, decrypts the session key, and then uses the session key to
24734 * decrypt the message.
24735 */
24736class PublicKeyEncryptedSessionKeyPacket {
24737 static get tag() {
24738 return enums.packet.publicKeyEncryptedSessionKey;
24739 }
24740
24741 constructor() {
24742 this.version = 3;
24743
24744 this.publicKeyID = new KeyID();
24745 this.publicKeyAlgorithm = null;
24746
24747 this.sessionKey = null;
24748 /**
24749 * Algorithm to encrypt the message with
24750 * @type {enums.symmetric}
24751 */
24752 this.sessionKeyAlgorithm = null;
24753
24754 /** @type {Object} */
24755 this.encrypted = {};
24756 }
24757
24758 /**
24759 * Parsing function for a publickey encrypted session key packet (tag 1).
24760 *
24761 * @param {Uint8Array} bytes - Payload of a tag 1 packet
24762 */
24763 read(bytes) {
24764 let i = 0;
24765 this.version = bytes[i++];
24766 if (this.version !== VERSION$3) {
24767 throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);
24768 }
24769 i += this.publicKeyID.read(bytes.subarray(i));
24770 this.publicKeyAlgorithm = bytes[i++];
24771 this.encrypted = mod.parseEncSessionKeyParams(this.publicKeyAlgorithm, bytes.subarray(i), this.version);
24772 if (this.publicKeyAlgorithm === enums.publicKey.x25519) {
24773 this.sessionKeyAlgorithm = enums.write(enums.symmetric, this.encrypted.C.algorithm);
24774 }
24775 }
24776
24777 /**
24778 * Create a binary representation of a tag 1 packet
24779 *
24780 * @returns {Uint8Array} The Uint8Array representation.
24781 */
24782 write() {
24783 const arr = [
24784 new Uint8Array([this.version]),
24785 this.publicKeyID.write(),
24786 new Uint8Array([this.publicKeyAlgorithm]),
24787 mod.serializeParams(this.publicKeyAlgorithm, this.encrypted)
24788 ];
24789
24790 return util.concatUint8Array(arr);
24791 }
24792
24793 /**
24794 * Encrypt session key packet
24795 * @param {PublicKeyPacket} key - Public key
24796 * @throws {Error} if encryption failed
24797 * @async
24798 */
24799 async encrypt(key) {
24800 const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);
24801 const encoded = encodeSessionKey(this.version, algo, this.sessionKeyAlgorithm, this.sessionKey);
24802 this.encrypted = await mod.publicKeyEncrypt(
24803 algo, this.sessionKeyAlgorithm, key.publicParams, encoded, key.getFingerprintBytes());
24804 }
24805
24806 /**
24807 * Decrypts the session key (only for public key encrypted session key packets (tag 1)
24808 * @param {SecretKeyPacket} key - decrypted private key
24809 * @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.
24810 * This is needed for constant-time processing. Expected object of the form: { sessionKey: Uint8Array, sessionKeyAlgorithm: enums.symmetric }
24811 * @throws {Error} if decryption failed, unless `randomSessionKey` is given
24812 * @async
24813 */
24814 async decrypt(key, randomSessionKey) {
24815 // check that session key algo matches the secret key algo
24816 if (this.publicKeyAlgorithm !== key.algorithm) {
24817 throw new Error('Decryption error');
24818 }
24819
24820 const randomPayload = randomSessionKey ?
24821 encodeSessionKey(this.version, this.publicKeyAlgorithm, randomSessionKey.sessionKeyAlgorithm, randomSessionKey.sessionKey) :
24822 null;
24823 const decryptedData = await mod.publicKeyDecrypt(this.publicKeyAlgorithm, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes(), randomPayload);
24824
24825 const { sessionKey, sessionKeyAlgorithm } = decodeSessionKey(this.version, this.publicKeyAlgorithm, decryptedData, randomSessionKey);
24826
24827 // v3 Montgomery curves have cleartext cipher algo
24828 if (this.publicKeyAlgorithm !== enums.publicKey.x25519) {
24829 this.sessionKeyAlgorithm = sessionKeyAlgorithm;
24830 }
24831 this.sessionKey = sessionKey;
24832 }
24833}
24834
24835
24836function encodeSessionKey(version, keyAlgo, cipherAlgo, sessionKeyData) {
24837 switch (keyAlgo) {
24838 case enums.publicKey.rsaEncrypt:
24839 case enums.publicKey.rsaEncryptSign:
24840 case enums.publicKey.elgamal:
24841 case enums.publicKey.ecdh: {
24842 // add checksum
24843 return util.concatUint8Array([
24844 new Uint8Array([cipherAlgo]),
24845 sessionKeyData,
24846 util.writeChecksum(sessionKeyData.subarray(sessionKeyData.length % 8))
24847 ]);
24848 }
24849 case enums.publicKey.x25519:
24850 return sessionKeyData;
24851 default:
24852 throw new Error('Unsupported public key algorithm');
24853 }
24854}
24855
24856
24857function decodeSessionKey(version, keyAlgo, decryptedData, randomSessionKey) {
24858 switch (keyAlgo) {
24859 case enums.publicKey.rsaEncrypt:
24860 case enums.publicKey.rsaEncryptSign:
24861 case enums.publicKey.elgamal:
24862 case enums.publicKey.ecdh: {
24863 // verify checksum in constant time
24864 const result = decryptedData.subarray(0, decryptedData.length - 2);
24865 const checksum = decryptedData.subarray(decryptedData.length - 2);
24866 const computedChecksum = util.writeChecksum(result.subarray(result.length % 8));
24867 const isValidChecksum = computedChecksum[0] === checksum[0] & computedChecksum[1] === checksum[1];
24868 const decryptedSessionKey = { sessionKeyAlgorithm: result[0], sessionKey: result.subarray(1) };
24869 if (randomSessionKey) {
24870 // We must not leak info about the validity of the decrypted checksum or cipher algo.
24871 // 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.
24872 const isValidPayload = isValidChecksum &
24873 decryptedSessionKey.sessionKeyAlgorithm === randomSessionKey.sessionKeyAlgorithm &
24874 decryptedSessionKey.sessionKey.length === randomSessionKey.sessionKey.length;
24875 return {
24876 sessionKey: util.selectUint8Array(isValidPayload, decryptedSessionKey.sessionKey, randomSessionKey.sessionKey),
24877 sessionKeyAlgorithm: util.selectUint8(
24878 isValidPayload,
24879 decryptedSessionKey.sessionKeyAlgorithm,
24880 randomSessionKey.sessionKeyAlgorithm
24881 )
24882 };
24883 } else {
24884 const isValidPayload = isValidChecksum && enums.read(enums.symmetric, decryptedSessionKey.sessionKeyAlgorithm);
24885 if (isValidPayload) {
24886 return decryptedSessionKey;
24887 } else {
24888 throw new Error('Decryption error');
24889 }
24890 }
24891 }
24892 case enums.publicKey.x25519:
24893 return {
24894 sessionKey: decryptedData
24895 };
24896 default:
24897 throw new Error('Unsupported public key algorithm');
24898 }
24899}
24900
24901// GPG4Browsers - An OpenPGP implementation in javascript
24902
24903class S2K {
24904 /**
24905 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24906 */
24907 constructor(config$1 = config) {
24908 /**
24909 * Hash function identifier, or 0 for gnu-dummy keys
24910 * @type {module:enums.hash | 0}
24911 */
24912 this.algorithm = enums.hash.sha256;
24913 /**
24914 * enums.s2k identifier or 'gnu-dummy'
24915 * @type {String}
24916 */
24917 this.type = 'iterated';
24918 /** @type {Integer} */
24919 this.c = config$1.s2kIterationCountByte;
24920 /** Eight bytes of salt in a binary string.
24921 * @type {Uint8Array}
24922 */
24923 this.salt = null;
24924 }
24925
24926 getCount() {
24927 // Exponent bias, defined in RFC4880
24928 const expbias = 6;
24929
24930 return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);
24931 }
24932
24933 /**
24934 * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).
24935 * @param {Uint8Array} bytes - Payload of string-to-key specifier
24936 * @returns {Integer} Actual length of the object.
24937 */
24938 read(bytes) {
24939 let i = 0;
24940 try {
24941 this.type = enums.read(enums.s2k, bytes[i++]);
24942 } catch (err) {
24943 throw new UnsupportedError('Unknown S2K type.');
24944 }
24945 this.algorithm = bytes[i++];
24946
24947 switch (this.type) {
24948 case 'simple':
24949 break;
24950
24951 case 'salted':
24952 this.salt = bytes.subarray(i, i + 8);
24953 i += 8;
24954 break;
24955
24956 case 'iterated':
24957 this.salt = bytes.subarray(i, i + 8);
24958 i += 8;
24959
24960 // Octet 10: count, a one-octet, coded value
24961 this.c = bytes[i++];
24962 break;
24963
24964 case 'gnu':
24965 if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {
24966 i += 3; // GNU
24967 const gnuExtType = 1000 + bytes[i++];
24968 if (gnuExtType === 1001) {
24969 this.type = 'gnu-dummy';
24970 // GnuPG extension mode 1001 -- don't write secret key at all
24971 } else {
24972 throw new UnsupportedError('Unknown s2k gnu protection mode.');
24973 }
24974 } else {
24975 throw new UnsupportedError('Unknown s2k type.');
24976 }
24977 break;
24978
24979 default:
24980 throw new UnsupportedError('Unknown s2k type.'); // unreachable
24981 }
24982
24983 return i;
24984 }
24985
24986 /**
24987 * Serializes s2k information
24988 * @returns {Uint8Array} Binary representation of s2k.
24989 */
24990 write() {
24991 if (this.type === 'gnu-dummy') {
24992 return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);
24993 }
24994 const arr = [new Uint8Array([enums.write(enums.s2k, this.type), this.algorithm])];
24995
24996 switch (this.type) {
24997 case 'simple':
24998 break;
24999 case 'salted':
25000 arr.push(this.salt);
25001 break;
25002 case 'iterated':
25003 arr.push(this.salt);
25004 arr.push(new Uint8Array([this.c]));
25005 break;
25006 case 'gnu':
25007 throw new Error('GNU s2k type not supported.');
25008 default:
25009 throw new Error('Unknown s2k type.');
25010 }
25011
25012 return util.concatUint8Array(arr);
25013 }
25014
25015 /**
25016 * Produces a key using the specified passphrase and the defined
25017 * hashAlgorithm
25018 * @param {String} passphrase - Passphrase containing user input
25019 * @returns {Promise<Uint8Array>} Produced key with a length corresponding to.
25020 * hashAlgorithm hash length
25021 * @async
25022 */
25023 async produceKey(passphrase, numBytes) {
25024 passphrase = util.encodeUTF8(passphrase);
25025
25026 const arr = [];
25027 let rlength = 0;
25028
25029 let prefixlen = 0;
25030 while (rlength < numBytes) {
25031 let toHash;
25032 switch (this.type) {
25033 case 'simple':
25034 toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);
25035 break;
25036 case 'salted':
25037 toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);
25038 break;
25039 case 'iterated': {
25040 const data = util.concatUint8Array([this.salt, passphrase]);
25041 let datalen = data.length;
25042 const count = Math.max(this.getCount(), datalen);
25043 toHash = new Uint8Array(prefixlen + count);
25044 toHash.set(data, prefixlen);
25045 for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {
25046 toHash.copyWithin(pos, prefixlen, pos);
25047 }
25048 break;
25049 }
25050 case 'gnu':
25051 throw new Error('GNU s2k type not supported.');
25052 default:
25053 throw new Error('Unknown s2k type.');
25054 }
25055 const result = await mod.hash.digest(this.algorithm, toHash);
25056 arr.push(result);
25057 rlength += result.length;
25058 prefixlen++;
25059 }
25060
25061 return util.concatUint8Array(arr).subarray(0, numBytes);
25062 }
25063}
25064
25065// GPG4Browsers - An OpenPGP implementation in javascript
25066
25067/**
25068 * Symmetric-Key Encrypted Session Key Packets (Tag 3)
25069 *
25070 * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:
25071 * The Symmetric-Key Encrypted Session Key packet holds the
25072 * symmetric-key encryption of a session key used to encrypt a message.
25073 * Zero or more Public-Key Encrypted Session Key packets and/or
25074 * Symmetric-Key Encrypted Session Key packets may precede a
25075 * Symmetrically Encrypted Data packet that holds an encrypted message.
25076 * The message is encrypted with a session key, and the session key is
25077 * itself encrypted and stored in the Encrypted Session Key packet or
25078 * the Symmetric-Key Encrypted Session Key packet.
25079 */
25080class SymEncryptedSessionKeyPacket {
25081 static get tag() {
25082 return enums.packet.symEncryptedSessionKey;
25083 }
25084
25085 /**
25086 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25087 */
25088 constructor(config$1 = config) {
25089 this.version = config$1.aeadProtect ? 5 : 4;
25090 this.sessionKey = null;
25091 /**
25092 * Algorithm to encrypt the session key with
25093 * @type {enums.symmetric}
25094 */
25095 this.sessionKeyEncryptionAlgorithm = null;
25096 /**
25097 * Algorithm to encrypt the message with
25098 * @type {enums.symmetric}
25099 */
25100 this.sessionKeyAlgorithm = enums.symmetric.aes256;
25101 /**
25102 * AEAD mode to encrypt the session key with (if AEAD protection is enabled)
25103 * @type {enums.aead}
25104 */
25105 this.aeadAlgorithm = enums.write(enums.aead, config$1.preferredAEADAlgorithm);
25106 this.encrypted = null;
25107 this.s2k = null;
25108 this.iv = null;
25109 }
25110
25111 /**
25112 * Parsing function for a symmetric encrypted session key packet (tag 3).
25113 *
25114 * @param {Uint8Array} bytes - Payload of a tag 3 packet
25115 */
25116 read(bytes) {
25117 let offset = 0;
25118
25119 // A one-octet version number. The only currently defined version is 4.
25120 this.version = bytes[offset++];
25121 if (this.version !== 4 && this.version !== 5) {
25122 throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);
25123 }
25124
25125 // A one-octet number describing the symmetric algorithm used.
25126 const algo = bytes[offset++];
25127
25128 if (this.version === 5) {
25129 // A one-octet AEAD algorithm.
25130 this.aeadAlgorithm = bytes[offset++];
25131 }
25132
25133 // A string-to-key (S2K) specifier, length as defined above.
25134 this.s2k = new S2K();
25135 offset += this.s2k.read(bytes.subarray(offset, bytes.length));
25136
25137 if (this.version === 5) {
25138 const mode = mod.getAEADMode(this.aeadAlgorithm);
25139
25140 // A starting initialization vector of size specified by the AEAD
25141 // algorithm.
25142 this.iv = bytes.subarray(offset, offset += mode.ivLength);
25143 }
25144
25145 // The encrypted session key itself, which is decrypted with the
25146 // string-to-key object. This is optional in version 4.
25147 if (this.version === 5 || offset < bytes.length) {
25148 this.encrypted = bytes.subarray(offset, bytes.length);
25149 this.sessionKeyEncryptionAlgorithm = algo;
25150 } else {
25151 this.sessionKeyAlgorithm = algo;
25152 }
25153 }
25154
25155 /**
25156 * Create a binary representation of a tag 3 packet
25157 *
25158 * @returns {Uint8Array} The Uint8Array representation.
25159 */
25160 write() {
25161 const algo = this.encrypted === null ?
25162 this.sessionKeyAlgorithm :
25163 this.sessionKeyEncryptionAlgorithm;
25164
25165 let bytes;
25166
25167 if (this.version === 5) {
25168 bytes = util.concatUint8Array([new Uint8Array([this.version, algo, this.aeadAlgorithm]), this.s2k.write(), this.iv, this.encrypted]);
25169 } else {
25170 bytes = util.concatUint8Array([new Uint8Array([this.version, algo]), this.s2k.write()]);
25171
25172 if (this.encrypted !== null) {
25173 bytes = util.concatUint8Array([bytes, this.encrypted]);
25174 }
25175 }
25176
25177 return bytes;
25178 }
25179
25180 /**
25181 * Decrypts the session key with the given passphrase
25182 * @param {String} passphrase - The passphrase in string form
25183 * @throws {Error} if decryption was not successful
25184 * @async
25185 */
25186 async decrypt(passphrase) {
25187 const algo = this.sessionKeyEncryptionAlgorithm !== null ?
25188 this.sessionKeyEncryptionAlgorithm :
25189 this.sessionKeyAlgorithm;
25190
25191 const { blockSize, keySize } = mod.getCipher(algo);
25192 const key = await this.s2k.produceKey(passphrase, keySize);
25193
25194 if (this.version === 5) {
25195 const mode = mod.getAEADMode(this.aeadAlgorithm);
25196 const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);
25197 const modeInstance = await mode(algo, key);
25198 this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);
25199 } else if (this.encrypted !== null) {
25200 const decrypted = await mod.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(blockSize));
25201
25202 this.sessionKeyAlgorithm = enums.write(enums.symmetric, decrypted[0]);
25203 this.sessionKey = decrypted.subarray(1, decrypted.length);
25204 } else {
25205 this.sessionKey = key;
25206 }
25207 }
25208
25209 /**
25210 * Encrypts the session key with the given passphrase
25211 * @param {String} passphrase - The passphrase in string form
25212 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25213 * @throws {Error} if encryption was not successful
25214 * @async
25215 */
25216 async encrypt(passphrase, config$1 = config) {
25217 const algo = this.sessionKeyEncryptionAlgorithm !== null ?
25218 this.sessionKeyEncryptionAlgorithm :
25219 this.sessionKeyAlgorithm;
25220
25221 this.sessionKeyEncryptionAlgorithm = algo;
25222
25223 this.s2k = new S2K(config$1);
25224 this.s2k.salt = mod.random.getRandomBytes(8);
25225
25226 const { blockSize, keySize } = mod.getCipher(algo);
25227 const encryptionKey = await this.s2k.produceKey(passphrase, keySize);
25228
25229 if (this.sessionKey === null) {
25230 this.sessionKey = mod.generateSessionKey(this.sessionKeyAlgorithm);
25231 }
25232
25233 if (this.version === 5) {
25234 const mode = mod.getAEADMode(this.aeadAlgorithm);
25235 this.iv = mod.random.getRandomBytes(mode.ivLength); // generate new random IV
25236 const associatedData = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, this.sessionKeyEncryptionAlgorithm, this.aeadAlgorithm]);
25237 const modeInstance = await mode(algo, encryptionKey);
25238 this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, associatedData);
25239 } else {
25240 const toEncrypt = util.concatUint8Array([
25241 new Uint8Array([this.sessionKeyAlgorithm]),
25242 this.sessionKey
25243 ]);
25244 this.encrypted = await mod.mode.cfb.encrypt(algo, encryptionKey, toEncrypt, new Uint8Array(blockSize), config$1);
25245 }
25246 }
25247}
25248
25249// GPG4Browsers - An OpenPGP implementation in javascript
25250
25251/**
25252 * Implementation of the Key Material Packet (Tag 5,6,7,14)
25253 *
25254 * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:
25255 * A key material packet contains all the information about a public or
25256 * private key. There are four variants of this packet type, and two
25257 * major versions.
25258 *
25259 * A Public-Key packet starts a series of packets that forms an OpenPGP
25260 * key (sometimes called an OpenPGP certificate).
25261 */
25262class PublicKeyPacket {
25263 static get tag() {
25264 return enums.packet.publicKey;
25265 }
25266
25267 /**
25268 * @param {Date} [date] - Creation date
25269 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25270 */
25271 constructor(date = new Date(), config$1 = config) {
25272 /**
25273 * Packet version
25274 * @type {Integer}
25275 */
25276 this.version = config$1.v5Keys ? 5 : 4;
25277 /**
25278 * Key creation date.
25279 * @type {Date}
25280 */
25281 this.created = util.normalizeDate(date);
25282 /**
25283 * Public key algorithm.
25284 * @type {enums.publicKey}
25285 */
25286 this.algorithm = null;
25287 /**
25288 * Algorithm specific public params
25289 * @type {Object}
25290 */
25291 this.publicParams = null;
25292 /**
25293 * Time until expiration in days (V3 only)
25294 * @type {Integer}
25295 */
25296 this.expirationTimeV3 = 0;
25297 /**
25298 * Fingerprint bytes
25299 * @type {Uint8Array}
25300 */
25301 this.fingerprint = null;
25302 /**
25303 * KeyID
25304 * @type {module:type/keyid~KeyID}
25305 */
25306 this.keyID = null;
25307 }
25308
25309 /**
25310 * Create a PublicKeyPacket from a SecretKeyPacket
25311 * @param {SecretKeyPacket} secretKeyPacket - key packet to convert
25312 * @returns {PublicKeyPacket} public key packet
25313 * @static
25314 */
25315 static fromSecretKeyPacket(secretKeyPacket) {
25316 const keyPacket = new PublicKeyPacket();
25317 const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;
25318 keyPacket.version = version;
25319 keyPacket.created = created;
25320 keyPacket.algorithm = algorithm;
25321 keyPacket.publicParams = publicParams;
25322 keyPacket.keyID = keyID;
25323 keyPacket.fingerprint = fingerprint;
25324 return keyPacket;
25325 }
25326
25327 /**
25328 * 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}
25329 * @param {Uint8Array} bytes - Input array to read the packet from
25330 * @returns {Object} This object with attributes set by the parser
25331 * @async
25332 */
25333 async read(bytes) {
25334 let pos = 0;
25335 // A one-octet version number (3, 4 or 5).
25336 this.version = bytes[pos++];
25337
25338 if (this.version === 4 || this.version === 5) {
25339 // - A four-octet number denoting the time that the key was created.
25340 this.created = util.readDate(bytes.subarray(pos, pos + 4));
25341 pos += 4;
25342
25343 // - A one-octet number denoting the public-key algorithm of this key.
25344 this.algorithm = bytes[pos++];
25345
25346 if (this.version === 5) {
25347 // - A four-octet scalar octet count for the following key material.
25348 pos += 4;
25349 }
25350
25351 // - A series of values comprising the key material.
25352 const { read, publicParams } = mod.parsePublicKeyParams(this.algorithm, bytes.subarray(pos));
25353 this.publicParams = publicParams;
25354 pos += read;
25355
25356 // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor
25357 await this.computeFingerprintAndKeyID();
25358 return pos;
25359 }
25360 throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);
25361 }
25362
25363 /**
25364 * Creates an OpenPGP public key packet for the given key.
25365 * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.
25366 */
25367 write() {
25368 const arr = [];
25369 // Version
25370 arr.push(new Uint8Array([this.version]));
25371 arr.push(util.writeDate(this.created));
25372 // A one-octet number denoting the public-key algorithm of this key
25373 arr.push(new Uint8Array([this.algorithm]));
25374
25375 const params = mod.serializeParams(this.algorithm, this.publicParams);
25376 if (this.version === 5) {
25377 // A four-octet scalar octet count for the following key material
25378 arr.push(util.writeNumber(params.length, 4));
25379 }
25380 // Algorithm-specific params
25381 arr.push(params);
25382 return util.concatUint8Array(arr);
25383 }
25384
25385 /**
25386 * Write packet in order to be hashed; either for a signature or a fingerprint
25387 * @param {Integer} version - target version of signature or key
25388 */
25389 writeForHash(version) {
25390 const bytes = this.writePublicKey();
25391
25392 if (version === 5) {
25393 return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]);
25394 }
25395 return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]);
25396 }
25397
25398 /**
25399 * Check whether secret-key data is available in decrypted form. Returns null for public keys.
25400 * @returns {Boolean|null}
25401 */
25402 isDecrypted() {
25403 return null;
25404 }
25405
25406 /**
25407 * Returns the creation time of the key
25408 * @returns {Date}
25409 */
25410 getCreationTime() {
25411 return this.created;
25412 }
25413
25414 /**
25415 * Return the key ID of the key
25416 * @returns {module:type/keyid~KeyID} The 8-byte key ID
25417 */
25418 getKeyID() {
25419 return this.keyID;
25420 }
25421
25422 /**
25423 * Computes and set the key ID and fingerprint of the key
25424 * @async
25425 */
25426 async computeFingerprintAndKeyID() {
25427 await this.computeFingerprint();
25428 this.keyID = new KeyID();
25429
25430 if (this.version === 5) {
25431 this.keyID.read(this.fingerprint.subarray(0, 8));
25432 } else if (this.version === 4) {
25433 this.keyID.read(this.fingerprint.subarray(12, 20));
25434 } else {
25435 throw new Error('Unsupported key version');
25436 }
25437 }
25438
25439 /**
25440 * Computes and set the fingerprint of the key
25441 */
25442 async computeFingerprint() {
25443 const toHash = this.writeForHash(this.version);
25444
25445 if (this.version === 5) {
25446 this.fingerprint = await mod.hash.sha256(toHash);
25447 } else if (this.version === 4) {
25448 this.fingerprint = await mod.hash.sha1(toHash);
25449 } else {
25450 throw new Error('Unsupported key version');
25451 }
25452 }
25453
25454 /**
25455 * Returns the fingerprint of the key, as an array of bytes
25456 * @returns {Uint8Array} A Uint8Array containing the fingerprint
25457 */
25458 getFingerprintBytes() {
25459 return this.fingerprint;
25460 }
25461
25462 /**
25463 * Calculates and returns the fingerprint of the key, as a string
25464 * @returns {String} A string containing the fingerprint in lowercase hex
25465 */
25466 getFingerprint() {
25467 return util.uint8ArrayToHex(this.getFingerprintBytes());
25468 }
25469
25470 /**
25471 * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint
25472 * @returns {Boolean} Whether the two keys have the same version and public key data.
25473 */
25474 hasSameFingerprintAs(other) {
25475 return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());
25476 }
25477
25478 /**
25479 * Returns algorithm information
25480 * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.
25481 */
25482 getAlgorithmInfo() {
25483 const result = {};
25484 result.algorithm = enums.read(enums.publicKey, this.algorithm);
25485 // RSA, DSA or ElGamal public modulo
25486 const modulo = this.publicParams.n || this.publicParams.p;
25487 if (modulo) {
25488 result.bits = util.uint8ArrayBitLength(modulo);
25489 } else if (this.publicParams.oid) {
25490 result.curve = this.publicParams.oid.getName();
25491 }
25492 return result;
25493 }
25494}
25495
25496/**
25497 * Alias of read()
25498 * @see PublicKeyPacket#read
25499 */
25500PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;
25501
25502/**
25503 * Alias of write()
25504 * @see PublicKeyPacket#write
25505 */
25506PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;
25507
25508// GPG4Browsers - An OpenPGP implementation in javascript
25509
25510// A SE packet can contain the following packet types
25511const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([
25512 LiteralDataPacket,
25513 CompressedDataPacket,
25514 OnePassSignaturePacket,
25515 SignaturePacket
25516]);
25517
25518/**
25519 * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)
25520 *
25521 * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:
25522 * The Symmetrically Encrypted Data packet contains data encrypted with a
25523 * symmetric-key algorithm. When it has been decrypted, it contains other
25524 * packets (usually a literal data packet or compressed data packet, but in
25525 * theory other Symmetrically Encrypted Data packets or sequences of packets
25526 * that form whole OpenPGP messages).
25527 */
25528class SymmetricallyEncryptedDataPacket {
25529 static get tag() {
25530 return enums.packet.symmetricallyEncryptedData;
25531 }
25532
25533 constructor() {
25534 /**
25535 * Encrypted secret-key data
25536 */
25537 this.encrypted = null;
25538 /**
25539 * Decrypted packets contained within.
25540 * @type {PacketList}
25541 */
25542 this.packets = null;
25543 }
25544
25545 read(bytes) {
25546 this.encrypted = bytes;
25547 }
25548
25549 write() {
25550 return this.encrypted;
25551 }
25552
25553 /**
25554 * Decrypt the symmetrically-encrypted packet data
25555 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
25556 * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use
25557 * @param {Uint8Array} key - The key of cipher blocksize length to be used
25558 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25559
25560 * @throws {Error} if decryption was not successful
25561 * @async
25562 */
25563 async decrypt(sessionKeyAlgorithm, key, config$1 = config) {
25564 // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error
25565 if (!config$1.allowUnauthenticatedMessages) {
25566 throw new Error('Message is not authenticated.');
25567 }
25568
25569 const { blockSize } = mod.getCipher(sessionKeyAlgorithm);
25570 const encrypted = await readToEnd(clone(this.encrypted));
25571 const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key,
25572 encrypted.subarray(blockSize + 2),
25573 encrypted.subarray(2, blockSize + 2)
25574 );
25575
25576 this.packets = await PacketList.fromBinary(decrypted, allowedPackets$3, config$1);
25577 }
25578
25579 /**
25580 * Encrypt the symmetrically-encrypted packet data
25581 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
25582 * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use
25583 * @param {Uint8Array} key - The key of cipher blocksize length to be used
25584 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25585 * @throws {Error} if encryption was not successful
25586 * @async
25587 */
25588 async encrypt(sessionKeyAlgorithm, key, config$1 = config) {
25589 const data = this.packets.write();
25590 const { blockSize } = mod.getCipher(sessionKeyAlgorithm);
25591
25592 const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm);
25593 const FRE = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, prefix, new Uint8Array(blockSize), config$1);
25594 const ciphertext = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, data, FRE.subarray(2), config$1);
25595 this.encrypted = util.concat([FRE, ciphertext]);
25596 }
25597}
25598
25599// GPG4Browsers - An OpenPGP implementation in javascript
25600
25601/**
25602 * Implementation of the strange "Marker packet" (Tag 10)
25603 *
25604 * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:
25605 * An experimental version of PGP used this packet as the Literal
25606 * packet, but no released version of PGP generated Literal packets with this
25607 * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as
25608 * the Marker packet.
25609 *
25610 * The body of this packet consists of:
25611 * The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8).
25612 *
25613 * Such a packet MUST be ignored when received. It may be placed at the
25614 * beginning of a message that uses features not available in PGP
25615 * version 2.6 in order to cause that version to report that newer
25616 * software is necessary to process the message.
25617 */
25618class MarkerPacket {
25619 static get tag() {
25620 return enums.packet.marker;
25621 }
25622
25623 /**
25624 * Parsing function for a marker data packet (tag 10).
25625 * @param {Uint8Array} bytes - Payload of a tag 10 packet
25626 * @returns {Boolean} whether the packet payload contains "PGP"
25627 */
25628 read(bytes) {
25629 if (bytes[0] === 0x50 && // P
25630 bytes[1] === 0x47 && // G
25631 bytes[2] === 0x50) { // P
25632 return true;
25633 }
25634 return false;
25635 }
25636
25637 write() {
25638 return new Uint8Array([0x50, 0x47, 0x50]);
25639 }
25640}
25641
25642// GPG4Browsers - An OpenPGP implementation in javascript
25643
25644/**
25645 * A Public-Subkey packet (tag 14) has exactly the same format as a
25646 * Public-Key packet, but denotes a subkey. One or more subkeys may be
25647 * associated with a top-level key. By convention, the top-level key
25648 * provides signature services, and the subkeys provide encryption
25649 * services.
25650 * @extends PublicKeyPacket
25651 */
25652class PublicSubkeyPacket extends PublicKeyPacket {
25653 static get tag() {
25654 return enums.packet.publicSubkey;
25655 }
25656
25657 /**
25658 * @param {Date} [date] - Creation date
25659 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25660 */
25661 // eslint-disable-next-line no-useless-constructor
25662 constructor(date, config) {
25663 super(date, config);
25664 }
25665
25666 /**
25667 * Create a PublicSubkeyPacket from a SecretSubkeyPacket
25668 * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert
25669 * @returns {SecretSubkeyPacket} public key packet
25670 * @static
25671 */
25672 static fromSecretSubkeyPacket(secretSubkeyPacket) {
25673 const keyPacket = new PublicSubkeyPacket();
25674 const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;
25675 keyPacket.version = version;
25676 keyPacket.created = created;
25677 keyPacket.algorithm = algorithm;
25678 keyPacket.publicParams = publicParams;
25679 keyPacket.keyID = keyID;
25680 keyPacket.fingerprint = fingerprint;
25681 return keyPacket;
25682 }
25683}
25684
25685// GPG4Browsers - An OpenPGP implementation in javascript
25686
25687/**
25688 * Implementation of the User Attribute Packet (Tag 17)
25689 *
25690 * The User Attribute packet is a variation of the User ID packet. It
25691 * is capable of storing more types of data than the User ID packet,
25692 * which is limited to text. Like the User ID packet, a User Attribute
25693 * packet may be certified by the key owner ("self-signed") or any other
25694 * key owner who cares to certify it. Except as noted, a User Attribute
25695 * packet may be used anywhere that a User ID packet may be used.
25696 *
25697 * While User Attribute packets are not a required part of the OpenPGP
25698 * standard, implementations SHOULD provide at least enough
25699 * compatibility to properly handle a certification signature on the
25700 * User Attribute packet. A simple way to do this is by treating the
25701 * User Attribute packet as a User ID packet with opaque contents, but
25702 * an implementation may use any method desired.
25703 */
25704class UserAttributePacket {
25705 static get tag() {
25706 return enums.packet.userAttribute;
25707 }
25708
25709 constructor() {
25710 this.attributes = [];
25711 }
25712
25713 /**
25714 * parsing function for a user attribute packet (tag 17).
25715 * @param {Uint8Array} input - Payload of a tag 17 packet
25716 */
25717 read(bytes) {
25718 let i = 0;
25719 while (i < bytes.length) {
25720 const len = readSimpleLength(bytes.subarray(i, bytes.length));
25721 i += len.offset;
25722
25723 this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));
25724 i += len.len;
25725 }
25726 }
25727
25728 /**
25729 * Creates a binary representation of the user attribute packet
25730 * @returns {Uint8Array} String representation.
25731 */
25732 write() {
25733 const arr = [];
25734 for (let i = 0; i < this.attributes.length; i++) {
25735 arr.push(writeSimpleLength(this.attributes[i].length));
25736 arr.push(util.stringToUint8Array(this.attributes[i]));
25737 }
25738 return util.concatUint8Array(arr);
25739 }
25740
25741 /**
25742 * Compare for equality
25743 * @param {UserAttributePacket} usrAttr
25744 * @returns {Boolean} True if equal.
25745 */
25746 equals(usrAttr) {
25747 if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {
25748 return false;
25749 }
25750 return this.attributes.every(function(attr, index) {
25751 return attr === usrAttr.attributes[index];
25752 });
25753 }
25754}
25755
25756// GPG4Browsers - An OpenPGP implementation in javascript
25757
25758/**
25759 * A Secret-Key packet contains all the information that is found in a
25760 * Public-Key packet, including the public-key material, but also
25761 * includes the secret-key material after all the public-key fields.
25762 * @extends PublicKeyPacket
25763 */
25764class SecretKeyPacket extends PublicKeyPacket {
25765 static get tag() {
25766 return enums.packet.secretKey;
25767 }
25768
25769 /**
25770 * @param {Date} [date] - Creation date
25771 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25772 */
25773 constructor(date = new Date(), config$1 = config) {
25774 super(date, config$1);
25775 /**
25776 * Secret-key data
25777 */
25778 this.keyMaterial = null;
25779 /**
25780 * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.
25781 */
25782 this.isEncrypted = null;
25783 /**
25784 * S2K usage
25785 * @type {enums.symmetric}
25786 */
25787 this.s2kUsage = 0;
25788 /**
25789 * S2K object
25790 * @type {type/s2k}
25791 */
25792 this.s2k = null;
25793 /**
25794 * Symmetric algorithm to encrypt the key with
25795 * @type {enums.symmetric}
25796 */
25797 this.symmetric = null;
25798 /**
25799 * AEAD algorithm to encrypt the key with (if AEAD protection is enabled)
25800 * @type {enums.aead}
25801 */
25802 this.aead = null;
25803 /**
25804 * Decrypted private parameters, referenced by name
25805 * @type {Object}
25806 */
25807 this.privateParams = null;
25808 }
25809
25810 // 5.5.3. Secret-Key Packet Formats
25811
25812 /**
25813 * Internal parser for private keys as specified in
25814 * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}
25815 * @param {Uint8Array} bytes - Input string to read the packet from
25816 * @async
25817 */
25818 async read(bytes) {
25819 // - A Public-Key or Public-Subkey packet, as described above.
25820 let i = await this.readPublicKey(bytes);
25821 const startOfSecretKeyData = i;
25822
25823 // - One octet indicating string-to-key usage conventions. Zero
25824 // indicates that the secret-key data is not encrypted. 255 or 254
25825 // indicates that a string-to-key specifier is being given. Any
25826 // other value is a symmetric-key encryption algorithm identifier.
25827 this.s2kUsage = bytes[i++];
25828
25829 // - Only for a version 5 packet, a one-octet scalar octet count of
25830 // the next 4 optional fields.
25831 if (this.version === 5) {
25832 i++;
25833 }
25834
25835 try {
25836 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25837 // one-octet symmetric encryption algorithm.
25838 if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {
25839 this.symmetric = bytes[i++];
25840
25841 // - [Optional] If string-to-key usage octet was 253, a one-octet
25842 // AEAD algorithm.
25843 if (this.s2kUsage === 253) {
25844 this.aead = bytes[i++];
25845 }
25846
25847 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25848 // string-to-key specifier. The length of the string-to-key
25849 // specifier is implied by its type, as described above.
25850 this.s2k = new S2K();
25851 i += this.s2k.read(bytes.subarray(i, bytes.length));
25852
25853 if (this.s2k.type === 'gnu-dummy') {
25854 return;
25855 }
25856 } else if (this.s2kUsage) {
25857 this.symmetric = this.s2kUsage;
25858 }
25859
25860 // - [Optional] If secret data is encrypted (string-to-key usage octet
25861 // not zero), an Initial Vector (IV) of the same length as the
25862 // cipher's block size.
25863 if (this.s2kUsage) {
25864 this.iv = bytes.subarray(
25865 i,
25866 i + mod.getCipher(this.symmetric).blockSize
25867 );
25868
25869 i += this.iv.length;
25870 }
25871 } catch (e) {
25872 // if the s2k is unsupported, we still want to support encrypting and verifying with the given key
25873 if (!this.s2kUsage) throw e; // always throw for decrypted keys
25874 this.unparseableKeyMaterial = bytes.subarray(startOfSecretKeyData);
25875 this.isEncrypted = true;
25876 }
25877
25878 // - Only for a version 5 packet, a four-octet scalar octet count for
25879 // the following key material.
25880 if (this.version === 5) {
25881 i += 4;
25882 }
25883
25884 // - Plain or encrypted multiprecision integers comprising the secret
25885 // key data. These algorithm-specific fields are as described
25886 // below.
25887 this.keyMaterial = bytes.subarray(i);
25888 this.isEncrypted = !!this.s2kUsage;
25889
25890 if (!this.isEncrypted) {
25891 const cleartext = this.keyMaterial.subarray(0, -2);
25892 if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {
25893 throw new Error('Key checksum mismatch');
25894 }
25895 try {
25896 const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);
25897 this.privateParams = privateParams;
25898 } catch (err) {
25899 if (err instanceof UnsupportedError) throw err;
25900 // avoid throwing potentially sensitive errors
25901 throw new Error('Error reading MPIs');
25902 }
25903 }
25904 }
25905
25906 /**
25907 * Creates an OpenPGP key packet for the given key.
25908 * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.
25909 */
25910 write() {
25911 const serializedPublicKey = this.writePublicKey();
25912 if (this.unparseableKeyMaterial) {
25913 return util.concatUint8Array([
25914 serializedPublicKey,
25915 this.unparseableKeyMaterial
25916 ]);
25917 }
25918
25919 const arr = [serializedPublicKey];
25920 arr.push(new Uint8Array([this.s2kUsage]));
25921
25922 const optionalFieldsArr = [];
25923 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25924 // one- octet symmetric encryption algorithm.
25925 if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {
25926 optionalFieldsArr.push(this.symmetric);
25927
25928 // - [Optional] If string-to-key usage octet was 253, a one-octet
25929 // AEAD algorithm.
25930 if (this.s2kUsage === 253) {
25931 optionalFieldsArr.push(this.aead);
25932 }
25933
25934 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25935 // string-to-key specifier. The length of the string-to-key
25936 // specifier is implied by its type, as described above.
25937 optionalFieldsArr.push(...this.s2k.write());
25938 }
25939
25940 // - [Optional] If secret data is encrypted (string-to-key usage octet
25941 // not zero), an Initial Vector (IV) of the same length as the
25942 // cipher's block size.
25943 if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {
25944 optionalFieldsArr.push(...this.iv);
25945 }
25946
25947 if (this.version === 5) {
25948 arr.push(new Uint8Array([optionalFieldsArr.length]));
25949 }
25950 arr.push(new Uint8Array(optionalFieldsArr));
25951
25952 if (!this.isDummy()) {
25953 if (!this.s2kUsage) {
25954 this.keyMaterial = mod.serializeParams(this.algorithm, this.privateParams);
25955 }
25956
25957 if (this.version === 5) {
25958 arr.push(util.writeNumber(this.keyMaterial.length, 4));
25959 }
25960 arr.push(this.keyMaterial);
25961
25962 if (!this.s2kUsage) {
25963 arr.push(util.writeChecksum(this.keyMaterial));
25964 }
25965 }
25966
25967 return util.concatUint8Array(arr);
25968 }
25969
25970 /**
25971 * Check whether secret-key data is available in decrypted form.
25972 * Returns false for gnu-dummy keys and null for public keys.
25973 * @returns {Boolean|null}
25974 */
25975 isDecrypted() {
25976 return this.isEncrypted === false;
25977 }
25978
25979 /**
25980 * Check whether the key includes secret key material.
25981 * Some secret keys do not include it, and can thus only be used
25982 * for public-key operations (encryption and verification).
25983 * Such keys are:
25984 * - GNU-dummy keys, where the secret material has been stripped away
25985 * - encrypted keys with unsupported S2K or cipher
25986 */
25987 isMissingSecretKeyMaterial() {
25988 return this.unparseableKeyMaterial !== undefined || this.isDummy();
25989 }
25990
25991 /**
25992 * Check whether this is a gnu-dummy key
25993 * @returns {Boolean}
25994 */
25995 isDummy() {
25996 return !!(this.s2k && this.s2k.type === 'gnu-dummy');
25997 }
25998
25999 /**
26000 * Remove private key material, converting the key to a dummy one.
26001 * The resulting key cannot be used for signing/decrypting but can still verify signatures.
26002 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26003 */
26004 makeDummy(config$1 = config) {
26005 if (this.isDummy()) {
26006 return;
26007 }
26008 if (this.isDecrypted()) {
26009 this.clearPrivateParams();
26010 }
26011 delete this.unparseableKeyMaterial;
26012 this.isEncrypted = null;
26013 this.keyMaterial = null;
26014 this.s2k = new S2K(config$1);
26015 this.s2k.algorithm = 0;
26016 this.s2k.c = 0;
26017 this.s2k.type = 'gnu-dummy';
26018 this.s2kUsage = 254;
26019 this.symmetric = enums.symmetric.aes256;
26020 }
26021
26022 /**
26023 * Encrypt the payload. By default, we use aes256 and iterated, salted string
26024 * to key specifier. If the key is in a decrypted state (isEncrypted === false)
26025 * and the passphrase is empty or undefined, the key will be set as not encrypted.
26026 * This can be used to remove passphrase protection after calling decrypt().
26027 * @param {String} passphrase
26028 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26029 * @throws {Error} if encryption was not successful
26030 * @async
26031 */
26032 async encrypt(passphrase, config$1 = config) {
26033 if (this.isDummy()) {
26034 return;
26035 }
26036
26037 if (!this.isDecrypted()) {
26038 throw new Error('Key packet is already encrypted');
26039 }
26040
26041 if (!passphrase) {
26042 throw new Error('A non-empty passphrase is required for key encryption.');
26043 }
26044
26045 this.s2k = new S2K(config$1);
26046 this.s2k.salt = mod.random.getRandomBytes(8);
26047 const cleartext = mod.serializeParams(this.algorithm, this.privateParams);
26048 this.symmetric = enums.symmetric.aes256;
26049 const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);
26050
26051 const { blockSize } = mod.getCipher(this.symmetric);
26052 this.iv = mod.random.getRandomBytes(blockSize);
26053
26054 if (config$1.aeadProtect) {
26055 this.s2kUsage = 253;
26056 this.aead = enums.aead.eax;
26057 const mode = mod.getAEADMode(this.aead);
26058 const modeInstance = await mode(this.symmetric, key);
26059 this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array());
26060 } else {
26061 this.s2kUsage = 254;
26062 this.keyMaterial = await mod.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([
26063 cleartext,
26064 await mod.hash.sha1(cleartext, config$1)
26065 ]), this.iv, config$1);
26066 }
26067 }
26068
26069 /**
26070 * Decrypts the private key params which are needed to use the key.
26071 * Successful decryption does not imply key integrity, call validate() to confirm that.
26072 * {@link SecretKeyPacket.isDecrypted} should be false, as
26073 * otherwise calls to this function will throw an error.
26074 * @param {String} passphrase - The passphrase for this private key as string
26075 * @throws {Error} if the key is already decrypted, or if decryption was not successful
26076 * @async
26077 */
26078 async decrypt(passphrase) {
26079 if (this.isDummy()) {
26080 return false;
26081 }
26082
26083 if (this.unparseableKeyMaterial) {
26084 throw new Error('Key packet cannot be decrypted: unsupported S2K or cipher algo');
26085 }
26086
26087 if (this.isDecrypted()) {
26088 throw new Error('Key packet is already decrypted.');
26089 }
26090
26091 let key;
26092 if (this.s2kUsage === 254 || this.s2kUsage === 253) {
26093 key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);
26094 } else if (this.s2kUsage === 255) {
26095 throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');
26096 } else {
26097 throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');
26098 }
26099
26100 let cleartext;
26101 if (this.s2kUsage === 253) {
26102 const mode = mod.getAEADMode(this.aead);
26103 const modeInstance = await mode(this.symmetric, key);
26104 try {
26105 cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array());
26106 } catch (err) {
26107 if (err.message === 'Authentication tag mismatch') {
26108 throw new Error('Incorrect key passphrase: ' + err.message);
26109 }
26110 throw err;
26111 }
26112 } else {
26113 const cleartextWithHash = await mod.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);
26114
26115 cleartext = cleartextWithHash.subarray(0, -20);
26116 const hash = await mod.hash.sha1(cleartext);
26117
26118 if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {
26119 throw new Error('Incorrect key passphrase');
26120 }
26121 }
26122
26123 try {
26124 const { privateParams } = mod.parsePrivateKeyParams(this.algorithm, cleartext, this.publicParams);
26125 this.privateParams = privateParams;
26126 } catch (err) {
26127 throw new Error('Error reading MPIs');
26128 }
26129 this.isEncrypted = false;
26130 this.keyMaterial = null;
26131 this.s2kUsage = 0;
26132 }
26133
26134 /**
26135 * Checks that the key parameters are consistent
26136 * @throws {Error} if validation was not successful
26137 * @async
26138 */
26139 async validate() {
26140 if (this.isDummy()) {
26141 return;
26142 }
26143
26144 if (!this.isDecrypted()) {
26145 throw new Error('Key is not decrypted');
26146 }
26147
26148 let validParams;
26149 try {
26150 // this can throw if some parameters are undefined
26151 validParams = await mod.validateParams(this.algorithm, this.publicParams, this.privateParams);
26152 } catch (_) {
26153 validParams = false;
26154 }
26155 if (!validParams) {
26156 throw new Error('Key is invalid');
26157 }
26158 }
26159
26160 async generate(bits, curve) {
26161 const { privateParams, publicParams } = await mod.generateParams(this.algorithm, bits, curve);
26162 this.privateParams = privateParams;
26163 this.publicParams = publicParams;
26164 this.isEncrypted = false;
26165 }
26166
26167 /**
26168 * Clear private key parameters
26169 */
26170 clearPrivateParams() {
26171 if (this.isMissingSecretKeyMaterial()) {
26172 return;
26173 }
26174
26175 Object.keys(this.privateParams).forEach(name => {
26176 const param = this.privateParams[name];
26177 param.fill(0);
26178 delete this.privateParams[name];
26179 });
26180 this.privateParams = null;
26181 this.isEncrypted = true;
26182 }
26183}
26184
26185async function produceEncryptionKey(s2k, passphrase, algorithm) {
26186 const { keySize } = mod.getCipher(algorithm);
26187 return s2k.produceKey(passphrase, keySize);
26188}
26189
26190var emailAddresses = createCommonjsModule(function (module) {
26191// email-addresses.js - RFC 5322 email address parser
26192// v 3.1.0
26193//
26194// http://tools.ietf.org/html/rfc5322
26195//
26196// This library does not validate email addresses.
26197// emailAddresses attempts to parse addresses using the (fairly liberal)
26198// grammar specified in RFC 5322.
26199//
26200// email-addresses returns {
26201// ast: <an abstract syntax tree based on rfc5322>,
26202// addresses: [{
26203// node: <node in ast for this address>,
26204// name: <display-name>,
26205// address: <addr-spec>,
26206// local: <local-part>,
26207// domain: <domain>
26208// }, ...]
26209// }
26210//
26211// emailAddresses.parseOneAddress and emailAddresses.parseAddressList
26212// work as you might expect. Try it out.
26213//
26214// Many thanks to Dominic Sayers and his documentation on the is_email function,
26215// http://code.google.com/p/isemail/ , which helped greatly in writing this parser.
26216
26217(function (global) {
26218
26219function parse5322(opts) {
26220
26221 // tokenizing functions
26222
26223 function inStr() { return pos < len; }
26224 function curTok() { return parseString[pos]; }
26225 function getPos() { return pos; }
26226 function setPos(i) { pos = i; }
26227 function nextTok() { pos += 1; }
26228 function initialize() {
26229 pos = 0;
26230 len = parseString.length;
26231 }
26232
26233 // parser helper functions
26234
26235 function o(name, value) {
26236 return {
26237 name: name,
26238 tokens: value || "",
26239 semantic: value || "",
26240 children: []
26241 };
26242 }
26243
26244 function wrap(name, ast) {
26245 var n;
26246 if (ast === null) { return null; }
26247 n = o(name);
26248 n.tokens = ast.tokens;
26249 n.semantic = ast.semantic;
26250 n.children.push(ast);
26251 return n;
26252 }
26253
26254 function add(parent, child) {
26255 if (child !== null) {
26256 parent.tokens += child.tokens;
26257 parent.semantic += child.semantic;
26258 }
26259 parent.children.push(child);
26260 return parent;
26261 }
26262
26263 function compareToken(fxnCompare) {
26264 var tok;
26265 if (!inStr()) { return null; }
26266 tok = curTok();
26267 if (fxnCompare(tok)) {
26268 nextTok();
26269 return o('token', tok);
26270 }
26271 return null;
26272 }
26273
26274 function literal(lit) {
26275 return function literalFunc() {
26276 return wrap('literal', compareToken(function (tok) {
26277 return tok === lit;
26278 }));
26279 };
26280 }
26281
26282 function and() {
26283 var args = arguments;
26284 return function andFunc() {
26285 var i, s, result, start;
26286 start = getPos();
26287 s = o('and');
26288 for (i = 0; i < args.length; i += 1) {
26289 result = args[i]();
26290 if (result === null) {
26291 setPos(start);
26292 return null;
26293 }
26294 add(s, result);
26295 }
26296 return s;
26297 };
26298 }
26299
26300 function or() {
26301 var args = arguments;
26302 return function orFunc() {
26303 var i, result, start;
26304 start = getPos();
26305 for (i = 0; i < args.length; i += 1) {
26306 result = args[i]();
26307 if (result !== null) {
26308 return result;
26309 }
26310 setPos(start);
26311 }
26312 return null;
26313 };
26314 }
26315
26316 function opt(prod) {
26317 return function optFunc() {
26318 var result, start;
26319 start = getPos();
26320 result = prod();
26321 if (result !== null) {
26322 return result;
26323 }
26324 else {
26325 setPos(start);
26326 return o('opt');
26327 }
26328 };
26329 }
26330
26331 function invis(prod) {
26332 return function invisFunc() {
26333 var result = prod();
26334 if (result !== null) {
26335 result.semantic = "";
26336 }
26337 return result;
26338 };
26339 }
26340
26341 function colwsp(prod) {
26342 return function collapseSemanticWhitespace() {
26343 var result = prod();
26344 if (result !== null && result.semantic.length > 0) {
26345 result.semantic = " ";
26346 }
26347 return result;
26348 };
26349 }
26350
26351 function star(prod, minimum) {
26352 return function starFunc() {
26353 var s, result, count, start, min;
26354 start = getPos();
26355 s = o('star');
26356 count = 0;
26357 min = minimum === undefined ? 0 : minimum;
26358 while ((result = prod()) !== null) {
26359 count = count + 1;
26360 add(s, result);
26361 }
26362 if (count >= min) {
26363 return s;
26364 }
26365 else {
26366 setPos(start);
26367 return null;
26368 }
26369 };
26370 }
26371
26372 // One expects names to get normalized like this:
26373 // " First Last " -> "First Last"
26374 // "First Last" -> "First Last"
26375 // "First Last" -> "First Last"
26376 function collapseWhitespace(s) {
26377 return s.replace(/([ \t]|\r\n)+/g, ' ').replace(/^\s*/, '').replace(/\s*$/, '');
26378 }
26379
26380 // UTF-8 pseudo-production (RFC 6532)
26381 // RFC 6532 extends RFC 5322 productions to include UTF-8
26382 // using the following productions:
26383 // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4
26384 // UTF8-2 = <Defined in Section 4 of RFC3629>
26385 // UTF8-3 = <Defined in Section 4 of RFC3629>
26386 // UTF8-4 = <Defined in Section 4 of RFC3629>
26387 //
26388 // For reference, the extended RFC 5322 productions are:
26389 // VCHAR =/ UTF8-non-ascii
26390 // ctext =/ UTF8-non-ascii
26391 // atext =/ UTF8-non-ascii
26392 // qtext =/ UTF8-non-ascii
26393 // dtext =/ UTF8-non-ascii
26394 function isUTF8NonAscii(tok) {
26395 // In JavaScript, we just deal directly with Unicode code points,
26396 // so we aren't checking individual bytes for UTF-8 encoding.
26397 // Just check that the character is non-ascii.
26398 return tok.charCodeAt(0) >= 128;
26399 }
26400
26401
26402 // common productions (RFC 5234)
26403 // http://tools.ietf.org/html/rfc5234
26404 // B.1. Core Rules
26405
26406 // CR = %x0D
26407 // ; carriage return
26408 function cr() { return wrap('cr', literal('\r')()); }
26409
26410 // CRLF = CR LF
26411 // ; Internet standard newline
26412 function crlf() { return wrap('crlf', and(cr, lf)()); }
26413
26414 // DQUOTE = %x22
26415 // ; " (Double Quote)
26416 function dquote() { return wrap('dquote', literal('"')()); }
26417
26418 // HTAB = %x09
26419 // ; horizontal tab
26420 function htab() { return wrap('htab', literal('\t')()); }
26421
26422 // LF = %x0A
26423 // ; linefeed
26424 function lf() { return wrap('lf', literal('\n')()); }
26425
26426 // SP = %x20
26427 function sp() { return wrap('sp', literal(' ')()); }
26428
26429 // VCHAR = %x21-7E
26430 // ; visible (printing) characters
26431 function vchar() {
26432 return wrap('vchar', compareToken(function vcharFunc(tok) {
26433 var code = tok.charCodeAt(0);
26434 var accept = (0x21 <= code && code <= 0x7E);
26435 if (opts.rfc6532) {
26436 accept = accept || isUTF8NonAscii(tok);
26437 }
26438 return accept;
26439 }));
26440 }
26441
26442 // WSP = SP / HTAB
26443 // ; white space
26444 function wsp() { return wrap('wsp', or(sp, htab)()); }
26445
26446
26447 // email productions (RFC 5322)
26448 // http://tools.ietf.org/html/rfc5322
26449 // 3.2.1. Quoted characters
26450
26451 // quoted-pair = ("\" (VCHAR / WSP)) / obs-qp
26452 function quotedPair() {
26453 var qp = wrap('quoted-pair',
26454 or(
26455 and(literal('\\'), or(vchar, wsp)),
26456 obsQP
26457 )());
26458 if (qp === null) { return null; }
26459 // a quoted pair will be two characters, and the "\" character
26460 // should be semantically "invisible" (RFC 5322 3.2.1)
26461 qp.semantic = qp.semantic[1];
26462 return qp;
26463 }
26464
26465 // 3.2.2. Folding White Space and Comments
26466
26467 // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS
26468 function fws() {
26469 return wrap('fws', or(
26470 obsFws,
26471 and(
26472 opt(and(
26473 star(wsp),
26474 invis(crlf)
26475 )),
26476 star(wsp, 1)
26477 )
26478 )());
26479 }
26480
26481 // ctext = %d33-39 / ; Printable US-ASCII
26482 // %d42-91 / ; characters not including
26483 // %d93-126 / ; "(", ")", or "\"
26484 // obs-ctext
26485 function ctext() {
26486 return wrap('ctext', or(
26487 function ctextFunc1() {
26488 return compareToken(function ctextFunc2(tok) {
26489 var code = tok.charCodeAt(0);
26490 var accept =
26491 (33 <= code && code <= 39) ||
26492 (42 <= code && code <= 91) ||
26493 (93 <= code && code <= 126);
26494 if (opts.rfc6532) {
26495 accept = accept || isUTF8NonAscii(tok);
26496 }
26497 return accept;
26498 });
26499 },
26500 obsCtext
26501 )());
26502 }
26503
26504 // ccontent = ctext / quoted-pair / comment
26505 function ccontent() {
26506 return wrap('ccontent', or(ctext, quotedPair, comment)());
26507 }
26508
26509 // comment = "(" *([FWS] ccontent) [FWS] ")"
26510 function comment() {
26511 return wrap('comment', and(
26512 literal('('),
26513 star(and(opt(fws), ccontent)),
26514 opt(fws),
26515 literal(')')
26516 )());
26517 }
26518
26519 // CFWS = (1*([FWS] comment) [FWS]) / FWS
26520 function cfws() {
26521 return wrap('cfws', or(
26522 and(
26523 star(
26524 and(opt(fws), comment),
26525 1
26526 ),
26527 opt(fws)
26528 ),
26529 fws
26530 )());
26531 }
26532
26533 // 3.2.3. Atom
26534
26535 //atext = ALPHA / DIGIT / ; Printable US-ASCII
26536 // "!" / "#" / ; characters not including
26537 // "$" / "%" / ; specials. Used for atoms.
26538 // "&" / "'" /
26539 // "*" / "+" /
26540 // "-" / "/" /
26541 // "=" / "?" /
26542 // "^" / "_" /
26543 // "`" / "{" /
26544 // "|" / "}" /
26545 // "~"
26546 function atext() {
26547 return wrap('atext', compareToken(function atextFunc(tok) {
26548 var accept =
26549 ('a' <= tok && tok <= 'z') ||
26550 ('A' <= tok && tok <= 'Z') ||
26551 ('0' <= tok && tok <= '9') ||
26552 (['!', '#', '$', '%', '&', '\'', '*', '+', '-', '/',
26553 '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0);
26554 if (opts.rfc6532) {
26555 accept = accept || isUTF8NonAscii(tok);
26556 }
26557 return accept;
26558 }));
26559 }
26560
26561 // atom = [CFWS] 1*atext [CFWS]
26562 function atom() {
26563 return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))());
26564 }
26565
26566 // dot-atom-text = 1*atext *("." 1*atext)
26567 function dotAtomText() {
26568 var s, maybeText;
26569 s = wrap('dot-atom-text', star(atext, 1)());
26570 if (s === null) { return s; }
26571 maybeText = star(and(literal('.'), star(atext, 1)))();
26572 if (maybeText !== null) {
26573 add(s, maybeText);
26574 }
26575 return s;
26576 }
26577
26578 // dot-atom = [CFWS] dot-atom-text [CFWS]
26579 function dotAtom() {
26580 return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))());
26581 }
26582
26583 // 3.2.4. Quoted Strings
26584
26585 // qtext = %d33 / ; Printable US-ASCII
26586 // %d35-91 / ; characters not including
26587 // %d93-126 / ; "\" or the quote character
26588 // obs-qtext
26589 function qtext() {
26590 return wrap('qtext', or(
26591 function qtextFunc1() {
26592 return compareToken(function qtextFunc2(tok) {
26593 var code = tok.charCodeAt(0);
26594 var accept =
26595 (33 === code) ||
26596 (35 <= code && code <= 91) ||
26597 (93 <= code && code <= 126);
26598 if (opts.rfc6532) {
26599 accept = accept || isUTF8NonAscii(tok);
26600 }
26601 return accept;
26602 });
26603 },
26604 obsQtext
26605 )());
26606 }
26607
26608 // qcontent = qtext / quoted-pair
26609 function qcontent() {
26610 return wrap('qcontent', or(qtext, quotedPair)());
26611 }
26612
26613 // quoted-string = [CFWS]
26614 // DQUOTE *([FWS] qcontent) [FWS] DQUOTE
26615 // [CFWS]
26616 function quotedString() {
26617 return wrap('quoted-string', and(
26618 invis(opt(cfws)),
26619 invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote),
26620 invis(opt(cfws))
26621 )());
26622 }
26623
26624 // 3.2.5 Miscellaneous Tokens
26625
26626 // word = atom / quoted-string
26627 function word() {
26628 return wrap('word', or(atom, quotedString)());
26629 }
26630
26631 // phrase = 1*word / obs-phrase
26632 function phrase() {
26633 return wrap('phrase', or(obsPhrase, star(word, 1))());
26634 }
26635
26636 // 3.4. Address Specification
26637 // address = mailbox / group
26638 function address() {
26639 return wrap('address', or(mailbox, group)());
26640 }
26641
26642 // mailbox = name-addr / addr-spec
26643 function mailbox() {
26644 return wrap('mailbox', or(nameAddr, addrSpec)());
26645 }
26646
26647 // name-addr = [display-name] angle-addr
26648 function nameAddr() {
26649 return wrap('name-addr', and(opt(displayName), angleAddr)());
26650 }
26651
26652 // angle-addr = [CFWS] "<" addr-spec ">" [CFWS] /
26653 // obs-angle-addr
26654 function angleAddr() {
26655 return wrap('angle-addr', or(
26656 and(
26657 invis(opt(cfws)),
26658 literal('<'),
26659 addrSpec,
26660 literal('>'),
26661 invis(opt(cfws))
26662 ),
26663 obsAngleAddr
26664 )());
26665 }
26666
26667 // group = display-name ":" [group-list] ";" [CFWS]
26668 function group() {
26669 return wrap('group', and(
26670 displayName,
26671 literal(':'),
26672 opt(groupList),
26673 literal(';'),
26674 invis(opt(cfws))
26675 )());
26676 }
26677
26678 // display-name = phrase
26679 function displayName() {
26680 return wrap('display-name', function phraseFixedSemantic() {
26681 var result = phrase();
26682 if (result !== null) {
26683 result.semantic = collapseWhitespace(result.semantic);
26684 }
26685 return result;
26686 }());
26687 }
26688
26689 // mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list
26690 function mailboxList() {
26691 return wrap('mailbox-list', or(
26692 and(
26693 mailbox,
26694 star(and(literal(','), mailbox))
26695 ),
26696 obsMboxList
26697 )());
26698 }
26699
26700 // address-list = (address *("," address)) / obs-addr-list
26701 function addressList() {
26702 return wrap('address-list', or(
26703 and(
26704 address,
26705 star(and(literal(','), address))
26706 ),
26707 obsAddrList
26708 )());
26709 }
26710
26711 // group-list = mailbox-list / CFWS / obs-group-list
26712 function groupList() {
26713 return wrap('group-list', or(
26714 mailboxList,
26715 invis(cfws),
26716 obsGroupList
26717 )());
26718 }
26719
26720 // 3.4.1 Addr-Spec Specification
26721
26722 // local-part = dot-atom / quoted-string / obs-local-part
26723 function localPart() {
26724 // note: quoted-string, dotAtom are proper subsets of obs-local-part
26725 // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree
26726 return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)());
26727 }
26728
26729 // dtext = %d33-90 / ; Printable US-ASCII
26730 // %d94-126 / ; characters not including
26731 // obs-dtext ; "[", "]", or "\"
26732 function dtext() {
26733 return wrap('dtext', or(
26734 function dtextFunc1() {
26735 return compareToken(function dtextFunc2(tok) {
26736 var code = tok.charCodeAt(0);
26737 var accept =
26738 (33 <= code && code <= 90) ||
26739 (94 <= code && code <= 126);
26740 if (opts.rfc6532) {
26741 accept = accept || isUTF8NonAscii(tok);
26742 }
26743 return accept;
26744 });
26745 },
26746 obsDtext
26747 )()
26748 );
26749 }
26750
26751 // domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
26752 function domainLiteral() {
26753 return wrap('domain-literal', and(
26754 invis(opt(cfws)),
26755 literal('['),
26756 star(and(opt(fws), dtext)),
26757 opt(fws),
26758 literal(']'),
26759 invis(opt(cfws))
26760 )());
26761 }
26762
26763 // domain = dot-atom / domain-literal / obs-domain
26764 function domain() {
26765 return wrap('domain', function domainCheckTLD() {
26766 var result = or(obsDomain, dotAtom, domainLiteral)();
26767 if (opts.rejectTLD) {
26768 if (result && result.semantic && result.semantic.indexOf('.') < 0) {
26769 return null;
26770 }
26771 }
26772 // strip all whitespace from domains
26773 if (result) {
26774 result.semantic = result.semantic.replace(/\s+/g, '');
26775 }
26776 return result;
26777 }());
26778 }
26779
26780 // addr-spec = local-part "@" domain
26781 function addrSpec() {
26782 return wrap('addr-spec', and(
26783 localPart, literal('@'), domain
26784 )());
26785 }
26786
26787 // 3.6.2 Originator Fields
26788 // Below we only parse the field body, not the name of the field
26789 // like "From:", "Sender:", or "Reply-To:". Other libraries that
26790 // parse email headers can parse those and defer to these productions
26791 // for the "RFC 5322" part.
26792
26793 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
26794 // from = "From:" (mailbox-list / address-list) CRLF
26795 function fromSpec() {
26796 return wrap('from', or(
26797 mailboxList,
26798 addressList
26799 )());
26800 }
26801
26802 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
26803 // sender = "Sender:" (mailbox / address) CRLF
26804 function senderSpec() {
26805 return wrap('sender', or(
26806 mailbox,
26807 address
26808 )());
26809 }
26810
26811 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
26812 // reply-to = "Reply-To:" address-list CRLF
26813 function replyToSpec() {
26814 return wrap('reply-to', addressList());
26815 }
26816
26817 // 4.1. Miscellaneous Obsolete Tokens
26818
26819 // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
26820 // %d11 / ; characters that do not
26821 // %d12 / ; include the carriage
26822 // %d14-31 / ; return, line feed, and
26823 // %d127 ; white space characters
26824 function obsNoWsCtl() {
26825 return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) {
26826 var code = tok.charCodeAt(0);
26827 return ((1 <= code && code <= 8) ||
26828 (11 === code || 12 === code) ||
26829 (14 <= code && code <= 31) ||
26830 (127 === code));
26831 }));
26832 }
26833
26834 // obs-ctext = obs-NO-WS-CTL
26835 function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); }
26836
26837 // obs-qtext = obs-NO-WS-CTL
26838 function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); }
26839
26840 // obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR)
26841 function obsQP() {
26842 return opts.strict ? null : wrap('obs-qp', and(
26843 literal('\\'),
26844 or(literal('\0'), obsNoWsCtl, lf, cr)
26845 )());
26846 }
26847
26848 // obs-phrase = word *(word / "." / CFWS)
26849 function obsPhrase() {
26850 if (opts.strict ) return null;
26851 return opts.atInDisplayName ? wrap('obs-phrase', and(
26852 word,
26853 star(or(word, literal('.'), literal('@'), colwsp(cfws)))
26854 )()) :
26855 wrap('obs-phrase', and(
26856 word,
26857 star(or(word, literal('.'), colwsp(cfws)))
26858 )());
26859 }
26860
26861 // 4.2. Obsolete Folding White Space
26862
26863 // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908
26864 // obs-FWS = 1*([CRLF] WSP)
26865 function obsFws() {
26866 return opts.strict ? null : wrap('obs-FWS', star(
26867 and(invis(opt(crlf)), wsp),
26868 1
26869 )());
26870 }
26871
26872 // 4.4. Obsolete Addressing
26873
26874 // obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS]
26875 function obsAngleAddr() {
26876 return opts.strict ? null : wrap('obs-angle-addr', and(
26877 invis(opt(cfws)),
26878 literal('<'),
26879 obsRoute,
26880 addrSpec,
26881 literal('>'),
26882 invis(opt(cfws))
26883 )());
26884 }
26885
26886 // obs-route = obs-domain-list ":"
26887 function obsRoute() {
26888 return opts.strict ? null : wrap('obs-route', and(
26889 obsDomainList,
26890 literal(':')
26891 )());
26892 }
26893
26894 // obs-domain-list = *(CFWS / ",") "@" domain
26895 // *("," [CFWS] ["@" domain])
26896 function obsDomainList() {
26897 return opts.strict ? null : wrap('obs-domain-list', and(
26898 star(or(invis(cfws), literal(','))),
26899 literal('@'),
26900 domain,
26901 star(and(
26902 literal(','),
26903 invis(opt(cfws)),
26904 opt(and(literal('@'), domain))
26905 ))
26906 )());
26907 }
26908
26909 // obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS])
26910 function obsMboxList() {
26911 return opts.strict ? null : wrap('obs-mbox-list', and(
26912 star(and(
26913 invis(opt(cfws)),
26914 literal(',')
26915 )),
26916 mailbox,
26917 star(and(
26918 literal(','),
26919 opt(and(
26920 mailbox,
26921 invis(cfws)
26922 ))
26923 ))
26924 )());
26925 }
26926
26927 // obs-addr-list = *([CFWS] ",") address *("," [address / CFWS])
26928 function obsAddrList() {
26929 return opts.strict ? null : wrap('obs-addr-list', and(
26930 star(and(
26931 invis(opt(cfws)),
26932 literal(',')
26933 )),
26934 address,
26935 star(and(
26936 literal(','),
26937 opt(and(
26938 address,
26939 invis(cfws)
26940 ))
26941 ))
26942 )());
26943 }
26944
26945 // obs-group-list = 1*([CFWS] ",") [CFWS]
26946 function obsGroupList() {
26947 return opts.strict ? null : wrap('obs-group-list', and(
26948 star(and(
26949 invis(opt(cfws)),
26950 literal(',')
26951 ), 1),
26952 invis(opt(cfws))
26953 )());
26954 }
26955
26956 // obs-local-part = word *("." word)
26957 function obsLocalPart() {
26958 return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))());
26959 }
26960
26961 // obs-domain = atom *("." atom)
26962 function obsDomain() {
26963 return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))());
26964 }
26965
26966 // obs-dtext = obs-NO-WS-CTL / quoted-pair
26967 function obsDtext() {
26968 return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)());
26969 }
26970
26971 /////////////////////////////////////////////////////
26972
26973 // ast analysis
26974
26975 function findNode(name, root) {
26976 var i, stack, node;
26977 if (root === null || root === undefined) { return null; }
26978 stack = [root];
26979 while (stack.length > 0) {
26980 node = stack.pop();
26981 if (node.name === name) {
26982 return node;
26983 }
26984 for (i = node.children.length - 1; i >= 0; i -= 1) {
26985 stack.push(node.children[i]);
26986 }
26987 }
26988 return null;
26989 }
26990
26991 function findAllNodes(name, root) {
26992 var i, stack, node, result;
26993 if (root === null || root === undefined) { return null; }
26994 stack = [root];
26995 result = [];
26996 while (stack.length > 0) {
26997 node = stack.pop();
26998 if (node.name === name) {
26999 result.push(node);
27000 }
27001 for (i = node.children.length - 1; i >= 0; i -= 1) {
27002 stack.push(node.children[i]);
27003 }
27004 }
27005 return result;
27006 }
27007
27008 function findAllNodesNoChildren(names, root) {
27009 var i, stack, node, result, namesLookup;
27010 if (root === null || root === undefined) { return null; }
27011 stack = [root];
27012 result = [];
27013 namesLookup = {};
27014 for (i = 0; i < names.length; i += 1) {
27015 namesLookup[names[i]] = true;
27016 }
27017
27018 while (stack.length > 0) {
27019 node = stack.pop();
27020 if (node.name in namesLookup) {
27021 result.push(node);
27022 // don't look at children (hence findAllNodesNoChildren)
27023 } else {
27024 for (i = node.children.length - 1; i >= 0; i -= 1) {
27025 stack.push(node.children[i]);
27026 }
27027 }
27028 }
27029 return result;
27030 }
27031
27032 function giveResult(ast) {
27033 var addresses, groupsAndMailboxes, i, groupOrMailbox, result;
27034 if (ast === null) {
27035 return null;
27036 }
27037 addresses = [];
27038
27039 // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'.
27040 groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast);
27041 for (i = 0; i < groupsAndMailboxes.length; i += 1) {
27042 groupOrMailbox = groupsAndMailboxes[i];
27043 if (groupOrMailbox.name === 'group') {
27044 addresses.push(giveResultGroup(groupOrMailbox));
27045 } else if (groupOrMailbox.name === 'mailbox') {
27046 addresses.push(giveResultMailbox(groupOrMailbox));
27047 }
27048 }
27049
27050 result = {
27051 ast: ast,
27052 addresses: addresses,
27053 };
27054 if (opts.simple) {
27055 result = simplifyResult(result);
27056 }
27057 if (opts.oneResult) {
27058 return oneResult(result);
27059 }
27060 if (opts.simple) {
27061 return result && result.addresses;
27062 } else {
27063 return result;
27064 }
27065 }
27066
27067 function giveResultGroup(group) {
27068 var i;
27069 var groupName = findNode('display-name', group);
27070 var groupResultMailboxes = [];
27071 var mailboxes = findAllNodesNoChildren(['mailbox'], group);
27072 for (i = 0; i < mailboxes.length; i += 1) {
27073 groupResultMailboxes.push(giveResultMailbox(mailboxes[i]));
27074 }
27075 return {
27076 node: group,
27077 parts: {
27078 name: groupName,
27079 },
27080 type: group.name, // 'group'
27081 name: grabSemantic(groupName),
27082 addresses: groupResultMailboxes,
27083 };
27084 }
27085
27086 function giveResultMailbox(mailbox) {
27087 var name = findNode('display-name', mailbox);
27088 var aspec = findNode('addr-spec', mailbox);
27089 var cfws = findAllNodes('cfws', mailbox);
27090 var comments = findAllNodesNoChildren(['comment'], mailbox);
27091
27092
27093 var local = findNode('local-part', aspec);
27094 var domain = findNode('domain', aspec);
27095 return {
27096 node: mailbox,
27097 parts: {
27098 name: name,
27099 address: aspec,
27100 local: local,
27101 domain: domain,
27102 comments: cfws
27103 },
27104 type: mailbox.name, // 'mailbox'
27105 name: grabSemantic(name),
27106 address: grabSemantic(aspec),
27107 local: grabSemantic(local),
27108 domain: grabSemantic(domain),
27109 comments: concatComments(comments),
27110 groupName: grabSemantic(mailbox.groupName),
27111 };
27112 }
27113
27114 function grabSemantic(n) {
27115 return n !== null && n !== undefined ? n.semantic : null;
27116 }
27117
27118 function simplifyResult(result) {
27119 var i;
27120 if (result && result.addresses) {
27121 for (i = 0; i < result.addresses.length; i += 1) {
27122 delete result.addresses[i].node;
27123 }
27124 }
27125 return result;
27126 }
27127
27128 function concatComments(comments) {
27129 var result = '';
27130 if (comments) {
27131 for (var i = 0; i < comments.length; i += 1) {
27132 result += grabSemantic(comments[i]);
27133 }
27134 }
27135 return result;
27136 }
27137
27138 function oneResult(result) {
27139 if (!result) { return null; }
27140 if (!opts.partial && result.addresses.length > 1) { return null; }
27141 return result.addresses && result.addresses[0];
27142 }
27143
27144 /////////////////////////////////////////////////////
27145
27146 var parseString, pos, len, parsed, startProduction;
27147
27148 opts = handleOpts(opts, {});
27149 if (opts === null) { return null; }
27150
27151 parseString = opts.input;
27152
27153 startProduction = {
27154 'address': address,
27155 'address-list': addressList,
27156 'angle-addr': angleAddr,
27157 'from': fromSpec,
27158 'group': group,
27159 'mailbox': mailbox,
27160 'mailbox-list': mailboxList,
27161 'reply-to': replyToSpec,
27162 'sender': senderSpec,
27163 }[opts.startAt] || addressList;
27164
27165 if (!opts.strict) {
27166 initialize();
27167 opts.strict = true;
27168 parsed = startProduction(parseString);
27169 if (opts.partial || !inStr()) {
27170 return giveResult(parsed);
27171 }
27172 opts.strict = false;
27173 }
27174
27175 initialize();
27176 parsed = startProduction(parseString);
27177 if (!opts.partial && inStr()) { return null; }
27178 return giveResult(parsed);
27179}
27180
27181function parseOneAddressSimple(opts) {
27182 return parse5322(handleOpts(opts, {
27183 oneResult: true,
27184 rfc6532: true,
27185 simple: true,
27186 startAt: 'address-list',
27187 }));
27188}
27189
27190function parseAddressListSimple(opts) {
27191 return parse5322(handleOpts(opts, {
27192 rfc6532: true,
27193 simple: true,
27194 startAt: 'address-list',
27195 }));
27196}
27197
27198function parseFromSimple(opts) {
27199 return parse5322(handleOpts(opts, {
27200 rfc6532: true,
27201 simple: true,
27202 startAt: 'from',
27203 }));
27204}
27205
27206function parseSenderSimple(opts) {
27207 return parse5322(handleOpts(opts, {
27208 oneResult: true,
27209 rfc6532: true,
27210 simple: true,
27211 startAt: 'sender',
27212 }));
27213}
27214
27215function parseReplyToSimple(opts) {
27216 return parse5322(handleOpts(opts, {
27217 rfc6532: true,
27218 simple: true,
27219 startAt: 'reply-to',
27220 }));
27221}
27222
27223function handleOpts(opts, defs) {
27224 function isString(str) {
27225 return Object.prototype.toString.call(str) === '[object String]';
27226 }
27227
27228 function isObject(o) {
27229 return o === Object(o);
27230 }
27231
27232 function isNullUndef(o) {
27233 return o === null || o === undefined;
27234 }
27235
27236 var defaults, o;
27237
27238 if (isString(opts)) {
27239 opts = { input: opts };
27240 } else if (!isObject(opts)) {
27241 return null;
27242 }
27243
27244 if (!isString(opts.input)) { return null; }
27245 if (!defs) { return null; }
27246
27247 defaults = {
27248 oneResult: false,
27249 partial: false,
27250 rejectTLD: false,
27251 rfc6532: false,
27252 simple: false,
27253 startAt: 'address-list',
27254 strict: false,
27255 atInDisplayName: false
27256 };
27257
27258 for (o in defaults) {
27259 if (isNullUndef(opts[o])) {
27260 opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o];
27261 }
27262 }
27263 return opts;
27264}
27265
27266parse5322.parseOneAddress = parseOneAddressSimple;
27267parse5322.parseAddressList = parseAddressListSimple;
27268parse5322.parseFrom = parseFromSimple;
27269parse5322.parseSender = parseSenderSimple;
27270parse5322.parseReplyTo = parseReplyToSimple;
27271
27272{
27273 module.exports = parse5322;
27274}
27275
27276}());
27277});
27278
27279// GPG4Browsers - An OpenPGP implementation in javascript
27280
27281/**
27282 * Implementation of the User ID Packet (Tag 13)
27283 *
27284 * A User ID packet consists of UTF-8 text that is intended to represent
27285 * the name and email address of the key holder. By convention, it
27286 * includes an RFC 2822 [RFC2822] mail name-addr, but there are no
27287 * restrictions on its content. The packet length in the header
27288 * specifies the length of the User ID.
27289 */
27290class UserIDPacket {
27291 static get tag() {
27292 return enums.packet.userID;
27293 }
27294
27295 constructor() {
27296 /** A string containing the user id. Usually in the form
27297 * John Doe <john@example.com>
27298 * @type {String}
27299 */
27300 this.userID = '';
27301
27302 this.name = '';
27303 this.email = '';
27304 this.comment = '';
27305 }
27306
27307 /**
27308 * Create UserIDPacket instance from object
27309 * @param {Object} userID - Object specifying userID name, email and comment
27310 * @returns {UserIDPacket}
27311 * @static
27312 */
27313 static fromObject(userID) {
27314 if (util.isString(userID) ||
27315 (userID.name && !util.isString(userID.name)) ||
27316 (userID.email && !util.isEmailAddress(userID.email)) ||
27317 (userID.comment && !util.isString(userID.comment))) {
27318 throw new Error('Invalid user ID format');
27319 }
27320 const packet = new UserIDPacket();
27321 Object.assign(packet, userID);
27322 const components = [];
27323 if (packet.name) components.push(packet.name);
27324 if (packet.comment) components.push(`(${packet.comment})`);
27325 if (packet.email) components.push(`<${packet.email}>`);
27326 packet.userID = components.join(' ');
27327 return packet;
27328 }
27329
27330 /**
27331 * Parsing function for a user id packet (tag 13).
27332 * @param {Uint8Array} input - Payload of a tag 13 packet
27333 */
27334 read(bytes, config$1 = config) {
27335 const userID = util.decodeUTF8(bytes);
27336 if (userID.length > config$1.maxUserIDLength) {
27337 throw new Error('User ID string is too long');
27338 }
27339 try {
27340 const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true });
27341 this.comment = comments.replace(/^\(|\)$/g, '');
27342 this.name = name;
27343 this.email = email;
27344 } catch (e) {}
27345 this.userID = userID;
27346 }
27347
27348 /**
27349 * Creates a binary representation of the user id packet
27350 * @returns {Uint8Array} Binary representation.
27351 */
27352 write() {
27353 return util.encodeUTF8(this.userID);
27354 }
27355
27356 equals(otherUserID) {
27357 return otherUserID && otherUserID.userID === this.userID;
27358 }
27359}
27360
27361// GPG4Browsers - An OpenPGP implementation in javascript
27362
27363/**
27364 * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret
27365 * Key packet and has exactly the same format.
27366 * @extends SecretKeyPacket
27367 */
27368class SecretSubkeyPacket extends SecretKeyPacket {
27369 static get tag() {
27370 return enums.packet.secretSubkey;
27371 }
27372
27373 /**
27374 * @param {Date} [date] - Creation date
27375 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27376 */
27377 constructor(date = new Date(), config$1 = config) {
27378 super(date, config$1);
27379 }
27380}
27381
27382/**
27383 * Implementation of the Trust Packet (Tag 12)
27384 *
27385 * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:
27386 * The Trust packet is used only within keyrings and is not normally
27387 * exported. Trust packets contain data that record the user's
27388 * specifications of which key holders are trustworthy introducers,
27389 * along with other information that implementing software uses for
27390 * trust information. The format of Trust packets is defined by a given
27391 * implementation.
27392 *
27393 * Trust packets SHOULD NOT be emitted to output streams that are
27394 * transferred to other users, and they SHOULD be ignored on any input
27395 * other than local keyring files.
27396 */
27397class TrustPacket {
27398 static get tag() {
27399 return enums.packet.trust;
27400 }
27401
27402 /**
27403 * Parsing function for a trust packet (tag 12).
27404 * Currently not implemented as we ignore trust packets
27405 */
27406 read() {
27407 throw new UnsupportedError('Trust packets are not supported');
27408 }
27409
27410 write() {
27411 throw new UnsupportedError('Trust packets are not supported');
27412 }
27413}
27414
27415// GPG4Browsers - An OpenPGP implementation in javascript
27416
27417// A Signature can contain the following packets
27418const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
27419
27420/**
27421 * Class that represents an OpenPGP signature.
27422 */
27423class Signature {
27424 /**
27425 * @param {PacketList} packetlist - The signature packets
27426 */
27427 constructor(packetlist) {
27428 this.packets = packetlist || new PacketList();
27429 }
27430
27431 /**
27432 * Returns binary encoded signature
27433 * @returns {ReadableStream<Uint8Array>} Binary signature.
27434 */
27435 write() {
27436 return this.packets.write();
27437 }
27438
27439 /**
27440 * Returns ASCII armored text of signature
27441 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27442 * @returns {ReadableStream<String>} ASCII armor.
27443 */
27444 armor(config$1 = config) {
27445 return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config$1);
27446 }
27447
27448 /**
27449 * Returns an array of KeyIDs of all of the issuers who created this signature
27450 * @returns {Array<KeyID>} The Key IDs of the signing keys
27451 */
27452 getSigningKeyIDs() {
27453 return this.packets.map(packet => packet.issuerKeyID);
27454 }
27455}
27456
27457/**
27458 * reads an (optionally armored) OpenPGP signature and returns a signature object
27459 * @param {Object} options
27460 * @param {String} [options.armoredSignature] - Armored signature to be parsed
27461 * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed
27462 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
27463 * @returns {Promise<Signature>} New signature object.
27464 * @async
27465 * @static
27466 */
27467async function readSignature({ armoredSignature, binarySignature, config: config$1, ...rest }) {
27468 config$1 = { ...config, ...config$1 };
27469 let input = armoredSignature || binarySignature;
27470 if (!input) {
27471 throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');
27472 }
27473 if (armoredSignature && !util.isString(armoredSignature)) {
27474 throw new Error('readSignature: options.armoredSignature must be a string');
27475 }
27476 if (binarySignature && !util.isUint8Array(binarySignature)) {
27477 throw new Error('readSignature: options.binarySignature must be a Uint8Array');
27478 }
27479 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
27480
27481 if (armoredSignature) {
27482 const { type, data } = await unarmor(input, config$1);
27483 if (type !== enums.armor.signature) {
27484 throw new Error('Armored text not of type signature');
27485 }
27486 input = data;
27487 }
27488 const packetlist = await PacketList.fromBinary(input, allowedPackets$4, config$1);
27489 return new Signature(packetlist);
27490}
27491
27492/**
27493 * @fileoverview Provides helpers methods for key module
27494 * @module key/helper
27495 * @private
27496 */
27497
27498async function generateSecretSubkey(options, config) {
27499 const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);
27500 secretSubkeyPacket.packets = null;
27501 secretSubkeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);
27502 await secretSubkeyPacket.generate(options.rsaBits, options.curve);
27503 await secretSubkeyPacket.computeFingerprintAndKeyID();
27504 return secretSubkeyPacket;
27505}
27506
27507async function generateSecretKey(options, config) {
27508 const secretKeyPacket = new SecretKeyPacket(options.date, config);
27509 secretKeyPacket.packets = null;
27510 secretKeyPacket.algorithm = enums.write(enums.publicKey, options.algorithm);
27511 await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);
27512 await secretKeyPacket.computeFingerprintAndKeyID();
27513 return secretKeyPacket;
27514}
27515
27516/**
27517 * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.
27518 * @param {Array<SignaturePacket>} signatures - List of signatures
27519 * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature
27520 * @param {Date} date - Use the given date instead of the current time
27521 * @param {Object} config - full configuration
27522 * @returns {Promise<SignaturePacket>} The latest valid signature.
27523 * @async
27524 */
27525async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {
27526 let latestValid;
27527 let exception;
27528 for (let i = signatures.length - 1; i >= 0; i--) {
27529 try {
27530 if (
27531 (!latestValid || signatures[i].created >= latestValid.created)
27532 ) {
27533 await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);
27534 latestValid = signatures[i];
27535 }
27536 } catch (e) {
27537 exception = e;
27538 }
27539 }
27540 if (!latestValid) {
27541 throw util.wrapError(
27542 `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`
27543 .replace('certGeneric ', 'self-')
27544 .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase()),
27545 exception);
27546 }
27547 return latestValid;
27548}
27549
27550function isDataExpired(keyPacket, signature, date = new Date()) {
27551 const normDate = util.normalizeDate(date);
27552 if (normDate !== null) {
27553 const expirationTime = getKeyExpirationTime(keyPacket, signature);
27554 return !(keyPacket.created <= normDate && normDate < expirationTime);
27555 }
27556 return false;
27557}
27558
27559/**
27560 * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}
27561 * @param {SecretSubkeyPacket} subkey - Subkey key packet
27562 * @param {SecretKeyPacket} primaryKey - Primary key packet
27563 * @param {Object} options
27564 * @param {Object} config - Full configuration
27565 */
27566async function createBindingSignature(subkey, primaryKey, options, config) {
27567 const dataToSign = {};
27568 dataToSign.key = primaryKey;
27569 dataToSign.bind = subkey;
27570 const signatureProperties = { signatureType: enums.signature.subkeyBinding };
27571 if (options.sign) {
27572 signatureProperties.keyFlags = [enums.keyFlags.signData];
27573 signatureProperties.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, {
27574 signatureType: enums.signature.keyBinding
27575 }, options.date, undefined, undefined, undefined, config);
27576 } else {
27577 signatureProperties.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];
27578 }
27579 if (options.keyExpirationTime > 0) {
27580 signatureProperties.keyExpirationTime = options.keyExpirationTime;
27581 signatureProperties.keyNeverExpires = false;
27582 }
27583 const subkeySignaturePacket = await createSignaturePacket(dataToSign, null, primaryKey, signatureProperties, options.date, undefined, undefined, undefined, config);
27584 return subkeySignaturePacket;
27585}
27586
27587/**
27588 * Returns the preferred signature hash algorithm of a key
27589 * @param {Key} [key] - The key to get preferences from
27590 * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing
27591 * @param {Date} [date] - Use the given date for verification instead of the current time
27592 * @param {Object} [userID] - User ID
27593 * @param {Object} config - full configuration
27594 * @returns {Promise<enums.hash>}
27595 * @async
27596 */
27597async function getPreferredHashAlgo$2(key, keyPacket, date = new Date(), userID = {}, config) {
27598 let hashAlgo = config.preferredHashAlgorithm;
27599 let prefAlgo = hashAlgo;
27600 if (key) {
27601 const primaryUser = await key.getPrimaryUser(date, userID, config);
27602 if (primaryUser.selfCertification.preferredHashAlgorithms) {
27603 [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms;
27604 hashAlgo = mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ?
27605 prefAlgo : hashAlgo;
27606 }
27607 }
27608 switch (keyPacket.algorithm) {
27609 case enums.publicKey.ecdsa:
27610 case enums.publicKey.eddsaLegacy:
27611 case enums.publicKey.ed25519:
27612 prefAlgo = mod.getPreferredCurveHashAlgo(keyPacket.algorithm, keyPacket.publicParams.oid);
27613 }
27614 return mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ?
27615 prefAlgo : hashAlgo;
27616}
27617
27618/**
27619 * Returns the preferred symmetric/aead/compression algorithm for a set of keys
27620 * @param {'symmetric'|'aead'|'compression'} type - Type of preference to return
27621 * @param {Array<Key>} [keys] - Set of keys
27622 * @param {Date} [date] - Use the given date for verification instead of the current time
27623 * @param {Array} [userIDs] - User IDs
27624 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27625 * @returns {Promise<module:enums.symmetric|aead|compression>} Preferred algorithm
27626 * @async
27627 */
27628async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config$1 = config) {
27629 const defaultAlgo = { // these are all must-implement in rfc4880bis
27630 'symmetric': enums.symmetric.aes128,
27631 'aead': enums.aead.eax,
27632 'compression': enums.compression.uncompressed
27633 }[type];
27634 const preferredSenderAlgo = {
27635 'symmetric': config$1.preferredSymmetricAlgorithm,
27636 'aead': config$1.preferredAEADAlgorithm,
27637 'compression': config$1.preferredCompressionAlgorithm
27638 }[type];
27639 const prefPropertyName = {
27640 'symmetric': 'preferredSymmetricAlgorithms',
27641 'aead': 'preferredAEADAlgorithms',
27642 'compression': 'preferredCompressionAlgorithms'
27643 }[type];
27644
27645 // if preferredSenderAlgo appears in the prefs of all recipients, we pick it
27646 // otherwise we use the default algo
27647 // if no keys are available, preferredSenderAlgo is returned
27648 const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) {
27649 const primaryUser = await key.getPrimaryUser(date, userIDs[i], config$1);
27650 const recipientPrefs = primaryUser.selfCertification[prefPropertyName];
27651 return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;
27652 }));
27653 return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;
27654}
27655
27656/**
27657 * Create signature packet
27658 * @param {Object} dataToSign - Contains packets to be signed
27659 * @param {PrivateKey} privateKey - key to get preferences from
27660 * @param {SecretKeyPacket|
27661 * SecretSubkeyPacket} signingKeyPacket secret key packet for signing
27662 * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing
27663 * @param {Date} [date] - Override the creationtime of the signature
27664 * @param {Object} [userID] - User ID
27665 * @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 }]
27666 * @param {Object} [detached] - Whether to create a detached signature packet
27667 * @param {Object} config - full configuration
27668 * @returns {Promise<SignaturePacket>} Signature packet.
27669 */
27670async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, notations = [], detached = false, config) {
27671 if (signingKeyPacket.isDummy()) {
27672 throw new Error('Cannot sign with a gnu-dummy key.');
27673 }
27674 if (!signingKeyPacket.isDecrypted()) {
27675 throw new Error('Signing key is not decrypted.');
27676 }
27677 const signaturePacket = new SignaturePacket();
27678 Object.assign(signaturePacket, signatureProperties);
27679 signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;
27680 signaturePacket.hashAlgorithm = await getPreferredHashAlgo$2(privateKey, signingKeyPacket, date, userID, config);
27681 signaturePacket.rawNotations = notations;
27682 await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached);
27683 return signaturePacket;
27684}
27685
27686/**
27687 * Merges signatures from source[attr] to dest[attr]
27688 * @param {Object} source
27689 * @param {Object} dest
27690 * @param {String} attr
27691 * @param {Date} [date] - date to use for signature expiration check, instead of the current time
27692 * @param {Function} [checkFn] - signature only merged if true
27693 */
27694async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {
27695 source = source[attr];
27696 if (source) {
27697 if (!dest[attr].length) {
27698 dest[attr] = source;
27699 } else {
27700 await Promise.all(source.map(async function(sourceSig) {
27701 if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&
27702 !dest[attr].some(function(destSig) {
27703 return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());
27704 })) {
27705 dest[attr].push(sourceSig);
27706 }
27707 }));
27708 }
27709 }
27710}
27711
27712/**
27713 * Checks if a given certificate or binding signature is revoked
27714 * @param {SecretKeyPacket|
27715 * PublicKeyPacket} primaryKey The primary key packet
27716 * @param {Object} dataToVerify - The data to check
27717 * @param {Array<SignaturePacket>} revocations - The revocation signatures to check
27718 * @param {SignaturePacket} signature - The certificate or signature to check
27719 * @param {PublicSubkeyPacket|
27720 * SecretSubkeyPacket|
27721 * PublicKeyPacket|
27722 * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key
27723 * @param {Date} date - Use the given date instead of the current time
27724 * @param {Object} config - Full configuration
27725 * @returns {Promise<Boolean>} True if the signature revokes the data.
27726 * @async
27727 */
27728async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {
27729 key = key || primaryKey;
27730 const revocationKeyIDs = [];
27731 await Promise.all(revocations.map(async function(revocationSignature) {
27732 try {
27733 if (
27734 // Note: a third-party revocation signature could legitimately revoke a
27735 // self-signature if the signature has an authorized revocation key.
27736 // However, we don't support passing authorized revocation keys, nor
27737 // verifying such revocation signatures. Instead, we indicate an error
27738 // when parsing a key with an authorized revocation key, and ignore
27739 // third-party revocation signatures here. (It could also be revoking a
27740 // third-party key certification, which should only affect
27741 // `verifyAllCertifications`.)
27742 !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)
27743 ) {
27744 await revocationSignature.verify(
27745 key, signatureType, dataToVerify, config.revocationsExpire ? date : null, false, config
27746 );
27747
27748 // TODO get an identifier of the revoked object instead
27749 revocationKeyIDs.push(revocationSignature.issuerKeyID);
27750 }
27751 } catch (e) {}
27752 }));
27753 // TODO further verify that this is the signature that should be revoked
27754 if (signature) {
27755 signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :
27756 signature.revoked || false;
27757 return signature.revoked;
27758 }
27759 return revocationKeyIDs.length > 0;
27760}
27761
27762/**
27763 * Returns key expiration time based on the given certification signature.
27764 * The expiration time of the signature is ignored.
27765 * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check
27766 * @param {SignaturePacket} signature - signature to process
27767 * @returns {Date|Infinity} expiration time or infinity if the key does not expire
27768 */
27769function getKeyExpirationTime(keyPacket, signature) {
27770 let expirationTime;
27771 // check V4 expiration time
27772 if (signature.keyNeverExpires === false) {
27773 expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;
27774 }
27775 return expirationTime ? new Date(expirationTime) : Infinity;
27776}
27777
27778/**
27779 * Returns whether aead is supported by all keys in the set
27780 * @param {Array<Key>} keys - Set of keys
27781 * @param {Date} [date] - Use the given date for verification instead of the current time
27782 * @param {Array} [userIDs] - User IDs
27783 * @param {Object} config - full configuration
27784 * @returns {Promise<Boolean>}
27785 * @async
27786 */
27787async function isAEADSupported(keys, date = new Date(), userIDs = [], config$1 = config) {
27788 let supported = true;
27789 // TODO replace when Promise.some or Promise.any are implemented
27790 await Promise.all(keys.map(async function(key, i) {
27791 const primaryUser = await key.getPrimaryUser(date, userIDs[i], config$1);
27792 if (!primaryUser.selfCertification.features ||
27793 !(primaryUser.selfCertification.features[0] & enums.features.aead)) {
27794 supported = false;
27795 }
27796 }));
27797 return supported;
27798}
27799
27800function sanitizeKeyOptions(options, subkeyDefaults = {}) {
27801 options.type = options.type || subkeyDefaults.type;
27802 options.curve = options.curve || subkeyDefaults.curve;
27803 options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;
27804 options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;
27805 options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
27806 options.date = options.date || subkeyDefaults.date;
27807
27808 options.sign = options.sign || false;
27809
27810 switch (options.type) {
27811 case 'ecc':
27812 try {
27813 options.curve = enums.write(enums.curve, options.curve);
27814 } catch (e) {
27815 throw new Error('Unknown curve');
27816 }
27817 if (options.curve === enums.curve.ed25519Legacy || options.curve === enums.curve.curve25519Legacy) {
27818 options.curve = options.sign ? enums.curve.ed25519Legacy : enums.curve.curve25519Legacy;
27819 }
27820 if (options.sign) {
27821 options.algorithm = options.curve === enums.curve.ed25519Legacy ? enums.publicKey.eddsaLegacy : enums.publicKey.ecdsa;
27822 } else {
27823 options.algorithm = enums.publicKey.ecdh;
27824 }
27825 break;
27826 case 'rsa':
27827 options.algorithm = enums.publicKey.rsaEncryptSign;
27828 break;
27829 default:
27830 throw new Error(`Unsupported key type ${options.type}`);
27831 }
27832 return options;
27833}
27834
27835function isValidSigningKeyPacket(keyPacket, signature) {
27836 const keyAlgo = keyPacket.algorithm;
27837 return keyAlgo !== enums.publicKey.rsaEncrypt &&
27838 keyAlgo !== enums.publicKey.elgamal &&
27839 keyAlgo !== enums.publicKey.ecdh &&
27840 keyAlgo !== enums.publicKey.x25519 &&
27841 (!signature.keyFlags ||
27842 (signature.keyFlags[0] & enums.keyFlags.signData) !== 0);
27843}
27844
27845function isValidEncryptionKeyPacket(keyPacket, signature) {
27846 const keyAlgo = keyPacket.algorithm;
27847 return keyAlgo !== enums.publicKey.dsa &&
27848 keyAlgo !== enums.publicKey.rsaSign &&
27849 keyAlgo !== enums.publicKey.ecdsa &&
27850 keyAlgo !== enums.publicKey.eddsaLegacy &&
27851 keyAlgo !== enums.publicKey.ed25519 &&
27852 (!signature.keyFlags ||
27853 (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||
27854 (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0);
27855}
27856
27857function isValidDecryptionKeyPacket(signature, config) {
27858 if (config.allowInsecureDecryptionWithSigningKeys) {
27859 // This is only relevant for RSA keys, all other signing algorithms cannot decrypt
27860 return true;
27861 }
27862
27863 return !signature.keyFlags ||
27864 (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||
27865 (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;
27866}
27867
27868/**
27869 * Check key against blacklisted algorithms and minimum strength requirements.
27870 * @param {SecretKeyPacket|PublicKeyPacket|
27871 * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket
27872 * @param {Config} config
27873 * @throws {Error} if the key packet does not meet the requirements
27874 */
27875function checkKeyRequirements(keyPacket, config) {
27876 const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);
27877 const algoInfo = keyPacket.getAlgorithmInfo();
27878 if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {
27879 throw new Error(`${algoInfo.algorithm} keys are considered too weak.`);
27880 }
27881 switch (keyAlgo) {
27882 case enums.publicKey.rsaEncryptSign:
27883 case enums.publicKey.rsaSign:
27884 case enums.publicKey.rsaEncrypt:
27885 if (algoInfo.bits < config.minRSABits) {
27886 throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);
27887 }
27888 break;
27889 case enums.publicKey.ecdsa:
27890 case enums.publicKey.eddsaLegacy:
27891 case enums.publicKey.ecdh:
27892 if (config.rejectCurves.has(algoInfo.curve)) {
27893 throw new Error(`Support for ${algoInfo.algorithm} keys using curve ${algoInfo.curve} is disabled.`);
27894 }
27895 break;
27896 }
27897}
27898
27899/**
27900 * @module key/User
27901 * @private
27902 */
27903
27904/**
27905 * Class that represents an user ID or attribute packet and the relevant signatures.
27906 * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info
27907 * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with
27908 */
27909class User {
27910 constructor(userPacket, mainKey) {
27911 this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;
27912 this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;
27913 this.selfCertifications = [];
27914 this.otherCertifications = [];
27915 this.revocationSignatures = [];
27916 this.mainKey = mainKey;
27917 }
27918
27919 /**
27920 * Transforms structured user data to packetlist
27921 * @returns {PacketList}
27922 */
27923 toPacketList() {
27924 const packetlist = new PacketList();
27925 packetlist.push(this.userID || this.userAttribute);
27926 packetlist.push(...this.revocationSignatures);
27927 packetlist.push(...this.selfCertifications);
27928 packetlist.push(...this.otherCertifications);
27929 return packetlist;
27930 }
27931
27932 /**
27933 * Shallow clone
27934 * @returns {User}
27935 */
27936 clone() {
27937 const user = new User(this.userID || this.userAttribute, this.mainKey);
27938 user.selfCertifications = [...this.selfCertifications];
27939 user.otherCertifications = [...this.otherCertifications];
27940 user.revocationSignatures = [...this.revocationSignatures];
27941 return user;
27942 }
27943
27944 /**
27945 * Generate third-party certifications over this user and its primary key
27946 * @param {Array<PrivateKey>} signingKeys - Decrypted private keys for signing
27947 * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time
27948 * @param {Object} config - Full configuration
27949 * @returns {Promise<User>} New user with new certifications.
27950 * @async
27951 */
27952 async certify(signingKeys, date, config) {
27953 const primaryKey = this.mainKey.keyPacket;
27954 const dataToSign = {
27955 userID: this.userID,
27956 userAttribute: this.userAttribute,
27957 key: primaryKey
27958 };
27959 const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);
27960 user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) {
27961 if (!privateKey.isPrivate()) {
27962 throw new Error('Need private key for signing');
27963 }
27964 if (privateKey.hasSameFingerprintAs(primaryKey)) {
27965 throw new Error("The user's own key can only be used for self-certifications");
27966 }
27967 const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);
27968 return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, {
27969 // Most OpenPGP implementations use generic certification (0x10)
27970 signatureType: enums.signature.certGeneric,
27971 keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]
27972 }, date, undefined, undefined, undefined, config);
27973 }));
27974 await user.update(this, date, config);
27975 return user;
27976 }
27977
27978 /**
27979 * Checks if a given certificate of the user is revoked
27980 * @param {SignaturePacket} certificate - The certificate to verify
27981 * @param {PublicSubkeyPacket|
27982 * SecretSubkeyPacket|
27983 * PublicKeyPacket|
27984 * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key
27985 * @param {Date} [date] - Use the given date for verification instead of the current time
27986 * @param {Object} config - Full configuration
27987 * @returns {Promise<Boolean>} True if the certificate is revoked.
27988 * @async
27989 */
27990 async isRevoked(certificate, keyPacket, date = new Date(), config$1 = config) {
27991 const primaryKey = this.mainKey.keyPacket;
27992 return isDataRevoked(primaryKey, enums.signature.certRevocation, {
27993 key: primaryKey,
27994 userID: this.userID,
27995 userAttribute: this.userAttribute
27996 }, this.revocationSignatures, certificate, keyPacket, date, config$1);
27997 }
27998
27999 /**
28000 * Verifies the user certificate.
28001 * @param {SignaturePacket} certificate - A certificate of this user
28002 * @param {Array<PublicKey>} verificationKeys - Array of keys to verify certificate signatures
28003 * @param {Date} [date] - Use the given date instead of the current time
28004 * @param {Object} config - Full configuration
28005 * @returns {Promise<true|null>} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate
28006 * @throws if the user certificate is invalid.
28007 * @async
28008 */
28009 async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {
28010 const that = this;
28011 const primaryKey = this.mainKey.keyPacket;
28012 const dataToVerify = {
28013 userID: this.userID,
28014 userAttribute: this.userAttribute,
28015 key: primaryKey
28016 };
28017 const { issuerKeyID } = certificate;
28018 const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);
28019 if (issuerKeys.length === 0) {
28020 return null;
28021 }
28022 await Promise.all(issuerKeys.map(async key => {
28023 const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);
28024 if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {
28025 throw new Error('User certificate is revoked');
28026 }
28027 try {
28028 await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);
28029 } catch (e) {
28030 throw util.wrapError('User certificate is invalid', e);
28031 }
28032 }));
28033 return true;
28034 }
28035
28036 /**
28037 * Verifies all user certificates
28038 * @param {Array<PublicKey>} verificationKeys - Array of keys to verify certificate signatures
28039 * @param {Date} [date] - Use the given date instead of the current time
28040 * @param {Object} config - Full configuration
28041 * @returns {Promise<Array<{
28042 * keyID: module:type/keyid~KeyID,
28043 * valid: Boolean | null
28044 * }>>} List of signer's keyID and validity of signature.
28045 * Signature validity is null if the verification keys do not correspond to the certificate.
28046 * @async
28047 */
28048 async verifyAllCertifications(verificationKeys, date = new Date(), config) {
28049 const that = this;
28050 const certifications = this.selfCertifications.concat(this.otherCertifications);
28051 return Promise.all(certifications.map(async certification => ({
28052 keyID: certification.issuerKeyID,
28053 valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)
28054 })));
28055 }
28056
28057 /**
28058 * Verify User. Checks for existence of self signatures, revocation signatures
28059 * and validity of self signature.
28060 * @param {Date} date - Use the given date instead of the current time
28061 * @param {Object} config - Full configuration
28062 * @returns {Promise<true>} Status of user.
28063 * @throws {Error} if there are no valid self signatures.
28064 * @async
28065 */
28066 async verify(date = new Date(), config) {
28067 if (!this.selfCertifications.length) {
28068 throw new Error('No self-certifications found');
28069 }
28070 const that = this;
28071 const primaryKey = this.mainKey.keyPacket;
28072 const dataToVerify = {
28073 userID: this.userID,
28074 userAttribute: this.userAttribute,
28075 key: primaryKey
28076 };
28077 // TODO replace when Promise.some or Promise.any are implemented
28078 let exception;
28079 for (let i = this.selfCertifications.length - 1; i >= 0; i--) {
28080 try {
28081 const selfCertification = this.selfCertifications[i];
28082 if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {
28083 throw new Error('Self-certification is revoked');
28084 }
28085 try {
28086 await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);
28087 } catch (e) {
28088 throw util.wrapError('Self-certification is invalid', e);
28089 }
28090 return true;
28091 } catch (e) {
28092 exception = e;
28093 }
28094 }
28095 throw exception;
28096 }
28097
28098 /**
28099 * Update user with new components from specified user
28100 * @param {User} sourceUser - Source user to merge
28101 * @param {Date} date - Date to verify the validity of signatures
28102 * @param {Object} config - Full configuration
28103 * @returns {Promise<undefined>}
28104 * @async
28105 */
28106 async update(sourceUser, date, config) {
28107 const primaryKey = this.mainKey.keyPacket;
28108 const dataToVerify = {
28109 userID: this.userID,
28110 userAttribute: this.userAttribute,
28111 key: primaryKey
28112 };
28113 // self signatures
28114 await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) {
28115 try {
28116 await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);
28117 return true;
28118 } catch (e) {
28119 return false;
28120 }
28121 });
28122 // other signatures
28123 await mergeSignatures(sourceUser, this, 'otherCertifications', date);
28124 // revocation signatures
28125 await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) {
28126 return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);
28127 });
28128 }
28129
28130 /**
28131 * Revokes the user
28132 * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation
28133 * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation
28134 * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
28135 * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation
28136 * @param {Date} date - optional, override the creationtime of the revocation signature
28137 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28138 * @returns {Promise<User>} New user with revocation signature.
28139 * @async
28140 */
28141 async revoke(
28142 primaryKey,
28143 {
28144 flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,
28145 string: reasonForRevocationString = ''
28146 } = {},
28147 date = new Date(),
28148 config$1 = config
28149 ) {
28150 const dataToSign = {
28151 userID: this.userID,
28152 userAttribute: this.userAttribute,
28153 key: primaryKey
28154 };
28155 const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);
28156 user.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, {
28157 signatureType: enums.signature.certRevocation,
28158 reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),
28159 reasonForRevocationString
28160 }, date, undefined, undefined, false, config$1));
28161 await user.update(this);
28162 return user;
28163 }
28164}
28165
28166/**
28167 * @module key/Subkey
28168 * @private
28169 */
28170
28171/**
28172 * Class that represents a subkey packet and the relevant signatures.
28173 * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID
28174 * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint
28175 * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs
28176 * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo
28177 * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime
28178 * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted
28179 */
28180class Subkey {
28181 /**
28182 * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey
28183 * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey
28184 */
28185 constructor(subkeyPacket, mainKey) {
28186 this.keyPacket = subkeyPacket;
28187 this.bindingSignatures = [];
28188 this.revocationSignatures = [];
28189 this.mainKey = mainKey;
28190 }
28191
28192 /**
28193 * Transforms structured subkey data to packetlist
28194 * @returns {PacketList}
28195 */
28196 toPacketList() {
28197 const packetlist = new PacketList();
28198 packetlist.push(this.keyPacket);
28199 packetlist.push(...this.revocationSignatures);
28200 packetlist.push(...this.bindingSignatures);
28201 return packetlist;
28202 }
28203
28204 /**
28205 * Shallow clone
28206 * @return {Subkey}
28207 */
28208 clone() {
28209 const subkey = new Subkey(this.keyPacket, this.mainKey);
28210 subkey.bindingSignatures = [...this.bindingSignatures];
28211 subkey.revocationSignatures = [...this.revocationSignatures];
28212 return subkey;
28213 }
28214
28215 /**
28216 * Checks if a binding signature of a subkey is revoked
28217 * @param {SignaturePacket} signature - The binding signature to verify
28218 * @param {PublicSubkeyPacket|
28219 * SecretSubkeyPacket|
28220 * PublicKeyPacket|
28221 * SecretKeyPacket} key, optional The key to verify the signature
28222 * @param {Date} [date] - Use the given date for verification instead of the current time
28223 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28224 * @returns {Promise<Boolean>} True if the binding signature is revoked.
28225 * @async
28226 */
28227 async isRevoked(signature, key, date = new Date(), config$1 = config) {
28228 const primaryKey = this.mainKey.keyPacket;
28229 return isDataRevoked(
28230 primaryKey, enums.signature.subkeyRevocation, {
28231 key: primaryKey,
28232 bind: this.keyPacket
28233 }, this.revocationSignatures, signature, key, date, config$1
28234 );
28235 }
28236
28237 /**
28238 * Verify subkey. Checks for revocation signatures, expiration time
28239 * and valid binding signature.
28240 * @param {Date} date - Use the given date instead of the current time
28241 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28242 * @returns {Promise<SignaturePacket>}
28243 * @throws {Error} if the subkey is invalid.
28244 * @async
28245 */
28246 async verify(date = new Date(), config$1 = config) {
28247 const primaryKey = this.mainKey.keyPacket;
28248 const dataToVerify = { key: primaryKey, bind: this.keyPacket };
28249 // check subkey binding signatures
28250 const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1);
28251 // check binding signature is not revoked
28252 if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config$1)) {
28253 throw new Error('Subkey is revoked');
28254 }
28255 // check for expiration time
28256 if (isDataExpired(this.keyPacket, bindingSignature, date)) {
28257 throw new Error('Subkey is expired');
28258 }
28259 return bindingSignature;
28260 }
28261
28262 /**
28263 * Returns the expiration time of the subkey or Infinity if key does not expire.
28264 * Returns null if the subkey is invalid.
28265 * @param {Date} date - Use the given date instead of the current time
28266 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28267 * @returns {Promise<Date | Infinity | null>}
28268 * @async
28269 */
28270 async getExpirationTime(date = new Date(), config$1 = config) {
28271 const primaryKey = this.mainKey.keyPacket;
28272 const dataToVerify = { key: primaryKey, bind: this.keyPacket };
28273 let bindingSignature;
28274 try {
28275 bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1);
28276 } catch (e) {
28277 return null;
28278 }
28279 const keyExpiry = getKeyExpirationTime(this.keyPacket, bindingSignature);
28280 const sigExpiry = bindingSignature.getExpirationTime();
28281 return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;
28282 }
28283
28284 /**
28285 * Update subkey with new components from specified subkey
28286 * @param {Subkey} subkey - Source subkey to merge
28287 * @param {Date} [date] - Date to verify validity of signatures
28288 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28289 * @throws {Error} if update failed
28290 * @async
28291 */
28292 async update(subkey, date = new Date(), config$1 = config) {
28293 const primaryKey = this.mainKey.keyPacket;
28294 if (!this.hasSameFingerprintAs(subkey)) {
28295 throw new Error('Subkey update method: fingerprints of subkeys not equal');
28296 }
28297 // key packet
28298 if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&
28299 subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {
28300 this.keyPacket = subkey.keyPacket;
28301 }
28302 // update missing binding signatures
28303 const that = this;
28304 const dataToVerify = { key: primaryKey, bind: that.keyPacket };
28305 await mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) {
28306 for (let i = 0; i < that.bindingSignatures.length; i++) {
28307 if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {
28308 if (srcBindSig.created > that.bindingSignatures[i].created) {
28309 that.bindingSignatures[i] = srcBindSig;
28310 }
28311 return false;
28312 }
28313 }
28314 try {
28315 await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config$1);
28316 return true;
28317 } catch (e) {
28318 return false;
28319 }
28320 });
28321 // revocation signatures
28322 await mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) {
28323 return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config$1);
28324 });
28325 }
28326
28327 /**
28328 * Revokes the subkey
28329 * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation
28330 * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation
28331 * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
28332 * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation
28333 * @param {Date} date - optional, override the creationtime of the revocation signature
28334 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28335 * @returns {Promise<Subkey>} New subkey with revocation signature.
28336 * @async
28337 */
28338 async revoke(
28339 primaryKey,
28340 {
28341 flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,
28342 string: reasonForRevocationString = ''
28343 } = {},
28344 date = new Date(),
28345 config$1 = config
28346 ) {
28347 const dataToSign = { key: primaryKey, bind: this.keyPacket };
28348 const subkey = new Subkey(this.keyPacket, this.mainKey);
28349 subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, {
28350 signatureType: enums.signature.subkeyRevocation,
28351 reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),
28352 reasonForRevocationString
28353 }, date, undefined, undefined, false, config$1));
28354 await subkey.update(this);
28355 return subkey;
28356 }
28357
28358 hasSameFingerprintAs(other) {
28359 return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);
28360 }
28361}
28362
28363['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {
28364 Subkey.prototype[name] =
28365 function() {
28366 return this.keyPacket[name]();
28367 };
28368});
28369
28370// GPG4Browsers - An OpenPGP implementation in javascript
28371
28372// A key revocation certificate can contain the following packets
28373const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
28374const mainKeyPacketTags = new Set([enums.packet.publicKey, enums.packet.privateKey]);
28375const keyPacketTags = new Set([
28376 enums.packet.publicKey, enums.packet.privateKey,
28377 enums.packet.publicSubkey, enums.packet.privateSubkey
28378]);
28379
28380/**
28381 * Abstract class that represents an OpenPGP key. Must contain a primary key.
28382 * Can contain additional subkeys, signatures, user ids, user attributes.
28383 * @borrows PublicKeyPacket#getKeyID as Key#getKeyID
28384 * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint
28385 * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs
28386 * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo
28387 * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime
28388 */
28389class Key {
28390 /**
28391 * Transforms packetlist to structured key data
28392 * @param {PacketList} packetlist - The packets that form a key
28393 * @param {Set<enums.packet>} disallowedPackets - disallowed packet tags
28394 */
28395 packetListToStructure(packetlist, disallowedPackets = new Set()) {
28396 let user;
28397 let primaryKeyID;
28398 let subkey;
28399 let ignoreUntil;
28400
28401 for (const packet of packetlist) {
28402
28403 if (packet instanceof UnparseablePacket) {
28404 const isUnparseableKeyPacket = keyPacketTags.has(packet.tag);
28405 if (isUnparseableKeyPacket && !ignoreUntil) {
28406 // Since non-key packets apply to the preceding key packet, if a (sub)key is Unparseable we must
28407 // discard all non-key packets that follow, until another (sub)key packet is found.
28408 if (mainKeyPacketTags.has(packet.tag)) {
28409 ignoreUntil = mainKeyPacketTags;
28410 } else {
28411 ignoreUntil = keyPacketTags;
28412 }
28413 }
28414 continue;
28415 }
28416
28417 const tag = packet.constructor.tag;
28418 if (ignoreUntil) {
28419 if (!ignoreUntil.has(tag)) continue;
28420 ignoreUntil = null;
28421 }
28422 if (disallowedPackets.has(tag)) {
28423 throw new Error(`Unexpected packet type: ${tag}`);
28424 }
28425 switch (tag) {
28426 case enums.packet.publicKey:
28427 case enums.packet.secretKey:
28428 if (this.keyPacket) {
28429 throw new Error('Key block contains multiple keys');
28430 }
28431 this.keyPacket = packet;
28432 primaryKeyID = this.getKeyID();
28433 if (!primaryKeyID) {
28434 throw new Error('Missing Key ID');
28435 }
28436 break;
28437 case enums.packet.userID:
28438 case enums.packet.userAttribute:
28439 user = new User(packet, this);
28440 this.users.push(user);
28441 break;
28442 case enums.packet.publicSubkey:
28443 case enums.packet.secretSubkey:
28444 user = null;
28445 subkey = new Subkey(packet, this);
28446 this.subkeys.push(subkey);
28447 break;
28448 case enums.packet.signature:
28449 switch (packet.signatureType) {
28450 case enums.signature.certGeneric:
28451 case enums.signature.certPersona:
28452 case enums.signature.certCasual:
28453 case enums.signature.certPositive:
28454 if (!user) {
28455 util.printDebug('Dropping certification signatures without preceding user packet');
28456 continue;
28457 }
28458 if (packet.issuerKeyID.equals(primaryKeyID)) {
28459 user.selfCertifications.push(packet);
28460 } else {
28461 user.otherCertifications.push(packet);
28462 }
28463 break;
28464 case enums.signature.certRevocation:
28465 if (user) {
28466 user.revocationSignatures.push(packet);
28467 } else {
28468 this.directSignatures.push(packet);
28469 }
28470 break;
28471 case enums.signature.key:
28472 this.directSignatures.push(packet);
28473 break;
28474 case enums.signature.subkeyBinding:
28475 if (!subkey) {
28476 util.printDebug('Dropping subkey binding signature without preceding subkey packet');
28477 continue;
28478 }
28479 subkey.bindingSignatures.push(packet);
28480 break;
28481 case enums.signature.keyRevocation:
28482 this.revocationSignatures.push(packet);
28483 break;
28484 case enums.signature.subkeyRevocation:
28485 if (!subkey) {
28486 util.printDebug('Dropping subkey revocation signature without preceding subkey packet');
28487 continue;
28488 }
28489 subkey.revocationSignatures.push(packet);
28490 break;
28491 }
28492 break;
28493 }
28494 }
28495 }
28496
28497 /**
28498 * Transforms structured key data to packetlist
28499 * @returns {PacketList} The packets that form a key.
28500 */
28501 toPacketList() {
28502 const packetlist = new PacketList();
28503 packetlist.push(this.keyPacket);
28504 packetlist.push(...this.revocationSignatures);
28505 packetlist.push(...this.directSignatures);
28506 this.users.map(user => packetlist.push(...user.toPacketList()));
28507 this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));
28508 return packetlist;
28509 }
28510
28511 /**
28512 * 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.
28513 * @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.
28514 * @returns {Promise<Key>} Clone of the key.
28515 */
28516 clone(clonePrivateParams = false) {
28517 const key = new this.constructor(this.toPacketList());
28518 if (clonePrivateParams) {
28519 key.getKeys().forEach(k => {
28520 // shallow clone the key packets
28521 k.keyPacket = Object.create(
28522 Object.getPrototypeOf(k.keyPacket),
28523 Object.getOwnPropertyDescriptors(k.keyPacket)
28524 );
28525 if (!k.keyPacket.isDecrypted()) return;
28526 // deep clone the private params, which are cleared during encryption
28527 const privateParams = {};
28528 Object.keys(k.keyPacket.privateParams).forEach(name => {
28529 privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);
28530 });
28531 k.keyPacket.privateParams = privateParams;
28532 });
28533 }
28534 return key;
28535 }
28536
28537 /**
28538 * Returns an array containing all public or private subkeys matching keyID;
28539 * If no keyID is given, returns all subkeys.
28540 * @param {type/keyID} [keyID] - key ID to look for
28541 * @returns {Array<Subkey>} array of subkeys
28542 */
28543 getSubkeys(keyID = null) {
28544 const subkeys = this.subkeys.filter(subkey => (
28545 !keyID || subkey.getKeyID().equals(keyID, true)
28546 ));
28547 return subkeys;
28548 }
28549
28550 /**
28551 * Returns an array containing all public or private keys matching keyID.
28552 * If no keyID is given, returns all keys, starting with the primary key.
28553 * @param {type/keyid~KeyID} [keyID] - key ID to look for
28554 * @returns {Array<Key|Subkey>} array of keys
28555 */
28556 getKeys(keyID = null) {
28557 const keys = [];
28558 if (!keyID || this.getKeyID().equals(keyID, true)) {
28559 keys.push(this);
28560 }
28561 return keys.concat(this.getSubkeys(keyID));
28562 }
28563
28564 /**
28565 * Returns key IDs of all keys
28566 * @returns {Array<module:type/keyid~KeyID>}
28567 */
28568 getKeyIDs() {
28569 return this.getKeys().map(key => key.getKeyID());
28570 }
28571
28572 /**
28573 * Returns userIDs
28574 * @returns {Array<string>} Array of userIDs.
28575 */
28576 getUserIDs() {
28577 return this.users.map(user => {
28578 return user.userID ? user.userID.userID : null;
28579 }).filter(userID => userID !== null);
28580 }
28581
28582 /**
28583 * Returns binary encoded key
28584 * @returns {Uint8Array} Binary key.
28585 */
28586 write() {
28587 return this.toPacketList().write();
28588 }
28589
28590 /**
28591 * Returns last created key or key by given keyID that is available for signing and verification
28592 * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve
28593 * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date
28594 * @param {Object} [userID] - filter keys for the given user ID
28595 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28596 * @returns {Promise<Key|Subkey>} signing key
28597 * @throws if no valid signing key was found
28598 * @async
28599 */
28600 async getSigningKey(keyID = null, date = new Date(), userID = {}, config$1 = config) {
28601 await this.verifyPrimaryKey(date, userID, config$1);
28602 const primaryKey = this.keyPacket;
28603 const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);
28604 let exception;
28605 for (const subkey of subkeys) {
28606 if (!keyID || subkey.getKeyID().equals(keyID)) {
28607 try {
28608 await subkey.verify(date, config$1);
28609 const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };
28610 const bindingSignature = await getLatestValidSignature(
28611 subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1
28612 );
28613 if (!isValidSigningKeyPacket(subkey.keyPacket, bindingSignature)) {
28614 continue;
28615 }
28616 if (!bindingSignature.embeddedSignature) {
28617 throw new Error('Missing embedded signature');
28618 }
28619 // verify embedded signature
28620 await getLatestValidSignature(
28621 [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config$1
28622 );
28623 checkKeyRequirements(subkey.keyPacket, config$1);
28624 return subkey;
28625 } catch (e) {
28626 exception = e;
28627 }
28628 }
28629 }
28630
28631 try {
28632 const primaryUser = await this.getPrimaryUser(date, userID, config$1);
28633 if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&
28634 isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config$1)) {
28635 checkKeyRequirements(primaryKey, config$1);
28636 return this;
28637 }
28638 } catch (e) {
28639 exception = e;
28640 }
28641 throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);
28642 }
28643
28644 /**
28645 * Returns last created key or key by given keyID that is available for encryption or decryption
28646 * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve
28647 * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date
28648 * @param {Object} [userID] - filter keys for the given user ID
28649 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28650 * @returns {Promise<Key|Subkey>} encryption key
28651 * @throws if no valid encryption key was found
28652 * @async
28653 */
28654 async getEncryptionKey(keyID, date = new Date(), userID = {}, config$1 = config) {
28655 await this.verifyPrimaryKey(date, userID, config$1);
28656 const primaryKey = this.keyPacket;
28657 // V4: by convention subkeys are preferred for encryption service
28658 const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);
28659 let exception;
28660 for (const subkey of subkeys) {
28661 if (!keyID || subkey.getKeyID().equals(keyID)) {
28662 try {
28663 await subkey.verify(date, config$1);
28664 const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };
28665 const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1);
28666 if (isValidEncryptionKeyPacket(subkey.keyPacket, bindingSignature)) {
28667 checkKeyRequirements(subkey.keyPacket, config$1);
28668 return subkey;
28669 }
28670 } catch (e) {
28671 exception = e;
28672 }
28673 }
28674 }
28675
28676 try {
28677 // if no valid subkey for encryption, evaluate primary key
28678 const primaryUser = await this.getPrimaryUser(date, userID, config$1);
28679 if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&
28680 isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) {
28681 checkKeyRequirements(primaryKey, config$1);
28682 return this;
28683 }
28684 } catch (e) {
28685 exception = e;
28686 }
28687 throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);
28688 }
28689
28690 /**
28691 * Checks if a signature on a key is revoked
28692 * @param {SignaturePacket} signature - The signature to verify
28693 * @param {PublicSubkeyPacket|
28694 * SecretSubkeyPacket|
28695 * PublicKeyPacket|
28696 * SecretKeyPacket} key, optional The key to verify the signature
28697 * @param {Date} [date] - Use the given date for verification, instead of the current time
28698 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28699 * @returns {Promise<Boolean>} True if the certificate is revoked.
28700 * @async
28701 */
28702 async isRevoked(signature, key, date = new Date(), config$1 = config) {
28703 return isDataRevoked(
28704 this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config$1
28705 );
28706 }
28707
28708 /**
28709 * Verify primary key. Checks for revocation signatures, expiration time
28710 * and valid self signature. Throws if the primary key is invalid.
28711 * @param {Date} [date] - Use the given date for verification instead of the current time
28712 * @param {Object} [userID] - User ID
28713 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28714 * @throws {Error} If key verification failed
28715 * @async
28716 */
28717 async verifyPrimaryKey(date = new Date(), userID = {}, config$1 = config) {
28718 const primaryKey = this.keyPacket;
28719 // check for key revocation signatures
28720 if (await this.isRevoked(null, null, date, config$1)) {
28721 throw new Error('Primary key is revoked');
28722 }
28723 // check for valid, unrevoked, unexpired self signature
28724 const { selfCertification } = await this.getPrimaryUser(date, userID, config$1);
28725 // check for expiration time in binding signatures
28726 if (isDataExpired(primaryKey, selfCertification, date)) {
28727 throw new Error('Primary key is expired');
28728 }
28729 // check for expiration time in direct signatures
28730 const directSignature = await getLatestValidSignature(
28731 this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config$1
28732 ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key
28733
28734 if (directSignature && isDataExpired(primaryKey, directSignature, date)) {
28735 throw new Error('Primary key is expired');
28736 }
28737 }
28738
28739 /**
28740 * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.
28741 * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.
28742 * @param {Object} [userID] - User ID to consider instead of the primary user
28743 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28744 * @returns {Promise<Date | Infinity | null>}
28745 * @async
28746 */
28747 async getExpirationTime(userID, config$1 = config) {
28748 let primaryKeyExpiry;
28749 try {
28750 const { selfCertification } = await this.getPrimaryUser(null, userID, config$1);
28751 const selfSigKeyExpiry = getKeyExpirationTime(this.keyPacket, selfCertification);
28752 const selfSigExpiry = selfCertification.getExpirationTime();
28753 const directSignature = await getLatestValidSignature(
28754 this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config$1
28755 ).catch(() => {});
28756 if (directSignature) {
28757 const directSigKeyExpiry = getKeyExpirationTime(this.keyPacket, directSignature);
28758 // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,
28759 // causing a discountinous validy period for the key
28760 primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);
28761 } else {
28762 primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;
28763 }
28764 } catch (e) {
28765 primaryKeyExpiry = null;
28766 }
28767
28768 return util.normalizeDate(primaryKeyExpiry);
28769 }
28770
28771
28772 /**
28773 * Returns primary user and most significant (latest valid) self signature
28774 * - if multiple primary users exist, returns the one with the latest self signature
28775 * - otherwise, returns the user with the latest self signature
28776 * @param {Date} [date] - Use the given date for verification instead of the current time
28777 * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
28778 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28779 * @returns {Promise<{
28780 * user: User,
28781 * selfCertification: SignaturePacket
28782 * }>} The primary user and the self signature
28783 * @async
28784 */
28785 async getPrimaryUser(date = new Date(), userID = {}, config$1 = config) {
28786 const primaryKey = this.keyPacket;
28787 const users = [];
28788 let exception;
28789 for (let i = 0; i < this.users.length; i++) {
28790 try {
28791 const user = this.users[i];
28792 if (!user.userID) {
28793 continue;
28794 }
28795 if (
28796 (userID.name !== undefined && user.userID.name !== userID.name) ||
28797 (userID.email !== undefined && user.userID.email !== userID.email) ||
28798 (userID.comment !== undefined && user.userID.comment !== userID.comment)
28799 ) {
28800 throw new Error('Could not find user that matches that user ID');
28801 }
28802 const dataToVerify = { userID: user.userID, key: primaryKey };
28803 const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config$1);
28804 users.push({ index: i, user, selfCertification });
28805 } catch (e) {
28806 exception = e;
28807 }
28808 }
28809 if (!users.length) {
28810 throw exception || new Error('Could not find primary user');
28811 }
28812 await Promise.all(users.map(async function (a) {
28813 return a.selfCertification.revoked || a.user.isRevoked(a.selfCertification, null, date, config$1);
28814 }));
28815 // sort by primary user flag and signature creation time
28816 const primaryUser = users.sort(function(a, b) {
28817 const A = a.selfCertification;
28818 const B = b.selfCertification;
28819 return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;
28820 }).pop();
28821 const { user, selfCertification: cert } = primaryUser;
28822 if (cert.revoked || await user.isRevoked(cert, null, date, config$1)) {
28823 throw new Error('Primary user is revoked');
28824 }
28825 return primaryUser;
28826 }
28827
28828 /**
28829 * Update key with new components from specified key with same key ID:
28830 * users, subkeys, certificates are merged into the destination key,
28831 * duplicates and expired signatures are ignored.
28832 *
28833 * If the source key is a private key and the destination key is public,
28834 * a private key is returned.
28835 * @param {Key} sourceKey - Source key to merge
28836 * @param {Date} [date] - Date to verify validity of signatures and keys
28837 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28838 * @returns {Promise<Key>} updated key
28839 * @async
28840 */
28841 async update(sourceKey, date = new Date(), config$1 = config) {
28842 if (!this.hasSameFingerprintAs(sourceKey)) {
28843 throw new Error('Primary key fingerprints must be equal to update the key');
28844 }
28845 if (!this.isPrivate() && sourceKey.isPrivate()) {
28846 // check for equal subkey packets
28847 const equal = (this.subkeys.length === sourceKey.subkeys.length) &&
28848 (this.subkeys.every(destSubkey => {
28849 return sourceKey.subkeys.some(srcSubkey => {
28850 return destSubkey.hasSameFingerprintAs(srcSubkey);
28851 });
28852 }));
28853 if (!equal) {
28854 throw new Error('Cannot update public key with private key if subkeys mismatch');
28855 }
28856
28857 return sourceKey.update(this, config$1);
28858 }
28859 // from here on, either:
28860 // - destination key is private, source key is public
28861 // - the keys are of the same type
28862 // hence we don't need to convert the destination key type
28863 const updatedKey = this.clone();
28864 // revocation signatures
28865 await mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {
28866 return isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config$1);
28867 });
28868 // direct signatures
28869 await mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);
28870 // update users
28871 await Promise.all(sourceKey.users.map(async srcUser => {
28872 // multiple users with the same ID/attribute are not explicitly disallowed by the spec
28873 // hence we support them, just in case
28874 const usersToUpdate = updatedKey.users.filter(dstUser => (
28875 (srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||
28876 (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))
28877 ));
28878 if (usersToUpdate.length > 0) {
28879 await Promise.all(
28880 usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config$1))
28881 );
28882 } else {
28883 const newUser = srcUser.clone();
28884 newUser.mainKey = updatedKey;
28885 updatedKey.users.push(newUser);
28886 }
28887 }));
28888 // update subkeys
28889 await Promise.all(sourceKey.subkeys.map(async srcSubkey => {
28890 // multiple subkeys with same fingerprint might be preset
28891 const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (
28892 dstSubkey.hasSameFingerprintAs(srcSubkey)
28893 ));
28894 if (subkeysToUpdate.length > 0) {
28895 await Promise.all(
28896 subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config$1))
28897 );
28898 } else {
28899 const newSubkey = srcSubkey.clone();
28900 newSubkey.mainKey = updatedKey;
28901 updatedKey.subkeys.push(newSubkey);
28902 }
28903 }));
28904
28905 return updatedKey;
28906 }
28907
28908 /**
28909 * Get revocation certificate from a revoked key.
28910 * (To get a revocation certificate for an unrevoked key, call revoke() first.)
28911 * @param {Date} date - Use the given date instead of the current time
28912 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28913 * @returns {Promise<String>} Armored revocation certificate.
28914 * @async
28915 */
28916 async getRevocationCertificate(date = new Date(), config$1 = config) {
28917 const dataToVerify = { key: this.keyPacket };
28918 const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config$1);
28919 const packetlist = new PacketList();
28920 packetlist.push(revocationSignature);
28921 return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate');
28922 }
28923
28924 /**
28925 * Applies a revocation certificate to a key
28926 * This adds the first signature packet in the armored text to the key,
28927 * if it is a valid revocation signature.
28928 * @param {String} revocationCertificate - armored revocation certificate
28929 * @param {Date} [date] - Date to verify the certificate
28930 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28931 * @returns {Promise<Key>} Revoked key.
28932 * @async
28933 */
28934 async applyRevocationCertificate(revocationCertificate, date = new Date(), config$1 = config) {
28935 const input = await unarmor(revocationCertificate, config$1);
28936 const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config$1);
28937 const revocationSignature = packetlist.findPacket(enums.packet.signature);
28938 if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {
28939 throw new Error('Could not find revocation signature packet');
28940 }
28941 if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {
28942 throw new Error('Revocation signature does not match key');
28943 }
28944 try {
28945 await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config$1);
28946 } catch (e) {
28947 throw util.wrapError('Could not verify revocation signature', e);
28948 }
28949 const key = this.clone();
28950 key.revocationSignatures.push(revocationSignature);
28951 return key;
28952 }
28953
28954 /**
28955 * Signs primary user of key
28956 * @param {Array<PrivateKey>} privateKeys - decrypted private keys for signing
28957 * @param {Date} [date] - Use the given date for verification instead of the current time
28958 * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
28959 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28960 * @returns {Promise<Key>} Key with new certificate signature.
28961 * @async
28962 */
28963 async signPrimaryUser(privateKeys, date, userID, config$1 = config) {
28964 const { index, user } = await this.getPrimaryUser(date, userID, config$1);
28965 const userSign = await user.certify(privateKeys, date, config$1);
28966 const key = this.clone();
28967 key.users[index] = userSign;
28968 return key;
28969 }
28970
28971 /**
28972 * Signs all users of key
28973 * @param {Array<PrivateKey>} privateKeys - decrypted private keys for signing
28974 * @param {Date} [date] - Use the given date for signing, instead of the current time
28975 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28976 * @returns {Promise<Key>} Key with new certificate signature.
28977 * @async
28978 */
28979 async signAllUsers(privateKeys, date = new Date(), config$1 = config) {
28980 const key = this.clone();
28981 key.users = await Promise.all(this.users.map(function(user) {
28982 return user.certify(privateKeys, date, config$1);
28983 }));
28984 return key;
28985 }
28986
28987 /**
28988 * Verifies primary user of key
28989 * - if no arguments are given, verifies the self certificates;
28990 * - otherwise, verifies all certificates signed with given keys.
28991 * @param {Array<PublicKey>} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key
28992 * @param {Date} [date] - Use the given date for verification instead of the current time
28993 * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
28994 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28995 * @returns {Promise<Array<{
28996 * keyID: module:type/keyid~KeyID,
28997 * valid: Boolean|null
28998 * }>>} List of signer's keyID and validity of signature.
28999 * Signature validity is null if the verification keys do not correspond to the certificate.
29000 * @async
29001 */
29002 async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config$1 = config) {
29003 const primaryKey = this.keyPacket;
29004 const { user } = await this.getPrimaryUser(date, userID, config$1);
29005 const results = verificationKeys ?
29006 await user.verifyAllCertifications(verificationKeys, date, config$1) :
29007 [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }];
29008 return results;
29009 }
29010
29011 /**
29012 * Verifies all users of key
29013 * - if no arguments are given, verifies the self certificates;
29014 * - otherwise, verifies all certificates signed with given keys.
29015 * @param {Array<PublicKey>} [verificationKeys] - array of keys to verify certificate signatures
29016 * @param {Date} [date] - Use the given date for verification instead of the current time
29017 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29018 * @returns {Promise<Array<{
29019 * userID: String,
29020 * keyID: module:type/keyid~KeyID,
29021 * valid: Boolean|null
29022 * }>>} List of userID, signer's keyID and validity of signature.
29023 * Signature validity is null if the verification keys do not correspond to the certificate.
29024 * @async
29025 */
29026 async verifyAllUsers(verificationKeys, date = new Date(), config$1 = config) {
29027 const primaryKey = this.keyPacket;
29028 const results = [];
29029 await Promise.all(this.users.map(async user => {
29030 const signatures = verificationKeys ?
29031 await user.verifyAllCertifications(verificationKeys, date, config$1) :
29032 [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config$1).catch(() => false) }];
29033
29034 results.push(...signatures.map(
29035 signature => ({
29036 userID: user.userID ? user.userID.userID : null,
29037 userAttribute: user.userAttribute,
29038 keyID: signature.keyID,
29039 valid: signature.valid
29040 }))
29041 );
29042 }));
29043 return results;
29044 }
29045}
29046
29047['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {
29048 Key.prototype[name] =
29049 Subkey.prototype[name];
29050});
29051
29052// This library is free software; you can redistribute it and/or
29053
29054/**
29055 * Class that represents an OpenPGP Public Key
29056 */
29057class PublicKey extends Key {
29058 /**
29059 * @param {PacketList} packetlist - The packets that form this key
29060 */
29061 constructor(packetlist) {
29062 super();
29063 this.keyPacket = null;
29064 this.revocationSignatures = [];
29065 this.directSignatures = [];
29066 this.users = [];
29067 this.subkeys = [];
29068 if (packetlist) {
29069 this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));
29070 if (!this.keyPacket) {
29071 throw new Error('Invalid key: missing public-key packet');
29072 }
29073 }
29074 }
29075
29076 /**
29077 * Returns true if this is a private key
29078 * @returns {false}
29079 */
29080 isPrivate() {
29081 return false;
29082 }
29083
29084 /**
29085 * Returns key as public key (shallow copy)
29086 * @returns {PublicKey} New public Key
29087 */
29088 toPublic() {
29089 return this;
29090 }
29091
29092 /**
29093 * Returns ASCII armored text of key
29094 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29095 * @returns {ReadableStream<String>} ASCII armor.
29096 */
29097 armor(config$1 = config) {
29098 return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, config$1);
29099 }
29100}
29101
29102/**
29103 * Class that represents an OpenPGP Private key
29104 */
29105class PrivateKey extends PublicKey {
29106 /**
29107 * @param {PacketList} packetlist - The packets that form this key
29108 */
29109 constructor(packetlist) {
29110 super();
29111 this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));
29112 if (!this.keyPacket) {
29113 throw new Error('Invalid key: missing private-key packet');
29114 }
29115 }
29116
29117 /**
29118 * Returns true if this is a private key
29119 * @returns {Boolean}
29120 */
29121 isPrivate() {
29122 return true;
29123 }
29124
29125 /**
29126 * Returns key as public key (shallow copy)
29127 * @returns {PublicKey} New public Key
29128 */
29129 toPublic() {
29130 const packetlist = new PacketList();
29131 const keyPackets = this.toPacketList();
29132 for (const keyPacket of keyPackets) {
29133 switch (keyPacket.constructor.tag) {
29134 case enums.packet.secretKey: {
29135 const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);
29136 packetlist.push(pubKeyPacket);
29137 break;
29138 }
29139 case enums.packet.secretSubkey: {
29140 const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);
29141 packetlist.push(pubSubkeyPacket);
29142 break;
29143 }
29144 default:
29145 packetlist.push(keyPacket);
29146 }
29147 }
29148 return new PublicKey(packetlist);
29149 }
29150
29151 /**
29152 * Returns ASCII armored text of key
29153 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29154 * @returns {ReadableStream<String>} ASCII armor.
29155 */
29156 armor(config$1 = config) {
29157 return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, config$1);
29158 }
29159
29160 /**
29161 * Returns all keys that are available for decryption, matching the keyID when given
29162 * This is useful to retrieve keys for session key decryption
29163 * @param {module:type/keyid~KeyID} keyID, optional
29164 * @param {Date} date, optional
29165 * @param {String} userID, optional
29166 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29167 * @returns {Promise<Array<Key|Subkey>>} Array of decryption keys.
29168 * @async
29169 */
29170 async getDecryptionKeys(keyID, date = new Date(), userID = {}, config$1 = config) {
29171 const primaryKey = this.keyPacket;
29172 const keys = [];
29173 for (let i = 0; i < this.subkeys.length; i++) {
29174 if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {
29175 try {
29176 const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };
29177 const bindingSignature = await getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config$1);
29178 if (isValidDecryptionKeyPacket(bindingSignature, config$1)) {
29179 keys.push(this.subkeys[i]);
29180 }
29181 } catch (e) {}
29182 }
29183 }
29184
29185 // evaluate primary key
29186 const primaryUser = await this.getPrimaryUser(date, userID, config$1);
29187 if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) &&
29188 isValidDecryptionKeyPacket(primaryUser.selfCertification, config$1)) {
29189 keys.push(this);
29190 }
29191
29192 return keys;
29193 }
29194
29195 /**
29196 * Returns true if the primary key or any subkey is decrypted.
29197 * A dummy key is considered encrypted.
29198 */
29199 isDecrypted() {
29200 return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());
29201 }
29202
29203 /**
29204 * Check whether the private and public primary key parameters correspond
29205 * Together with verification of binding signatures, this guarantees key integrity
29206 * In case of gnu-dummy primary key, it is enough to validate any signing subkeys
29207 * otherwise all encryption subkeys are validated
29208 * If only gnu-dummy keys are found, we cannot properly validate so we throw an error
29209 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29210 * @throws {Error} if validation was not successful and the key cannot be trusted
29211 * @async
29212 */
29213 async validate(config$1 = config) {
29214 if (!this.isPrivate()) {
29215 throw new Error('Cannot validate a public key');
29216 }
29217
29218 let signingKeyPacket;
29219 if (!this.keyPacket.isDummy()) {
29220 signingKeyPacket = this.keyPacket;
29221 } else {
29222 /**
29223 * It is enough to validate any signing keys
29224 * since its binding signatures are also checked
29225 */
29226 const signingKey = await this.getSigningKey(null, null, undefined, { ...config$1, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });
29227 // This could again be a dummy key
29228 if (signingKey && !signingKey.keyPacket.isDummy()) {
29229 signingKeyPacket = signingKey.keyPacket;
29230 }
29231 }
29232
29233 if (signingKeyPacket) {
29234 return signingKeyPacket.validate();
29235 } else {
29236 const keys = this.getKeys();
29237 const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);
29238 if (allDummies) {
29239 throw new Error('Cannot validate an all-gnu-dummy key');
29240 }
29241
29242 return Promise.all(keys.map(async key => key.keyPacket.validate()));
29243 }
29244 }
29245
29246 /**
29247 * Clear private key parameters
29248 */
29249 clearPrivateParams() {
29250 this.getKeys().forEach(({ keyPacket }) => {
29251 if (keyPacket.isDecrypted()) {
29252 keyPacket.clearPrivateParams();
29253 }
29254 });
29255 }
29256
29257 /**
29258 * Revokes the key
29259 * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation
29260 * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
29261 * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation
29262 * @param {Date} date - optional, override the creationtime of the revocation signature
29263 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29264 * @returns {Promise<PrivateKey>} New key with revocation signature.
29265 * @async
29266 */
29267 async revoke(
29268 {
29269 flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,
29270 string: reasonForRevocationString = ''
29271 } = {},
29272 date = new Date(),
29273 config$1 = config
29274 ) {
29275 if (!this.isPrivate()) {
29276 throw new Error('Need private key for revoking');
29277 }
29278 const dataToSign = { key: this.keyPacket };
29279 const key = this.clone();
29280 key.revocationSignatures.push(await createSignaturePacket(dataToSign, null, this.keyPacket, {
29281 signatureType: enums.signature.keyRevocation,
29282 reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),
29283 reasonForRevocationString
29284 }, date, undefined, undefined, undefined, config$1));
29285 return key;
29286 }
29287
29288
29289 /**
29290 * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.
29291 * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.
29292 * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA
29293 * @param {String} options.curve (optional) Elliptic curve for ECC keys
29294 * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys
29295 * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires
29296 * @param {Date} options.date (optional) Override the creation date of the key and the key signatures
29297 * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false
29298 * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}
29299 * @returns {Promise<PrivateKey>}
29300 * @async
29301 */
29302 async addSubkey(options = {}) {
29303 const config$1 = { ...config, ...options.config };
29304 if (options.passphrase) {
29305 throw new Error('Subkey could not be encrypted here, please encrypt whole key');
29306 }
29307 if (options.rsaBits < config$1.minRSABits) {
29308 throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${options.rsaBits}`);
29309 }
29310 const secretKeyPacket = this.keyPacket;
29311 if (secretKeyPacket.isDummy()) {
29312 throw new Error('Cannot add subkey to gnu-dummy primary key');
29313 }
29314 if (!secretKeyPacket.isDecrypted()) {
29315 throw new Error('Key is not decrypted');
29316 }
29317 const defaultOptions = secretKeyPacket.getAlgorithmInfo();
29318 defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA
29319 defaultOptions.rsaBits = defaultOptions.bits || 4096;
29320 defaultOptions.curve = defaultOptions.curve || 'curve25519';
29321 options = sanitizeKeyOptions(options, defaultOptions);
29322 const keyPacket = await generateSecretSubkey(options);
29323 checkKeyRequirements(keyPacket, config$1);
29324 const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config$1);
29325 const packetList = this.toPacketList();
29326 packetList.push(keyPacket, bindingSignature);
29327 return new PrivateKey(packetList);
29328 }
29329}
29330
29331// OpenPGP.js - An OpenPGP implementation in javascript
29332
29333// A Key can contain the following packets
29334const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([
29335 PublicKeyPacket,
29336 PublicSubkeyPacket,
29337 SecretKeyPacket,
29338 SecretSubkeyPacket,
29339 UserIDPacket,
29340 UserAttributePacket,
29341 SignaturePacket
29342]);
29343
29344/**
29345 * Creates a PublicKey or PrivateKey depending on the packetlist in input
29346 * @param {PacketList} - packets to parse
29347 * @return {Key} parsed key
29348 * @throws if no key packet was found
29349 */
29350function createKey(packetlist) {
29351 for (const packet of packetlist) {
29352 switch (packet.constructor.tag) {
29353 case enums.packet.secretKey:
29354 return new PrivateKey(packetlist);
29355 case enums.packet.publicKey:
29356 return new PublicKey(packetlist);
29357 }
29358 }
29359 throw new Error('No key packet found');
29360}
29361
29362
29363/**
29364 * Generates a new OpenPGP key. Supports RSA and ECC keys.
29365 * By default, primary and subkeys will be of same type.
29366 * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA
29367 * @param {String} options.curve Elliptic curve for ECC keys
29368 * @param {Integer} options.rsaBits Number of bits for RSA keys
29369 * @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' }
29370 * @param {String} options.passphrase Passphrase used to encrypt the resulting private key
29371 * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires
29372 * @param {Date} options.date Creation date of the key and the key signatures
29373 * @param {Object} config - Full configuration
29374 * @param {Array<Object>} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
29375 * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt
29376 * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}
29377 * @async
29378 * @static
29379 * @private
29380 */
29381async function generate$4(options, config) {
29382 options.sign = true; // primary key is always a signing key
29383 options = sanitizeKeyOptions(options);
29384 options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options));
29385 let promises = [generateSecretKey(options, config)];
29386 promises = promises.concat(options.subkeys.map(options => generateSecretSubkey(options, config)));
29387 const packets = await Promise.all(promises);
29388
29389 const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);
29390 const revocationCertificate = await key.getRevocationCertificate(options.date, config);
29391 key.revocationSignatures = [];
29392 return { key, revocationCertificate };
29393}
29394
29395/**
29396 * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.
29397 * @param {PrivateKey} options.privateKey The private key to reformat
29398 * @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' }
29399 * @param {String} options.passphrase Passphrase used to encrypt the resulting private key
29400 * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires
29401 * @param {Date} options.date Override the creation date of the key signatures
29402 * @param {Array<Object>} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
29403 * @param {Object} config - Full configuration
29404 *
29405 * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}
29406 * @async
29407 * @static
29408 * @private
29409 */
29410async function reformat(options, config) {
29411 options = sanitize(options);
29412 const { privateKey } = options;
29413
29414 if (!privateKey.isPrivate()) {
29415 throw new Error('Cannot reformat a public key');
29416 }
29417
29418 if (privateKey.keyPacket.isDummy()) {
29419 throw new Error('Cannot reformat a gnu-dummy primary key');
29420 }
29421
29422 const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());
29423 if (!isDecrypted) {
29424 throw new Error('Key is not decrypted');
29425 }
29426
29427 const secretKeyPacket = privateKey.keyPacket;
29428
29429 if (!options.subkeys) {
29430 options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => {
29431 const secretSubkeyPacket = subkey.keyPacket;
29432 const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };
29433 const bindingSignature = await (
29434 getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)
29435 ).catch(() => ({}));
29436 return {
29437 sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)
29438 };
29439 }));
29440 }
29441
29442 const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);
29443 if (options.subkeys.length !== secretSubkeyPackets.length) {
29444 throw new Error('Number of subkey options does not match number of subkeys');
29445 }
29446
29447 options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));
29448
29449 const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);
29450 const revocationCertificate = await key.getRevocationCertificate(options.date, config);
29451 key.revocationSignatures = [];
29452 return { key, revocationCertificate };
29453
29454 function sanitize(options, subkeyDefaults = {}) {
29455 options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;
29456 options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
29457 options.date = options.date || subkeyDefaults.date;
29458
29459 return options;
29460 }
29461}
29462
29463/**
29464 * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection
29465 * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.
29466 * @param {SecretKeyPacket} secretKeyPacket
29467 * @param {SecretSubkeyPacket} secretSubkeyPackets
29468 * @param {Object} options
29469 * @param {Object} config - Full configuration
29470 * @returns {PrivateKey}
29471 */
29472async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {
29473 // set passphrase protection
29474 if (options.passphrase) {
29475 await secretKeyPacket.encrypt(options.passphrase, config);
29476 }
29477
29478 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
29479 const subkeyPassphrase = options.subkeys[index].passphrase;
29480 if (subkeyPassphrase) {
29481 await secretSubkeyPacket.encrypt(subkeyPassphrase, config);
29482 }
29483 }));
29484
29485 const packetlist = new PacketList();
29486 packetlist.push(secretKeyPacket);
29487
29488 await Promise.all(options.userIDs.map(async function(userID, index) {
29489 function createPreferredAlgos(algos, preferredAlgo) {
29490 return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];
29491 }
29492
29493 const userIDPacket = UserIDPacket.fromObject(userID);
29494 const dataToSign = {};
29495 dataToSign.userID = userIDPacket;
29496 dataToSign.key = secretKeyPacket;
29497
29498 const signatureProperties = {};
29499 signatureProperties.signatureType = enums.signature.certGeneric;
29500 signatureProperties.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];
29501 signatureProperties.preferredSymmetricAlgorithms = createPreferredAlgos([
29502 // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support)
29503 enums.symmetric.aes256,
29504 enums.symmetric.aes128,
29505 enums.symmetric.aes192
29506 ], config.preferredSymmetricAlgorithm);
29507 if (config.aeadProtect) {
29508 signatureProperties.preferredAEADAlgorithms = createPreferredAlgos([
29509 enums.aead.eax,
29510 enums.aead.ocb
29511 ], config.preferredAEADAlgorithm);
29512 }
29513 signatureProperties.preferredHashAlgorithms = createPreferredAlgos([
29514 // prefer fast asm.js implementations (SHA-256)
29515 enums.hash.sha256,
29516 enums.hash.sha512
29517 ], config.preferredHashAlgorithm);
29518 signatureProperties.preferredCompressionAlgorithms = createPreferredAlgos([
29519 enums.compression.zlib,
29520 enums.compression.zip,
29521 enums.compression.uncompressed
29522 ], config.preferredCompressionAlgorithm);
29523 if (index === 0) {
29524 signatureProperties.isPrimaryUserID = true;
29525 }
29526 // integrity protection always enabled
29527 signatureProperties.features = [0];
29528 signatureProperties.features[0] |= enums.features.modificationDetection;
29529 if (config.aeadProtect) {
29530 signatureProperties.features[0] |= enums.features.aead;
29531 }
29532 if (config.v5Keys) {
29533 signatureProperties.features[0] |= enums.features.v5Keys;
29534 }
29535 if (options.keyExpirationTime > 0) {
29536 signatureProperties.keyExpirationTime = options.keyExpirationTime;
29537 signatureProperties.keyNeverExpires = false;
29538 }
29539
29540 const signaturePacket = await createSignaturePacket(dataToSign, null, secretKeyPacket, signatureProperties, options.date, undefined, undefined, undefined, config);
29541
29542 return { userIDPacket, signaturePacket };
29543 })).then(list => {
29544 list.forEach(({ userIDPacket, signaturePacket }) => {
29545 packetlist.push(userIDPacket);
29546 packetlist.push(signaturePacket);
29547 });
29548 });
29549
29550 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
29551 const subkeyOptions = options.subkeys[index];
29552 const subkeySignaturePacket = await createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);
29553 return { secretSubkeyPacket, subkeySignaturePacket };
29554 })).then(packets => {
29555 packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {
29556 packetlist.push(secretSubkeyPacket);
29557 packetlist.push(subkeySignaturePacket);
29558 });
29559 });
29560
29561 // Add revocation signature packet for creating a revocation certificate.
29562 // This packet should be removed before returning the key.
29563 const dataToSign = { key: secretKeyPacket };
29564 packetlist.push(await createSignaturePacket(dataToSign, null, secretKeyPacket, {
29565 signatureType: enums.signature.keyRevocation,
29566 reasonForRevocationFlag: enums.reasonForRevocation.noReason,
29567 reasonForRevocationString: ''
29568 }, options.date, undefined, undefined, undefined, config));
29569
29570 if (options.passphrase) {
29571 secretKeyPacket.clearPrivateParams();
29572 }
29573
29574 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
29575 const subkeyPassphrase = options.subkeys[index].passphrase;
29576 if (subkeyPassphrase) {
29577 secretSubkeyPacket.clearPrivateParams();
29578 }
29579 }));
29580
29581 return new PrivateKey(packetlist);
29582}
29583
29584/**
29585 * Reads an (optionally armored) OpenPGP key and returns a key object
29586 * @param {Object} options
29587 * @param {String} [options.armoredKey] - Armored key to be parsed
29588 * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed
29589 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29590 * @returns {Promise<Key>} Key object.
29591 * @async
29592 * @static
29593 */
29594async function readKey({ armoredKey, binaryKey, config: config$1, ...rest }) {
29595 config$1 = { ...config, ...config$1 };
29596 if (!armoredKey && !binaryKey) {
29597 throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');
29598 }
29599 if (armoredKey && !util.isString(armoredKey)) {
29600 throw new Error('readKey: options.armoredKey must be a string');
29601 }
29602 if (binaryKey && !util.isUint8Array(binaryKey)) {
29603 throw new Error('readKey: options.binaryKey must be a Uint8Array');
29604 }
29605 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
29606
29607 let input;
29608 if (armoredKey) {
29609 const { type, data } = await unarmor(armoredKey, config$1);
29610 if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {
29611 throw new Error('Armored text not of type key');
29612 }
29613 input = data;
29614 } else {
29615 input = binaryKey;
29616 }
29617 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1);
29618 return createKey(packetlist);
29619}
29620
29621/**
29622 * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object
29623 * @param {Object} options
29624 * @param {String} [options.armoredKey] - Armored key to be parsed
29625 * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed
29626 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29627 * @returns {Promise<PrivateKey>} Key object.
29628 * @async
29629 * @static
29630 */
29631async function readPrivateKey({ armoredKey, binaryKey, config: config$1, ...rest }) {
29632 config$1 = { ...config, ...config$1 };
29633 if (!armoredKey && !binaryKey) {
29634 throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');
29635 }
29636 if (armoredKey && !util.isString(armoredKey)) {
29637 throw new Error('readPrivateKey: options.armoredKey must be a string');
29638 }
29639 if (binaryKey && !util.isUint8Array(binaryKey)) {
29640 throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');
29641 }
29642 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
29643
29644 let input;
29645 if (armoredKey) {
29646 const { type, data } = await unarmor(armoredKey, config$1);
29647 if (!(type === enums.armor.privateKey)) {
29648 throw new Error('Armored text not of type private key');
29649 }
29650 input = data;
29651 } else {
29652 input = binaryKey;
29653 }
29654 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1);
29655 return new PrivateKey(packetlist);
29656}
29657
29658/**
29659 * Reads an (optionally armored) OpenPGP key block and returns a list of key objects
29660 * @param {Object} options
29661 * @param {String} [options.armoredKeys] - Armored keys to be parsed
29662 * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed
29663 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29664 * @returns {Promise<Array<Key>>} Key objects.
29665 * @async
29666 * @static
29667 */
29668async function readKeys({ armoredKeys, binaryKeys, config: config$1, ...rest }) {
29669 config$1 = { ...config, ...config$1 };
29670 let input = armoredKeys || binaryKeys;
29671 if (!input) {
29672 throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');
29673 }
29674 if (armoredKeys && !util.isString(armoredKeys)) {
29675 throw new Error('readKeys: options.armoredKeys must be a string');
29676 }
29677 if (binaryKeys && !util.isUint8Array(binaryKeys)) {
29678 throw new Error('readKeys: options.binaryKeys must be a Uint8Array');
29679 }
29680 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
29681
29682 if (armoredKeys) {
29683 const { type, data } = await unarmor(armoredKeys, config$1);
29684 if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {
29685 throw new Error('Armored text not of type key');
29686 }
29687 input = data;
29688 }
29689 const keys = [];
29690 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1);
29691 const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);
29692 if (keyIndex.length === 0) {
29693 throw new Error('No key packet found');
29694 }
29695 for (let i = 0; i < keyIndex.length; i++) {
29696 const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);
29697 const newKey = createKey(oneKeyList);
29698 keys.push(newKey);
29699 }
29700 return keys;
29701}
29702
29703/**
29704 * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects
29705 * @param {Object} options
29706 * @param {String} [options.armoredKeys] - Armored keys to be parsed
29707 * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed
29708 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29709 * @returns {Promise<Array<PrivateKey>>} Key objects.
29710 * @async
29711 * @static
29712 */
29713async function readPrivateKeys({ armoredKeys, binaryKeys, config: config$1 }) {
29714 config$1 = { ...config, ...config$1 };
29715 let input = armoredKeys || binaryKeys;
29716 if (!input) {
29717 throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');
29718 }
29719 if (armoredKeys && !util.isString(armoredKeys)) {
29720 throw new Error('readPrivateKeys: options.armoredKeys must be a string');
29721 }
29722 if (binaryKeys && !util.isUint8Array(binaryKeys)) {
29723 throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');
29724 }
29725 if (armoredKeys) {
29726 const { type, data } = await unarmor(armoredKeys, config$1);
29727 if (type !== enums.armor.privateKey) {
29728 throw new Error('Armored text not of type private key');
29729 }
29730 input = data;
29731 }
29732 const keys = [];
29733 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config$1);
29734 const keyIndex = packetlist.indexOfTag(enums.packet.secretKey);
29735 if (keyIndex.length === 0) {
29736 throw new Error('No secret key packet found');
29737 }
29738 for (let i = 0; i < keyIndex.length; i++) {
29739 const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);
29740 const newKey = new PrivateKey(oneKeyList);
29741 keys.push(newKey);
29742 }
29743 return keys;
29744}
29745
29746// GPG4Browsers - An OpenPGP implementation in javascript
29747
29748// A Message can contain the following packets
29749const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([
29750 LiteralDataPacket,
29751 CompressedDataPacket,
29752 AEADEncryptedDataPacket,
29753 SymEncryptedIntegrityProtectedDataPacket,
29754 SymmetricallyEncryptedDataPacket,
29755 PublicKeyEncryptedSessionKeyPacket,
29756 SymEncryptedSessionKeyPacket,
29757 OnePassSignaturePacket,
29758 SignaturePacket
29759]);
29760// A SKESK packet can contain the following packets
29761const allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);
29762// A detached signature can contain the following packets
29763const allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
29764
29765/**
29766 * Class that represents an OpenPGP message.
29767 * Can be an encrypted message, signed message, compressed message or literal message
29768 * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}
29769 */
29770class Message {
29771 /**
29772 * @param {PacketList} packetlist - The packets that form this message
29773 */
29774 constructor(packetlist) {
29775 this.packets = packetlist || new PacketList();
29776 }
29777
29778 /**
29779 * Returns the key IDs of the keys to which the session key is encrypted
29780 * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
29781 */
29782 getEncryptionKeyIDs() {
29783 const keyIDs = [];
29784 const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
29785 pkESKeyPacketlist.forEach(function(packet) {
29786 keyIDs.push(packet.publicKeyID);
29787 });
29788 return keyIDs;
29789 }
29790
29791 /**
29792 * Returns the key IDs of the keys that signed the message
29793 * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
29794 */
29795 getSigningKeyIDs() {
29796 const msg = this.unwrapCompressed();
29797 // search for one pass signatures
29798 const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);
29799 if (onePassSigList.length > 0) {
29800 return onePassSigList.map(packet => packet.issuerKeyID);
29801 }
29802 // if nothing found look for signature packets
29803 const signatureList = msg.packets.filterByTag(enums.packet.signature);
29804 return signatureList.map(packet => packet.issuerKeyID);
29805 }
29806
29807 /**
29808 * Decrypt the message. Either a private key, a session key, or a password must be specified.
29809 * @param {Array<PrivateKey>} [decryptionKeys] - Private keys with decrypted secret data
29810 * @param {Array<String>} [passwords] - Passwords used to decrypt
29811 * @param {Array<Object>} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
29812 * @param {Date} [date] - Use the given date for key verification instead of the current time
29813 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29814 * @returns {Promise<Message>} New message with decrypted content.
29815 * @async
29816 */
29817 async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config$1 = config) {
29818 const sessionKeyObjects = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, date, config$1);
29819
29820 const symEncryptedPacketlist = this.packets.filterByTag(
29821 enums.packet.symmetricallyEncryptedData,
29822 enums.packet.symEncryptedIntegrityProtectedData,
29823 enums.packet.aeadEncryptedData
29824 );
29825
29826 if (symEncryptedPacketlist.length === 0) {
29827 throw new Error('No encrypted data found');
29828 }
29829
29830 const symEncryptedPacket = symEncryptedPacketlist[0];
29831 let exception = null;
29832 const decryptedPromise = Promise.all(sessionKeyObjects.map(async ({ algorithm: algorithmName, data }) => {
29833 if (!util.isUint8Array(data) || !util.isString(algorithmName)) {
29834 throw new Error('Invalid session key for decryption.');
29835 }
29836
29837 try {
29838 const algo = enums.write(enums.symmetric, algorithmName);
29839 await symEncryptedPacket.decrypt(algo, data, config$1);
29840 } catch (e) {
29841 util.printDebugError(e);
29842 exception = e;
29843 }
29844 }));
29845 // We don't await stream.cancel here because it only returns when the other copy is canceled too.
29846 cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.
29847 symEncryptedPacket.encrypted = null;
29848 await decryptedPromise;
29849
29850 if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {
29851 throw exception || new Error('Decryption failed.');
29852 }
29853
29854 const resultMsg = new Message(symEncryptedPacket.packets);
29855 symEncryptedPacket.packets = new PacketList(); // remove packets after decryption
29856
29857 return resultMsg;
29858 }
29859
29860 /**
29861 * Decrypt encrypted session keys either with private keys or passwords.
29862 * @param {Array<PrivateKey>} [decryptionKeys] - Private keys with decrypted secret data
29863 * @param {Array<String>} [passwords] - Passwords used to decrypt
29864 * @param {Date} [date] - Use the given date for key verification, instead of current time
29865 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29866 * @returns {Promise<Array<{
29867 * data: Uint8Array,
29868 * algorithm: String
29869 * }>>} array of object with potential sessionKey, algorithm pairs
29870 * @async
29871 */
29872 async decryptSessionKeys(decryptionKeys, passwords, date = new Date(), config$1 = config) {
29873 let decryptedSessionKeyPackets = [];
29874
29875 let exception;
29876 if (passwords) {
29877 const skeskPackets = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);
29878 if (skeskPackets.length === 0) {
29879 throw new Error('No symmetrically encrypted session key packet found.');
29880 }
29881 await Promise.all(passwords.map(async function(password, i) {
29882 let packets;
29883 if (i) {
29884 packets = await PacketList.fromBinary(skeskPackets.write(), allowedSymSessionKeyPackets, config$1);
29885 } else {
29886 packets = skeskPackets;
29887 }
29888 await Promise.all(packets.map(async function(skeskPacket) {
29889 try {
29890 await skeskPacket.decrypt(password);
29891 decryptedSessionKeyPackets.push(skeskPacket);
29892 } catch (err) {
29893 util.printDebugError(err);
29894 }
29895 }));
29896 }));
29897 } else if (decryptionKeys) {
29898 const pkeskPackets = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
29899 if (pkeskPackets.length === 0) {
29900 throw new Error('No public key encrypted session key packet found.');
29901 }
29902 await Promise.all(pkeskPackets.map(async function(pkeskPacket) {
29903 await Promise.all(decryptionKeys.map(async function(decryptionKey) {
29904 let algos = [
29905 enums.symmetric.aes256, // Old OpenPGP.js default fallback
29906 enums.symmetric.aes128, // RFC4880bis fallback
29907 enums.symmetric.tripledes, // RFC4880 fallback
29908 enums.symmetric.cast5 // Golang OpenPGP fallback
29909 ];
29910 try {
29911 const primaryUser = await decryptionKey.getPrimaryUser(date, undefined, config$1); // TODO: Pass userID from somewhere.
29912 if (primaryUser.selfCertification.preferredSymmetricAlgorithms) {
29913 algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms);
29914 }
29915 } catch (e) {}
29916
29917 // do not check key expiration to allow decryption of old messages
29918 const decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(pkeskPacket.publicKeyID, null, undefined, config$1)).map(key => key.keyPacket);
29919 await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) {
29920 if (!decryptionKeyPacket || decryptionKeyPacket.isDummy()) {
29921 return;
29922 }
29923 if (!decryptionKeyPacket.isDecrypted()) {
29924 throw new Error('Decryption key is not decrypted.');
29925 }
29926
29927 // To hinder CCA attacks against PKCS1, we carry out a constant-time decryption flow if the `constantTimePKCS1Decryption` config option is set.
29928 const doConstantTimeDecryption = config$1.constantTimePKCS1Decryption && (
29929 pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncrypt ||
29930 pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaEncryptSign ||
29931 pkeskPacket.publicKeyAlgorithm === enums.publicKey.rsaSign ||
29932 pkeskPacket.publicKeyAlgorithm === enums.publicKey.elgamal
29933 );
29934
29935 if (doConstantTimeDecryption) {
29936 // The goal is to not reveal whether PKESK decryption (specifically the PKCS1 decoding step) failed, hence, we always proceed to decrypt the message,
29937 // either with the successfully decrypted session key, or with a randomly generated one.
29938 // 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
29939 // the decrypted payload, we always assume the message to be encrypted with one of the symmetric algorithms specified in `config.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms`:
29940 // - 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
29941 // randomly generated keys of the remaining key types.
29942 // - 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
29943 // generated session keys.
29944 // NB: as a result, if the data is encrypted with a non-suported cipher, decryption will always fail.
29945
29946 const serialisedPKESK = pkeskPacket.write(); // make copies to be able to decrypt the PKESK packet multiple times
29947 await Promise.all(Array.from(config$1.constantTimePKCS1DecryptionSupportedSymmetricAlgorithms).map(async sessionKeyAlgorithm => {
29948 const pkeskPacketCopy = new PublicKeyEncryptedSessionKeyPacket();
29949 pkeskPacketCopy.read(serialisedPKESK);
29950 const randomSessionKey = {
29951 sessionKeyAlgorithm,
29952 sessionKey: mod.generateSessionKey(sessionKeyAlgorithm)
29953 };
29954 try {
29955 await pkeskPacketCopy.decrypt(decryptionKeyPacket, randomSessionKey);
29956 decryptedSessionKeyPackets.push(pkeskPacketCopy);
29957 } catch (err) {
29958 // `decrypt` can still throw some non-security-sensitive errors
29959 util.printDebugError(err);
29960 exception = err;
29961 }
29962 }));
29963
29964 } else {
29965 try {
29966 await pkeskPacket.decrypt(decryptionKeyPacket);
29967 if (!algos.includes(enums.write(enums.symmetric, pkeskPacket.sessionKeyAlgorithm))) {
29968 throw new Error('A non-preferred symmetric algorithm was used.');
29969 }
29970 decryptedSessionKeyPackets.push(pkeskPacket);
29971 } catch (err) {
29972 util.printDebugError(err);
29973 exception = err;
29974 }
29975 }
29976 }));
29977 }));
29978 cancel(pkeskPacket.encrypted); // Don't keep copy of encrypted data in memory.
29979 pkeskPacket.encrypted = null;
29980 }));
29981 } else {
29982 throw new Error('No key or password specified.');
29983 }
29984
29985 if (decryptedSessionKeyPackets.length > 0) {
29986 // Return only unique session keys
29987 if (decryptedSessionKeyPackets.length > 1) {
29988 const seen = new Set();
29989 decryptedSessionKeyPackets = decryptedSessionKeyPackets.filter(item => {
29990 const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);
29991 if (seen.has(k)) {
29992 return false;
29993 }
29994 seen.add(k);
29995 return true;
29996 });
29997 }
29998
29999 return decryptedSessionKeyPackets.map(packet => ({
30000 data: packet.sessionKey,
30001 algorithm: enums.read(enums.symmetric, packet.sessionKeyAlgorithm)
30002 }));
30003 }
30004 throw exception || new Error('Session key decryption failed.');
30005 }
30006
30007 /**
30008 * Get literal data that is the body of the message
30009 * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.
30010 */
30011 getLiteralData() {
30012 const msg = this.unwrapCompressed();
30013 const literal = msg.packets.findPacket(enums.packet.literalData);
30014 return (literal && literal.getBytes()) || null;
30015 }
30016
30017 /**
30018 * Get filename from literal data packet
30019 * @returns {(String|null)} Filename of literal data packet as string.
30020 */
30021 getFilename() {
30022 const msg = this.unwrapCompressed();
30023 const literal = msg.packets.findPacket(enums.packet.literalData);
30024 return (literal && literal.getFilename()) || null;
30025 }
30026
30027 /**
30028 * Get literal data as text
30029 * @returns {(String|null)} Literal body of the message interpreted as text.
30030 */
30031 getText() {
30032 const msg = this.unwrapCompressed();
30033 const literal = msg.packets.findPacket(enums.packet.literalData);
30034 if (literal) {
30035 return literal.getText();
30036 }
30037 return null;
30038 }
30039
30040 /**
30041 * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.
30042 * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) to select algorithm preferences for
30043 * @param {Date} [date] - Date to select algorithm preferences at
30044 * @param {Array<Object>} [userIDs] - User IDs to select algorithm preferences for
30045 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30046 * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.
30047 * @async
30048 */
30049 static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config$1 = config) {
30050 const algo = await getPreferredAlgo('symmetric', encryptionKeys, date, userIDs, config$1);
30051 const algorithmName = enums.read(enums.symmetric, algo);
30052 const aeadAlgorithmName = config$1.aeadProtect && await isAEADSupported(encryptionKeys, date, userIDs, config$1) ?
30053 enums.read(enums.aead, await getPreferredAlgo('aead', encryptionKeys, date, userIDs, config$1)) :
30054 undefined;
30055
30056 await Promise.all(encryptionKeys.map(key => key.getEncryptionKey()
30057 .catch(() => null) // ignore key strength requirements
30058 .then(maybeKey => {
30059 if (maybeKey && (maybeKey.keyPacket.algorithm === enums.publicKey.x25519) && !util.isAES(algo)) {
30060 throw new Error('Could not generate a session key compatible with the given `encryptionKeys`: X22519 keys can only be used to encrypt AES session keys; change `config.preferredSymmetricAlgorithm` accordingly.');
30061 }
30062 })
30063 ));
30064
30065 const sessionKeyData = mod.generateSessionKey(algo);
30066 return { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName };
30067 }
30068
30069 /**
30070 * Encrypt the message either with public keys, passwords, or both at once.
30071 * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) for message encryption
30072 * @param {Array<String>} [passwords] - Password(s) for message encryption
30073 * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
30074 * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs
30075 * @param {Array<module:type/keyid~KeyID>} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]
30076 * @param {Date} [date] - Override the creation date of the literal package
30077 * @param {Array<Object>} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
30078 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30079 * @returns {Promise<Message>} New message with encrypted content.
30080 * @async
30081 */
30082 async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) {
30083 if (sessionKey) {
30084 if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {
30085 throw new Error('Invalid session key for encryption.');
30086 }
30087 } else if (encryptionKeys && encryptionKeys.length) {
30088 sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config$1);
30089 } else if (passwords && passwords.length) {
30090 sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config$1);
30091 } else {
30092 throw new Error('No keys, passwords, or session key provided.');
30093 }
30094
30095 const { data: sessionKeyData, algorithm: algorithmName, aeadAlgorithm: aeadAlgorithmName } = sessionKey;
30096
30097 const msg = await Message.encryptSessionKey(sessionKeyData, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config$1);
30098
30099 let symEncryptedPacket;
30100 if (aeadAlgorithmName) {
30101 symEncryptedPacket = new AEADEncryptedDataPacket();
30102 symEncryptedPacket.aeadAlgorithm = enums.write(enums.aead, aeadAlgorithmName);
30103 } else {
30104 symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket();
30105 }
30106 symEncryptedPacket.packets = this.packets;
30107
30108 const algorithm = enums.write(enums.symmetric, algorithmName);
30109 await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config$1);
30110
30111 msg.packets.push(symEncryptedPacket);
30112 symEncryptedPacket.packets = new PacketList(); // remove packets after encryption
30113 return msg;
30114 }
30115
30116 /**
30117 * Encrypt a session key either with public keys, passwords, or both at once.
30118 * @param {Uint8Array} sessionKey - session key for encryption
30119 * @param {String} algorithmName - session key algorithm
30120 * @param {String} [aeadAlgorithmName] - AEAD algorithm, e.g. 'eax' or 'ocb'
30121 * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) for message encryption
30122 * @param {Array<String>} [passwords] - For message encryption
30123 * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs
30124 * @param {Array<module:type/keyid~KeyID>} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]
30125 * @param {Date} [date] - Override the date
30126 * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
30127 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30128 * @returns {Promise<Message>} New message with encrypted content.
30129 * @async
30130 */
30131 static async encryptSessionKey(sessionKey, algorithmName, aeadAlgorithmName, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config$1 = config) {
30132 const packetlist = new PacketList();
30133 const algorithm = enums.write(enums.symmetric, algorithmName);
30134 const aeadAlgorithm = aeadAlgorithmName && enums.write(enums.aead, aeadAlgorithmName);
30135
30136 if (encryptionKeys) {
30137 const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) {
30138 const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config$1);
30139 const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket();
30140 pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID();
30141 pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm;
30142 pkESKeyPacket.sessionKey = sessionKey;
30143 pkESKeyPacket.sessionKeyAlgorithm = algorithm;
30144 await pkESKeyPacket.encrypt(encryptionKey.keyPacket);
30145 delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption
30146 return pkESKeyPacket;
30147 }));
30148 packetlist.push(...results);
30149 }
30150 if (passwords) {
30151 const testDecrypt = async function(keyPacket, password) {
30152 try {
30153 await keyPacket.decrypt(password);
30154 return 1;
30155 } catch (e) {
30156 return 0;
30157 }
30158 };
30159
30160 const sum = (accumulator, currentValue) => accumulator + currentValue;
30161
30162 const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {
30163 const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config$1);
30164 symEncryptedSessionKeyPacket.sessionKey = sessionKey;
30165 symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;
30166 if (aeadAlgorithm) {
30167 symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;
30168 }
30169 await symEncryptedSessionKeyPacket.encrypt(password, config$1);
30170
30171 if (config$1.passwordCollisionCheck) {
30172 const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));
30173 if (results.reduce(sum) !== 1) {
30174 return encryptPassword(sessionKey, algorithm, password);
30175 }
30176 }
30177
30178 delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption
30179 return symEncryptedSessionKeyPacket;
30180 };
30181
30182 const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd)));
30183 packetlist.push(...results);
30184 }
30185
30186 return new Message(packetlist);
30187 }
30188
30189 /**
30190 * Sign the message (the literal data packet of the message)
30191 * @param {Array<PrivateKey>} signingKeys - private keys with decrypted secret key data for signing
30192 * @param {Signature} [signature] - Any existing detached signature to add to the message
30193 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
30194 * @param {Date} [date] - Override the creation time of the signature
30195 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
30196 * @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 }]
30197 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30198 * @returns {Promise<Message>} New message with signed content.
30199 * @async
30200 */
30201 async sign(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) {
30202 const packetlist = new PacketList();
30203
30204 const literalDataPacket = this.packets.findPacket(enums.packet.literalData);
30205 if (!literalDataPacket) {
30206 throw new Error('No literal data packet to sign.');
30207 }
30208
30209 let i;
30210 let existingSigPacketlist;
30211 // If data packet was created from Uint8Array, use binary, otherwise use text
30212 const signatureType = literalDataPacket.text === null ?
30213 enums.signature.binary : enums.signature.text;
30214
30215 if (signature) {
30216 existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);
30217 for (i = existingSigPacketlist.length - 1; i >= 0; i--) {
30218 const signaturePacket = existingSigPacketlist[i];
30219 const onePassSig = new OnePassSignaturePacket();
30220 onePassSig.signatureType = signaturePacket.signatureType;
30221 onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;
30222 onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;
30223 onePassSig.issuerKeyID = signaturePacket.issuerKeyID;
30224 if (!signingKeys.length && i === 0) {
30225 onePassSig.flags = 1;
30226 }
30227 packetlist.push(onePassSig);
30228 }
30229 }
30230
30231 await Promise.all(Array.from(signingKeys).reverse().map(async function (primaryKey, i) {
30232 if (!primaryKey.isPrivate()) {
30233 throw new Error('Need private key for signing');
30234 }
30235 const signingKeyID = signingKeyIDs[signingKeys.length - 1 - i];
30236 const signingKey = await primaryKey.getSigningKey(signingKeyID, date, userIDs, config$1);
30237 const onePassSig = new OnePassSignaturePacket();
30238 onePassSig.signatureType = signatureType;
30239 onePassSig.hashAlgorithm = await getPreferredHashAlgo$2(primaryKey, signingKey.keyPacket, date, userIDs, config$1);
30240 onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm;
30241 onePassSig.issuerKeyID = signingKey.getKeyID();
30242 if (i === signingKeys.length - 1) {
30243 onePassSig.flags = 1;
30244 }
30245 return onePassSig;
30246 })).then(onePassSignatureList => {
30247 onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig));
30248 });
30249
30250 packetlist.push(literalDataPacket);
30251 packetlist.push(...(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, false, config$1)));
30252
30253 return new Message(packetlist);
30254 }
30255
30256 /**
30257 * Compresses the message (the literal and -if signed- signature data packets of the message)
30258 * @param {module:enums.compression} algo - compression algorithm
30259 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30260 * @returns {Message} New message with compressed content.
30261 */
30262 compress(algo, config$1 = config) {
30263 if (algo === enums.compression.uncompressed) {
30264 return this;
30265 }
30266
30267 const compressed = new CompressedDataPacket(config$1);
30268 compressed.algorithm = algo;
30269 compressed.packets = this.packets;
30270
30271 const packetList = new PacketList();
30272 packetList.push(compressed);
30273
30274 return new Message(packetList);
30275 }
30276
30277 /**
30278 * Create a detached signature for the message (the literal data packet of the message)
30279 * @param {Array<PrivateKey>} signingKeys - private keys with decrypted secret key data for signing
30280 * @param {Signature} [signature] - Any existing detached signature
30281 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
30282 * @param {Date} [date] - Override the creation time of the signature
30283 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
30284 * @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 }]
30285 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30286 * @returns {Promise<Signature>} New detached signature of message content.
30287 * @async
30288 */
30289 async signDetached(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) {
30290 const literalDataPacket = this.packets.findPacket(enums.packet.literalData);
30291 if (!literalDataPacket) {
30292 throw new Error('No literal data packet to sign.');
30293 }
30294 return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, notations, true, config$1));
30295 }
30296
30297 /**
30298 * Verify message signatures
30299 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
30300 * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
30301 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30302 * @returns {Promise<Array<{
30303 * keyID: module:type/keyid~KeyID,
30304 * signature: Promise<Signature>,
30305 * verified: Promise<true>
30306 * }>>} List of signer's keyID and validity of signatures.
30307 * @async
30308 */
30309 async verify(verificationKeys, date = new Date(), config$1 = config) {
30310 const msg = this.unwrapCompressed();
30311 const literalDataList = msg.packets.filterByTag(enums.packet.literalData);
30312 if (literalDataList.length !== 1) {
30313 throw new Error('Can only verify message with one literal data packet.');
30314 }
30315 if (isArrayStream(msg.packets.stream)) {
30316 msg.packets.push(...await readToEnd(msg.packets.stream, _ => _ || []));
30317 }
30318 const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();
30319 const signatureList = msg.packets.filterByTag(enums.packet.signature);
30320 if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !isArrayStream(msg.packets.stream)) {
30321 await Promise.all(onePassSigList.map(async onePassSig => {
30322 onePassSig.correspondingSig = new Promise((resolve, reject) => {
30323 onePassSig.correspondingSigResolve = resolve;
30324 onePassSig.correspondingSigReject = reject;
30325 });
30326 onePassSig.signatureData = fromAsync(async () => (await onePassSig.correspondingSig).signatureData);
30327 onePassSig.hashed = readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));
30328 onePassSig.hashed.catch(() => {});
30329 }));
30330 msg.packets.stream = transformPair(msg.packets.stream, async (readable, writable) => {
30331 const reader = getReader(readable);
30332 const writer = getWriter(writable);
30333 try {
30334 for (let i = 0; i < onePassSigList.length; i++) {
30335 const { value: signature } = await reader.read();
30336 onePassSigList[i].correspondingSigResolve(signature);
30337 }
30338 await reader.readToEnd();
30339 await writer.ready;
30340 await writer.close();
30341 } catch (e) {
30342 onePassSigList.forEach(onePassSig => {
30343 onePassSig.correspondingSigReject(e);
30344 });
30345 await writer.abort(e);
30346 }
30347 });
30348 return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config$1);
30349 }
30350 return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config$1);
30351 }
30352
30353 /**
30354 * Verify detached message signature
30355 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
30356 * @param {Signature} signature
30357 * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
30358 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30359 * @returns {Promise<Array<{
30360 * keyID: module:type/keyid~KeyID,
30361 * signature: Promise<Signature>,
30362 * verified: Promise<true>
30363 * }>>} List of signer's keyID and validity of signature.
30364 * @async
30365 */
30366 verifyDetached(signature, verificationKeys, date = new Date(), config$1 = config) {
30367 const msg = this.unwrapCompressed();
30368 const literalDataList = msg.packets.filterByTag(enums.packet.literalData);
30369 if (literalDataList.length !== 1) {
30370 throw new Error('Can only verify message with one literal data packet.');
30371 }
30372 const signatureList = signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets
30373 return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config$1);
30374 }
30375
30376 /**
30377 * Unwrap compressed message
30378 * @returns {Message} Message Content of compressed message.
30379 */
30380 unwrapCompressed() {
30381 const compressed = this.packets.filterByTag(enums.packet.compressedData);
30382 if (compressed.length) {
30383 return new Message(compressed[0].packets);
30384 }
30385 return this;
30386 }
30387
30388 /**
30389 * Append signature to unencrypted message object
30390 * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature
30391 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30392 */
30393 async appendSignature(detachedSignature, config$1 = config) {
30394 await this.packets.read(
30395 util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data,
30396 allowedDetachedSignaturePackets,
30397 config$1
30398 );
30399 }
30400
30401 /**
30402 * Returns binary encoded message
30403 * @returns {ReadableStream<Uint8Array>} Binary message.
30404 */
30405 write() {
30406 return this.packets.write();
30407 }
30408
30409 /**
30410 * Returns ASCII armored text of message
30411 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30412 * @returns {ReadableStream<String>} ASCII armor.
30413 */
30414 armor(config$1 = config) {
30415 return armor(enums.armor.message, this.write(), null, null, null, config$1);
30416 }
30417}
30418
30419/**
30420 * Create signature packets for the message
30421 * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign
30422 * @param {Array<PrivateKey>} [signingKeys] - private keys with decrypted secret key data for signing
30423 * @param {Signature} [signature] - Any existing detached signature to append
30424 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
30425 * @param {Date} [date] - Override the creationtime of the signature
30426 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
30427 * @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 }]
30428 * @param {Boolean} [detached] - Whether to create detached signature packets
30429 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30430 * @returns {Promise<PacketList>} List of signature packets.
30431 * @async
30432 * @private
30433 */
30434async function createSignaturePackets(literalDataPacket, signingKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], detached = false, config$1 = config) {
30435 const packetlist = new PacketList();
30436
30437 // If data packet was created from Uint8Array, use binary, otherwise use text
30438 const signatureType = literalDataPacket.text === null ?
30439 enums.signature.binary : enums.signature.text;
30440
30441 await Promise.all(signingKeys.map(async (primaryKey, i) => {
30442 const userID = userIDs[i];
30443 if (!primaryKey.isPrivate()) {
30444 throw new Error('Need private key for signing');
30445 }
30446 const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, userID, config$1);
30447 return createSignaturePacket(literalDataPacket, primaryKey, signingKey.keyPacket, { signatureType }, date, userID, notations, detached, config$1);
30448 })).then(signatureList => {
30449 packetlist.push(...signatureList);
30450 });
30451
30452 if (signature) {
30453 const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);
30454 packetlist.push(...existingSigPacketlist);
30455 }
30456 return packetlist;
30457}
30458
30459/**
30460 * Create object containing signer's keyID and validity of signature
30461 * @param {SignaturePacket} signature - Signature packet
30462 * @param {Array<LiteralDataPacket>} literalDataList - Array of literal data packets
30463 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
30464 * @param {Date} [date] - Check signature validity with respect to the given date
30465 * @param {Boolean} [detached] - Whether to verify detached signature packets
30466 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30467 * @returns {Promise<{
30468 * keyID: module:type/keyid~KeyID,
30469 * signature: Promise<Signature>,
30470 * verified: Promise<true>
30471 * }>} signer's keyID and validity of signature
30472 * @async
30473 * @private
30474 */
30475async function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) {
30476 let primaryKey;
30477 let unverifiedSigningKey;
30478
30479 for (const key of verificationKeys) {
30480 const issuerKeys = key.getKeys(signature.issuerKeyID);
30481 if (issuerKeys.length > 0) {
30482 primaryKey = key;
30483 unverifiedSigningKey = issuerKeys[0];
30484 break;
30485 }
30486 }
30487
30488 const isOnePassSignature = signature instanceof OnePassSignaturePacket;
30489 const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;
30490
30491 const verifiedSig = {
30492 keyID: signature.issuerKeyID,
30493 verified: (async () => {
30494 if (!unverifiedSigningKey) {
30495 throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);
30496 }
30497
30498 await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config$1);
30499 const signaturePacket = await signaturePacketPromise;
30500 if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {
30501 throw new Error('Key is newer than the signature');
30502 }
30503 // We pass the signature creation time to check whether the key was expired at the time of signing.
30504 // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before
30505 try {
30506 await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config$1);
30507 } catch (e) {
30508 // If a key was reformatted then the self-signatures of the signing key might be in the future compared to the message signature,
30509 // making the key invalid at the time of signing.
30510 // However, if the key is valid at the given `date`, we still allow using it provided the relevant `config` setting is enabled.
30511 // Note: we do not support the edge case of a key that was reformatted and it has expired.
30512 if (config$1.allowInsecureVerificationWithReformattedKeys && e.message.match(/Signature creation time is in the future/)) {
30513 await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), date, undefined, config$1);
30514 } else {
30515 throw e;
30516 }
30517 }
30518 return true;
30519 })(),
30520 signature: (async () => {
30521 const signaturePacket = await signaturePacketPromise;
30522 const packetlist = new PacketList();
30523 signaturePacket && packetlist.push(signaturePacket);
30524 return new Signature(packetlist);
30525 })()
30526 };
30527
30528 // Mark potential promise rejections as "handled". This is needed because in
30529 // some cases, we reject them before the user has a reasonable chance to
30530 // handle them (e.g. `await readToEnd(result.data); await result.verified` and
30531 // the data stream errors).
30532 verifiedSig.signature.catch(() => {});
30533 verifiedSig.verified.catch(() => {});
30534
30535 return verifiedSig;
30536}
30537
30538/**
30539 * Create list of objects containing signer's keyID and validity of signature
30540 * @param {Array<SignaturePacket>} signatureList - Array of signature packets
30541 * @param {Array<LiteralDataPacket>} literalDataList - Array of literal data packets
30542 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
30543 * @param {Date} date - Verify the signature against the given date,
30544 * i.e. check signature creation time < date < expiration time
30545 * @param {Boolean} [detached] - Whether to verify detached signature packets
30546 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30547 * @returns {Promise<Array<{
30548 * keyID: module:type/keyid~KeyID,
30549 * signature: Promise<Signature>,
30550 * verified: Promise<true>
30551 * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input)
30552 * @async
30553 * @private
30554 */
30555async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config$1 = config) {
30556 return Promise.all(signatureList.filter(function(signature) {
30557 return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));
30558 }).map(async function(signature) {
30559 return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config$1);
30560 }));
30561}
30562
30563/**
30564 * Reads an (optionally armored) OpenPGP message and returns a Message object
30565 * @param {Object} options
30566 * @param {String | ReadableStream<String>} [options.armoredMessage] - Armored message to be parsed
30567 * @param {Uint8Array | ReadableStream<Uint8Array>} [options.binaryMessage] - Binary to be parsed
30568 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30569 * @returns {Promise<Message>} New message object.
30570 * @async
30571 * @static
30572 */
30573async function readMessage({ armoredMessage, binaryMessage, config: config$1, ...rest }) {
30574 config$1 = { ...config, ...config$1 };
30575 let input = armoredMessage || binaryMessage;
30576 if (!input) {
30577 throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');
30578 }
30579 if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {
30580 throw new Error('readMessage: options.armoredMessage must be a string or stream');
30581 }
30582 if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {
30583 throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');
30584 }
30585 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30586
30587 const streamType = util.isStream(input);
30588 if (streamType) {
30589 await loadStreamsPonyfill();
30590 input = toStream(input);
30591 }
30592 if (armoredMessage) {
30593 const { type, data } = await unarmor(input, config$1);
30594 if (type !== enums.armor.message) {
30595 throw new Error('Armored text not of type message');
30596 }
30597 input = data;
30598 }
30599 const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config$1);
30600 const message = new Message(packetlist);
30601 message.fromStream = streamType;
30602 return message;
30603}
30604
30605/**
30606 * Creates new message object from text or binary data.
30607 * @param {Object} options
30608 * @param {String | ReadableStream<String>} [options.text] - The text message contents
30609 * @param {Uint8Array | ReadableStream<Uint8Array>} [options.binary] - The binary message contents
30610 * @param {String} [options.filename=""] - Name of the file (if any)
30611 * @param {Date} [options.date=current date] - Date of the message, or modification date of the file
30612 * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type
30613 * @returns {Promise<Message>} New message object.
30614 * @async
30615 * @static
30616 */
30617async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {
30618 let input = text !== undefined ? text : binary;
30619 if (input === undefined) {
30620 throw new Error('createMessage: must pass options object containing `text` or `binary`');
30621 }
30622 if (text && !util.isString(text) && !util.isStream(text)) {
30623 throw new Error('createMessage: options.text must be a string or stream');
30624 }
30625 if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {
30626 throw new Error('createMessage: options.binary must be a Uint8Array or stream');
30627 }
30628 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30629
30630 const streamType = util.isStream(input);
30631 if (streamType) {
30632 await loadStreamsPonyfill();
30633 input = toStream(input);
30634 }
30635 const literalDataPacket = new LiteralDataPacket(date);
30636 if (text !== undefined) {
30637 literalDataPacket.setText(input, enums.write(enums.literal, format));
30638 } else {
30639 literalDataPacket.setBytes(input, enums.write(enums.literal, format));
30640 }
30641 if (filename !== undefined) {
30642 literalDataPacket.setFilename(filename);
30643 }
30644 const literalDataPacketlist = new PacketList();
30645 literalDataPacketlist.push(literalDataPacket);
30646 const message = new Message(literalDataPacketlist);
30647 message.fromStream = streamType;
30648 return message;
30649}
30650
30651// GPG4Browsers - An OpenPGP implementation in javascript
30652
30653// A Cleartext message can contain the following packets
30654const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
30655
30656/**
30657 * Class that represents an OpenPGP cleartext signed message.
30658 * See {@link https://tools.ietf.org/html/rfc4880#section-7}
30659 */
30660class CleartextMessage {
30661 /**
30662 * @param {String} text - The cleartext of the signed message
30663 * @param {Signature} signature - The detached signature or an empty signature for unsigned messages
30664 */
30665 constructor(text, signature) {
30666 // remove trailing whitespace and normalize EOL to canonical form <CR><LF>
30667 this.text = util.removeTrailingSpaces(text).replace(/\r?\n/g, '\r\n');
30668 if (signature && !(signature instanceof Signature)) {
30669 throw new Error('Invalid signature input');
30670 }
30671 this.signature = signature || new Signature(new PacketList());
30672 }
30673
30674 /**
30675 * Returns the key IDs of the keys that signed the cleartext message
30676 * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
30677 */
30678 getSigningKeyIDs() {
30679 const keyIDs = [];
30680 const signatureList = this.signature.packets;
30681 signatureList.forEach(function(packet) {
30682 keyIDs.push(packet.issuerKeyID);
30683 });
30684 return keyIDs;
30685 }
30686
30687 /**
30688 * Sign the cleartext message
30689 * @param {Array<Key>} privateKeys - private keys with decrypted secret key data for signing
30690 * @param {Signature} [signature] - Any existing detached signature
30691 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]
30692 * @param {Date} [date] - The creation time of the signature that should be created
30693 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
30694 * @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 }]
30695 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30696 * @returns {Promise<CleartextMessage>} New cleartext message with signed content.
30697 * @async
30698 */
30699 async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], notations = [], config$1 = config) {
30700 const literalDataPacket = new LiteralDataPacket();
30701 literalDataPacket.setText(this.text);
30702 const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, notations, true, config$1));
30703 return new CleartextMessage(this.text, newSignature);
30704 }
30705
30706 /**
30707 * Verify signatures of cleartext signed message
30708 * @param {Array<Key>} keys - Array of keys to verify signatures
30709 * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
30710 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30711 * @returns {Promise<Array<{
30712 * keyID: module:type/keyid~KeyID,
30713 * signature: Promise<Signature>,
30714 * verified: Promise<true>
30715 * }>>} List of signer's keyID and validity of signature.
30716 * @async
30717 */
30718 verify(keys, date = new Date(), config$1 = config) {
30719 const signatureList = this.signature.packets.filterByTag(enums.packet.signature); // drop UnparsablePackets
30720 const literalDataPacket = new LiteralDataPacket();
30721 // we assume that cleartext signature is generated based on UTF8 cleartext
30722 literalDataPacket.setText(this.text);
30723 return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config$1);
30724 }
30725
30726 /**
30727 * Get cleartext
30728 * @returns {String} Cleartext of message.
30729 */
30730 getText() {
30731 // normalize end of line to \n
30732 return this.text.replace(/\r\n/g, '\n');
30733 }
30734
30735 /**
30736 * Returns ASCII armored text of cleartext signed message
30737 * @param {Object} [config] - Full configuration, defaults to openpgp.config
30738 * @returns {String | ReadableStream<String>} ASCII armor.
30739 */
30740 armor(config$1 = config) {
30741 let hashes = this.signature.packets.map(function(packet) {
30742 return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase();
30743 });
30744 hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; });
30745 const body = {
30746 hash: hashes.join(),
30747 text: this.text,
30748 data: this.signature.packets.write()
30749 };
30750 return armor(enums.armor.signed, body, undefined, undefined, undefined, config$1);
30751 }
30752}
30753
30754/**
30755 * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object
30756 * @param {Object} options
30757 * @param {String} options.cleartextMessage - Text to be parsed
30758 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30759 * @returns {Promise<CleartextMessage>} New cleartext message object.
30760 * @async
30761 * @static
30762 */
30763async function readCleartextMessage({ cleartextMessage, config: config$1, ...rest }) {
30764 config$1 = { ...config, ...config$1 };
30765 if (!cleartextMessage) {
30766 throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');
30767 }
30768 if (!util.isString(cleartextMessage)) {
30769 throw new Error('readCleartextMessage: options.cleartextMessage must be a string');
30770 }
30771 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30772
30773 const input = await unarmor(cleartextMessage);
30774 if (input.type !== enums.armor.signed) {
30775 throw new Error('No cleartext signed message.');
30776 }
30777 const packetlist = await PacketList.fromBinary(input.data, allowedPackets$5, config$1);
30778 verifyHeaders$1(input.headers, packetlist);
30779 const signature = new Signature(packetlist);
30780 return new CleartextMessage(input.text, signature);
30781}
30782
30783/**
30784 * Compare hash algorithm specified in the armor header with signatures
30785 * @param {Array<String>} headers - Armor headers
30786 * @param {PacketList} packetlist - The packetlist with signature packets
30787 * @private
30788 */
30789function verifyHeaders$1(headers, packetlist) {
30790 const checkHashAlgos = function(hashAlgos) {
30791 const check = packet => algo => packet.hashAlgorithm === algo;
30792
30793 for (let i = 0; i < packetlist.length; i++) {
30794 if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {
30795 return false;
30796 }
30797 }
30798 return true;
30799 };
30800
30801 let oneHeader = null;
30802 let hashAlgos = [];
30803 headers.forEach(function(header) {
30804 oneHeader = header.match(/^Hash: (.+)$/); // get header value
30805 if (oneHeader) {
30806 oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace
30807 oneHeader = oneHeader.split(',');
30808 oneHeader = oneHeader.map(function(hash) {
30809 hash = hash.toLowerCase();
30810 try {
30811 return enums.write(enums.hash, hash);
30812 } catch (e) {
30813 throw new Error('Unknown hash algorithm in armor header: ' + hash);
30814 }
30815 });
30816 hashAlgos = hashAlgos.concat(oneHeader);
30817 } else {
30818 throw new Error('Only "Hash" header allowed in cleartext signed message');
30819 }
30820 });
30821
30822 if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) {
30823 throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed');
30824 } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {
30825 throw new Error('Hash algorithm mismatch in armor header and signature');
30826 }
30827}
30828
30829/**
30830 * Creates a new CleartextMessage object from text
30831 * @param {Object} options
30832 * @param {String} options.text
30833 * @static
30834 * @async
30835 */
30836async function createCleartextMessage({ text, ...rest }) {
30837 if (!text) {
30838 throw new Error('createCleartextMessage: must pass options object containing `text`');
30839 }
30840 if (!util.isString(text)) {
30841 throw new Error('createCleartextMessage: options.text must be a string');
30842 }
30843 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30844
30845 return new CleartextMessage(text);
30846}
30847
30848// OpenPGP.js - An OpenPGP implementation in javascript
30849
30850
30851//////////////////////
30852// //
30853// Key handling //
30854// //
30855//////////////////////
30856
30857
30858/**
30859 * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type.
30860 * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.
30861 * @param {Object} options
30862 * @param {Object|Array<Object>} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`
30863 * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA
30864 * @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.
30865 * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys
30866 * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys:
30867 * curve25519 (default), p256, p384, p521, secp256k1,
30868 * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1
30869 * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures
30870 * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires
30871 * @param {Array<Object>} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`
30872 * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt
30873 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys
30874 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30875 * @returns {Promise<Object>} The generated key object in the form:
30876 * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }
30877 * @async
30878 * @static
30879 */
30880async function generateKey({ userIDs = [], passphrase, type = 'ecc', rsaBits = 4096, curve = 'curve25519', keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config: config$1, ...rest }) {
30881 config$1 = { ...config, ...config$1 }; checkConfig(config$1);
30882 userIDs = toArray$1(userIDs);
30883 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30884
30885 if (userIDs.length === 0) {
30886 throw new Error('UserIDs are required for key generation');
30887 }
30888 if (type === 'rsa' && rsaBits < config$1.minRSABits) {
30889 throw new Error(`rsaBits should be at least ${config$1.minRSABits}, got: ${rsaBits}`);
30890 }
30891
30892 const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };
30893
30894 try {
30895 const { key, revocationCertificate } = await generate$4(options, config$1);
30896 key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config$1));
30897
30898 return {
30899 privateKey: formatObject(key, format, config$1),
30900 publicKey: formatObject(key.toPublic(), format, config$1),
30901 revocationCertificate
30902 };
30903 } catch (err) {
30904 throw util.wrapError('Error generating keypair', err);
30905 }
30906}
30907
30908/**
30909 * Reformats signature packets for a key and rewraps key object.
30910 * @param {Object} options
30911 * @param {PrivateKey} options.privateKey - Private key to reformat
30912 * @param {Object|Array<Object>} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`
30913 * @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.
30914 * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires
30915 * @param {Date} [options.date] - Override the creation date of the key signatures. If the key was previously used to sign messages, it is recommended
30916 * to set the same date as the key creation time to ensure that old message signatures will still be verifiable using the reformatted key.
30917 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys
30918 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30919 * @returns {Promise<Object>} The generated key object in the form:
30920 * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }
30921 * @async
30922 * @static
30923 */
30924async function reformatKey({ privateKey, userIDs = [], passphrase, keyExpirationTime = 0, date, format = 'armored', config: config$1, ...rest }) {
30925 config$1 = { ...config, ...config$1 }; checkConfig(config$1);
30926 userIDs = toArray$1(userIDs);
30927 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30928
30929 if (userIDs.length === 0) {
30930 throw new Error('UserIDs are required for key reformat');
30931 }
30932 const options = { privateKey, userIDs, passphrase, keyExpirationTime, date };
30933
30934 try {
30935 const { key: reformattedKey, revocationCertificate } = await reformat(options, config$1);
30936
30937 return {
30938 privateKey: formatObject(reformattedKey, format, config$1),
30939 publicKey: formatObject(reformattedKey.toPublic(), format, config$1),
30940 revocationCertificate
30941 };
30942 } catch (err) {
30943 throw util.wrapError('Error reformatting keypair', err);
30944 }
30945}
30946
30947/**
30948 * Revokes a key. Requires either a private key or a revocation certificate.
30949 * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.
30950 * @param {Object} options
30951 * @param {Key} options.key - Public or private key to revoke
30952 * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with
30953 * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation
30954 * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation
30955 * @param {String} [options.reasonForRevocation.string=""] - String explaining the reason for revocation
30956 * @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
30957 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)
30958 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30959 * @returns {Promise<Object>} The revoked key in the form:
30960 * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or
30961 * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise
30962 * @async
30963 * @static
30964 */
30965async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config: config$1, ...rest }) {
30966 config$1 = { ...config, ...config$1 }; checkConfig(config$1);
30967 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30968
30969 try {
30970 const revokedKey = revocationCertificate ?
30971 await key.applyRevocationCertificate(revocationCertificate, date, config$1) :
30972 await key.revoke(reasonForRevocation, date, config$1);
30973
30974 return revokedKey.isPrivate() ? {
30975 privateKey: formatObject(revokedKey, format, config$1),
30976 publicKey: formatObject(revokedKey.toPublic(), format, config$1)
30977 } : {
30978 privateKey: null,
30979 publicKey: formatObject(revokedKey, format, config$1)
30980 };
30981 } catch (err) {
30982 throw util.wrapError('Error revoking key', err);
30983 }
30984}
30985
30986/**
30987 * Unlock a private key with the given passphrase.
30988 * This method does not change the original key.
30989 * @param {Object} options
30990 * @param {PrivateKey} options.privateKey - The private key to decrypt
30991 * @param {String|Array<String>} options.passphrase - The user's passphrase(s)
30992 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30993 * @returns {Promise<PrivateKey>} The unlocked key object.
30994 * @async
30995 */
30996async function decryptKey({ privateKey, passphrase, config: config$1, ...rest }) {
30997 config$1 = { ...config, ...config$1 }; checkConfig(config$1);
30998 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30999
31000 if (!privateKey.isPrivate()) {
31001 throw new Error('Cannot decrypt a public key');
31002 }
31003 const clonedPrivateKey = privateKey.clone(true);
31004 const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];
31005
31006 try {
31007 await Promise.all(clonedPrivateKey.getKeys().map(key => (
31008 // try to decrypt each key with any of the given passphrases
31009 util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase)))
31010 )));
31011
31012 await clonedPrivateKey.validate(config$1);
31013 return clonedPrivateKey;
31014 } catch (err) {
31015 clonedPrivateKey.clearPrivateParams();
31016 throw util.wrapError('Error decrypting private key', err);
31017 }
31018}
31019
31020/**
31021 * Lock a private key with the given passphrase.
31022 * This method does not change the original key.
31023 * @param {Object} options
31024 * @param {PrivateKey} options.privateKey - The private key to encrypt
31025 * @param {String|Array<String>} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt
31026 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
31027 * @returns {Promise<PrivateKey>} The locked key object.
31028 * @async
31029 */
31030async function encryptKey({ privateKey, passphrase, config: config$1, ...rest }) {
31031 config$1 = { ...config, ...config$1 }; checkConfig(config$1);
31032 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
31033
31034 if (!privateKey.isPrivate()) {
31035 throw new Error('Cannot encrypt a public key');
31036 }
31037 const clonedPrivateKey = privateKey.clone(true);
31038
31039 const keys = clonedPrivateKey.getKeys();
31040 const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);
31041 if (passphrases.length !== keys.length) {
31042 throw new Error('Invalid number of passphrases given for key encryption');
31043 }
31044
31045 try {
31046 await Promise.all(keys.map(async (key, i) => {
31047 const { keyPacket } = key;
31048 await keyPacket.encrypt(passphrases[i], config$1);
31049 keyPacket.clearPrivateParams();
31050 }));
31051 return clonedPrivateKey;
31052 } catch (err) {
31053 clonedPrivateKey.clearPrivateParams();
31054 throw util.wrapError('Error encrypting private key', err);
31055 }
31056}
31057
31058
31059///////////////////////////////////////////
31060// //
31061// Message encryption and decryption //
31062// //
31063///////////////////////////////////////////
31064
31065
31066/**
31067 * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys`, `passwords` or `sessionKeys`
31068 * must be specified. If signing keys are specified, those will be used to sign the message.
31069 * @param {Object} options
31070 * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}
31071 * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message
31072 * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed
31073 * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message
31074 * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`
31075 * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message
31076 * @param {Signature} [options.signature] - A detached signature to add to the encrypted message
31077 * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs
31078 * @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]`
31079 * @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]`
31080 * @param {Date} [options.date=current date] - Override the creation date of the message signature
31081 * @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' }]`
31082 * @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' }]`
31083 * @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 }]`
31084 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
31085 * @returns {Promise<MaybeStream<String>|MaybeStream<Uint8Array>>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).
31086 * @async
31087 * @static
31088 */
31089async function encrypt$5({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], signatureNotations = [], config: config$1, ...rest }) {
31090 config$1 = { ...config, ...config$1 }; checkConfig(config$1);
31091 checkMessage(message); checkOutputMessageFormat(format);
31092 encryptionKeys = toArray$1(encryptionKeys); signingKeys = toArray$1(signingKeys); passwords = toArray$1(passwords);
31093 signingKeyIDs = toArray$1(signingKeyIDs); encryptionKeyIDs = toArray$1(encryptionKeyIDs); signingUserIDs = toArray$1(signingUserIDs); encryptionUserIDs = toArray$1(encryptionUserIDs); signatureNotations = toArray$1(signatureNotations);
31094 if (rest.detached) {
31095 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.");
31096 }
31097 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');
31098 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');
31099 if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');
31100 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
31101
31102 if (!signingKeys) {
31103 signingKeys = [];
31104 }
31105 const streaming = message.fromStream;
31106 try {
31107 if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified
31108 message = await message.sign(signingKeys, signature, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1);
31109 }
31110 message = message.compress(
31111 await getPreferredAlgo('compression', encryptionKeys, date, encryptionUserIDs, config$1),
31112 config$1
31113 );
31114 message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1);
31115 if (format === 'object') return message;
31116 // serialize data
31117 const armor = format === 'armored';
31118 const data = armor ? message.armor(config$1) : message.write();
31119 return convertStream(data, streaming, armor ? 'utf8' : 'binary');
31120 } catch (err) {
31121 throw util.wrapError('Error encrypting message', err);
31122 }
31123}
31124
31125/**
31126 * Decrypts a message with the user's private key, a session key or a password.
31127 * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).
31128 * @param {Object} options
31129 * @param {Message} options.message - The message object with the encrypted data
31130 * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key
31131 * @param {String|String[]} [options.passwords] - Passwords to decrypt the message
31132 * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }
31133 * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures
31134 * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys
31135 * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.
31136 * @param {Signature} [options.signature] - Detached signature for verification
31137 * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time
31138 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
31139 * @returns {Promise<Object>} Object containing decrypted and verified message in the form:
31140 *
31141 * {
31142 * data: MaybeStream<String>, (if format was 'utf8', the default)
31143 * data: MaybeStream<Uint8Array>, (if format was 'binary')
31144 * filename: String,
31145 * signatures: [
31146 * {
31147 * keyID: module:type/keyid~KeyID,
31148 * verified: Promise<true>,
31149 * signature: Promise<Signature>
31150 * }, ...
31151 * ]
31152 * }
31153 *
31154 * where `signatures` contains a separate entry for each signature packet found in the input message.
31155 * @async
31156 * @static
31157 */
31158async function decrypt$5({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) {
31159 config$1 = { ...config, ...config$1 }; checkConfig(config$1);
31160 checkMessage(message); verificationKeys = toArray$1(verificationKeys); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords); sessionKeys = toArray$1(sessionKeys);
31161 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');
31162 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');
31163 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
31164
31165 try {
31166 const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config$1);
31167 if (!verificationKeys) {
31168 verificationKeys = [];
31169 }
31170
31171 const result = {};
31172 result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config$1) : await decrypted.verify(verificationKeys, date, config$1);
31173 result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();
31174 result.filename = decrypted.getFilename();
31175 linkStreams(result, message);
31176 if (expectSigned) {
31177 if (verificationKeys.length === 0) {
31178 throw new Error('Verification keys are required to verify message signatures');
31179 }
31180 if (result.signatures.length === 0) {
31181 throw new Error('Message is not signed');
31182 }
31183 result.data = concat([
31184 result.data,
31185 fromAsync(async () => {
31186 await util.anyPromise(result.signatures.map(sig => sig.verified));
31187 })
31188 ]);
31189 }
31190 result.data = await convertStream(result.data, message.fromStream, format);
31191 return result;
31192 } catch (err) {
31193 throw util.wrapError('Error decrypting message', err);
31194 }
31195}
31196
31197
31198//////////////////////////////////////////
31199// //
31200// Message signing and verification //
31201// //
31202//////////////////////////////////////////
31203
31204
31205/**
31206 * Signs a message.
31207 * @param {Object} options
31208 * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed
31209 * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext
31210 * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message
31211 * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature
31212 * @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]
31213 * @param {Date} [options.date=current date] - Override the creation date of the signature
31214 * @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' }]`
31215 * @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 }]`
31216 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
31217 * @returns {Promise<MaybeStream<String|Uint8Array>>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).
31218 * @async
31219 * @static
31220 */
31221async function sign$6({ message, signingKeys, format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], signatureNotations = [], config: config$1, ...rest }) {
31222 config$1 = { ...config, ...config$1 }; checkConfig(config$1);
31223 checkCleartextOrMessage(message); checkOutputMessageFormat(format);
31224 signingKeys = toArray$1(signingKeys); signingKeyIDs = toArray$1(signingKeyIDs); signingUserIDs = toArray$1(signingUserIDs); signatureNotations = toArray$1(signatureNotations);
31225
31226 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');
31227 if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');
31228 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
31229
31230 if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format');
31231 if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message');
31232
31233 if (!signingKeys || signingKeys.length === 0) {
31234 throw new Error('No signing keys provided');
31235 }
31236
31237 try {
31238 let signature;
31239 if (detached) {
31240 signature = await message.signDetached(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1);
31241 } else {
31242 signature = await message.sign(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, signatureNotations, config$1);
31243 }
31244 if (format === 'object') return signature;
31245
31246 const armor = format === 'armored';
31247 signature = armor ? signature.armor(config$1) : signature.write();
31248 if (detached) {
31249 signature = transformPair(message.packets.write(), async (readable, writable) => {
31250 await Promise.all([
31251 pipe(signature, writable),
31252 readToEnd(readable).catch(() => {})
31253 ]);
31254 });
31255 }
31256 return convertStream(signature, message.fromStream, armor ? 'utf8' : 'binary');
31257 } catch (err) {
31258 throw util.wrapError('Error signing message', err);
31259 }
31260}
31261
31262/**
31263 * Verifies signatures of cleartext signed message
31264 * @param {Object} options
31265 * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures
31266 * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures
31267 * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys
31268 * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.
31269 * @param {Signature} [options.signature] - Detached signature for verification
31270 * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time
31271 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
31272 * @returns {Promise<Object>} Object containing verified message in the form:
31273 *
31274 * {
31275 * data: MaybeStream<String>, (if `message` was a CleartextMessage)
31276 * data: MaybeStream<Uint8Array>, (if `message` was a Message)
31277 * signatures: [
31278 * {
31279 * keyID: module:type/keyid~KeyID,
31280 * verified: Promise<true>,
31281 * signature: Promise<Signature>
31282 * }, ...
31283 * ]
31284 * }
31285 *
31286 * where `signatures` contains a separate entry for each signature packet found in the input message.
31287 * @async
31288 * @static
31289 */
31290async function verify$6({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config: config$1, ...rest }) {
31291 config$1 = { ...config, ...config$1 }; checkConfig(config$1);
31292 checkCleartextOrMessage(message); verificationKeys = toArray$1(verificationKeys);
31293 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');
31294 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
31295
31296 if (message instanceof CleartextMessage && format === 'binary') throw new Error("Can't return cleartext message data as binary");
31297 if (message instanceof CleartextMessage && signature) throw new Error("Can't verify detached cleartext signature");
31298
31299 try {
31300 const result = {};
31301 if (signature) {
31302 result.signatures = await message.verifyDetached(signature, verificationKeys, date, config$1);
31303 } else {
31304 result.signatures = await message.verify(verificationKeys, date, config$1);
31305 }
31306 result.data = format === 'binary' ? message.getLiteralData() : message.getText();
31307 if (message.fromStream) linkStreams(result, message);
31308 if (expectSigned) {
31309 if (result.signatures.length === 0) {
31310 throw new Error('Message is not signed');
31311 }
31312 result.data = concat([
31313 result.data,
31314 fromAsync(async () => {
31315 await util.anyPromise(result.signatures.map(sig => sig.verified));
31316 })
31317 ]);
31318 }
31319 result.data = await convertStream(result.data, message.fromStream, format);
31320 return result;
31321 } catch (err) {
31322 throw util.wrapError('Error verifying signed message', err);
31323 }
31324}
31325
31326
31327///////////////////////////////////////////////
31328// //
31329// Session key encryption and decryption //
31330// //
31331///////////////////////////////////////////////
31332
31333/**
31334 * Generate a new session key object, taking the algorithm preferences of the passed public keys into account, if any.
31335 * @param {Object} options
31336 * @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}
31337 * @param {Date} [options.date=current date] - Date to select algorithm preferences at
31338 * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for
31339 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
31340 * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.
31341 * @async
31342 * @static
31343 */
31344async function generateSessionKey$1({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) {
31345 config$1 = { ...config, ...config$1 }; checkConfig(config$1);
31346 encryptionKeys = toArray$1(encryptionKeys); encryptionUserIDs = toArray$1(encryptionUserIDs);
31347 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');
31348 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
31349
31350 try {
31351 const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config$1);
31352 return sessionKeys;
31353 } catch (err) {
31354 throw util.wrapError('Error generating session key', err);
31355 }
31356}
31357
31358/**
31359 * Encrypt a symmetric session key with public keys, passwords, or both at once.
31360 * At least one of `encryptionKeys` or `passwords` must be specified.
31361 * @param {Object} options
31362 * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)
31363 * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'
31364 * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'
31365 * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key
31366 * @param {String|String[]} [options.passwords] - Passwords for the message
31367 * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value
31368 * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs
31369 * @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]
31370 * @param {Date} [options.date=current date] - Override the date
31371 * @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' }]`
31372 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
31373 * @returns {Promise<String|Uint8Array>} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).
31374 * @async
31375 * @static
31376 */
31377async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config: config$1, ...rest }) {
31378 config$1 = { ...config, ...config$1 }; checkConfig(config$1);
31379 checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format);
31380 encryptionKeys = toArray$1(encryptionKeys); passwords = toArray$1(passwords); encryptionKeyIDs = toArray$1(encryptionKeyIDs); encryptionUserIDs = toArray$1(encryptionUserIDs);
31381 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');
31382 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
31383
31384 if ((!encryptionKeys || encryptionKeys.length === 0) && (!passwords || passwords.length === 0)) {
31385 throw new Error('No encryption keys or passwords provided.');
31386 }
31387
31388 try {
31389 const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config$1);
31390 return formatObject(message, format, config$1);
31391 } catch (err) {
31392 throw util.wrapError('Error encrypting session key', err);
31393 }
31394}
31395
31396/**
31397 * Decrypt symmetric session keys using private keys or passwords (not both).
31398 * One of `decryptionKeys` or `passwords` must be specified.
31399 * @param {Object} options
31400 * @param {Message} options.message - A message object containing the encrypted session key packets
31401 * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data
31402 * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key
31403 * @param {Date} [options.date] - Date to use for key verification instead of the current time
31404 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
31405 * @returns {Promise<Object[]>} Array of decrypted session key, algorithm pairs in the form:
31406 * { data:Uint8Array, algorithm:String }
31407 * @throws if no session key could be found or decrypted
31408 * @async
31409 * @static
31410 */
31411async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config: config$1, ...rest }) {
31412 config$1 = { ...config, ...config$1 }; checkConfig(config$1);
31413 checkMessage(message); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords);
31414 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');
31415 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
31416
31417 try {
31418 const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, date, config$1);
31419 return sessionKeys;
31420 } catch (err) {
31421 throw util.wrapError('Error decrypting session keys', err);
31422 }
31423}
31424
31425
31426//////////////////////////
31427// //
31428// Helper functions //
31429// //
31430//////////////////////////
31431
31432
31433/**
31434 * Input validation
31435 * @private
31436 */
31437function checkString(data, name) {
31438 if (!util.isString(data)) {
31439 throw new Error('Parameter [' + (name || 'data') + '] must be of type String');
31440 }
31441}
31442function checkBinary(data, name) {
31443 if (!util.isUint8Array(data)) {
31444 throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');
31445 }
31446}
31447function checkMessage(message) {
31448 if (!(message instanceof Message)) {
31449 throw new Error('Parameter [message] needs to be of type Message');
31450 }
31451}
31452function checkCleartextOrMessage(message) {
31453 if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {
31454 throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');
31455 }
31456}
31457function checkOutputMessageFormat(format) {
31458 if (format !== 'armored' && format !== 'binary' && format !== 'object') {
31459 throw new Error(`Unsupported format ${format}`);
31460 }
31461}
31462const defaultConfigPropsCount = Object.keys(config).length;
31463function checkConfig(config$1) {
31464 const inputConfigProps = Object.keys(config$1);
31465 if (inputConfigProps.length !== defaultConfigPropsCount) {
31466 for (const inputProp of inputConfigProps) {
31467 if (config[inputProp] === undefined) {
31468 throw new Error(`Unknown config property: ${inputProp}`);
31469 }
31470 }
31471 }
31472}
31473
31474/**
31475 * Normalize parameter to an array if it is not undefined.
31476 * @param {Object} param - the parameter to be normalized
31477 * @returns {Array<Object>|undefined} The resulting array or undefined.
31478 * @private
31479 */
31480function toArray$1(param) {
31481 if (param && !util.isArray(param)) {
31482 param = [param];
31483 }
31484 return param;
31485}
31486
31487/**
31488 * Convert data to or from Stream
31489 * @param {Object} data - the data to convert
31490 * @param {'web'|'ponyfill'|'node'|false} streaming - Whether to return a ReadableStream, and of what type
31491 * @param {'utf8'|'binary'} [encoding] - How to return data in Node Readable streams
31492 * @returns {Promise<Object>} The data in the respective format.
31493 * @async
31494 * @private
31495 */
31496async function convertStream(data, streaming, encoding = 'utf8') {
31497 const streamType = util.isStream(data);
31498 if (streamType === 'array') {
31499 return readToEnd(data);
31500 }
31501 if (streaming === 'node') {
31502 data = webToNode(data);
31503 if (encoding !== 'binary') data.setEncoding(encoding);
31504 return data;
31505 }
31506 if (streaming === 'web' && streamType === 'ponyfill') {
31507 return toNativeReadable(data);
31508 }
31509 return data;
31510}
31511
31512/**
31513 * Link result.data to the message stream for cancellation.
31514 * Also, forward errors in the message to result.data.
31515 * @param {Object} result - the data to convert
31516 * @param {Message} message - message object
31517 * @returns {Object}
31518 * @private
31519 */
31520function linkStreams(result, message) {
31521 result.data = transformPair(message.packets.stream, async (readable, writable) => {
31522 await pipe(result.data, writable, {
31523 preventClose: true
31524 });
31525 const writer = getWriter(writable);
31526 try {
31527 // Forward errors in the message stream to result.data.
31528 await readToEnd(readable, _ => _);
31529 await writer.close();
31530 } catch (e) {
31531 await writer.abort(e);
31532 }
31533 });
31534}
31535
31536/**
31537 * Convert the object to the given format
31538 * @param {Key|Message} object
31539 * @param {'armored'|'binary'|'object'} format
31540 * @param {Object} config - Full configuration
31541 * @returns {String|Uint8Array|Object}
31542 */
31543function formatObject(object, format, config) {
31544 switch (format) {
31545 case 'object':
31546 return object;
31547 case 'armored':
31548 return object.armor(config);
31549 case 'binary':
31550 return object.write();
31551 default:
31552 throw new Error(`Unsupported format ${format}`);
31553 }
31554}
31555
31556/**
31557 * web-streams-polyfill v3.0.3
31558 */
31559/// <reference lib="es2015.symbol" />
31560const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
31561 Symbol :
31562 description => `Symbol(${description})`;
31563
31564/// <reference lib="dom" />
31565function noop() {
31566 return undefined;
31567}
31568function getGlobals() {
31569 if (typeof self !== 'undefined') {
31570 return self;
31571 }
31572 else if (typeof window !== 'undefined') {
31573 return window;
31574 }
31575 else if (typeof global !== 'undefined') {
31576 return global;
31577 }
31578 return undefined;
31579}
31580const globals = getGlobals();
31581
31582function typeIsObject(x) {
31583 return (typeof x === 'object' && x !== null) || typeof x === 'function';
31584}
31585const rethrowAssertionErrorRejection = noop;
31586
31587const originalPromise = Promise;
31588const originalPromiseThen = Promise.prototype.then;
31589const originalPromiseResolve = Promise.resolve.bind(originalPromise);
31590const originalPromiseReject = Promise.reject.bind(originalPromise);
31591function newPromise(executor) {
31592 return new originalPromise(executor);
31593}
31594function promiseResolvedWith(value) {
31595 return originalPromiseResolve(value);
31596}
31597function promiseRejectedWith(reason) {
31598 return originalPromiseReject(reason);
31599}
31600function PerformPromiseThen(promise, onFulfilled, onRejected) {
31601 // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an
31602 // approximation.
31603 return originalPromiseThen.call(promise, onFulfilled, onRejected);
31604}
31605function uponPromise(promise, onFulfilled, onRejected) {
31606 PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);
31607}
31608function uponFulfillment(promise, onFulfilled) {
31609 uponPromise(promise, onFulfilled);
31610}
31611function uponRejection(promise, onRejected) {
31612 uponPromise(promise, undefined, onRejected);
31613}
31614function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
31615 return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
31616}
31617function setPromiseIsHandledToTrue(promise) {
31618 PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);
31619}
31620const queueMicrotask = (() => {
31621 const globalQueueMicrotask = globals && globals.queueMicrotask;
31622 if (typeof globalQueueMicrotask === 'function') {
31623 return globalQueueMicrotask;
31624 }
31625 const resolvedPromise = promiseResolvedWith(undefined);
31626 return (fn) => PerformPromiseThen(resolvedPromise, fn);
31627})();
31628function reflectCall(F, V, args) {
31629 if (typeof F !== 'function') {
31630 throw new TypeError('Argument is not a function');
31631 }
31632 return Function.prototype.apply.call(F, V, args);
31633}
31634function promiseCall(F, V, args) {
31635 try {
31636 return promiseResolvedWith(reflectCall(F, V, args));
31637 }
31638 catch (value) {
31639 return promiseRejectedWith(value);
31640 }
31641}
31642
31643// Original from Chromium
31644// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js
31645const QUEUE_MAX_ARRAY_SIZE = 16384;
31646/**
31647 * Simple queue structure.
31648 *
31649 * Avoids scalability issues with using a packed array directly by using
31650 * multiple arrays in a linked list and keeping the array size bounded.
31651 */
31652class SimpleQueue {
31653 constructor() {
31654 this._cursor = 0;
31655 this._size = 0;
31656 // _front and _back are always defined.
31657 this._front = {
31658 _elements: [],
31659 _next: undefined
31660 };
31661 this._back = this._front;
31662 // The cursor is used to avoid calling Array.shift().
31663 // It contains the index of the front element of the array inside the
31664 // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).
31665 this._cursor = 0;
31666 // When there is only one node, size === elements.length - cursor.
31667 this._size = 0;
31668 }
31669 get length() {
31670 return this._size;
31671 }
31672 // For exception safety, this method is structured in order:
31673 // 1. Read state
31674 // 2. Calculate required state mutations
31675 // 3. Perform state mutations
31676 push(element) {
31677 const oldBack = this._back;
31678 let newBack = oldBack;
31679 if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
31680 newBack = {
31681 _elements: [],
31682 _next: undefined
31683 };
31684 }
31685 // push() is the mutation most likely to throw an exception, so it
31686 // goes first.
31687 oldBack._elements.push(element);
31688 if (newBack !== oldBack) {
31689 this._back = newBack;
31690 oldBack._next = newBack;
31691 }
31692 ++this._size;
31693 }
31694 // Like push(), shift() follows the read -> calculate -> mutate pattern for
31695 // exception safety.
31696 shift() { // must not be called on an empty queue
31697 const oldFront = this._front;
31698 let newFront = oldFront;
31699 const oldCursor = this._cursor;
31700 let newCursor = oldCursor + 1;
31701 const elements = oldFront._elements;
31702 const element = elements[oldCursor];
31703 if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
31704 newFront = oldFront._next;
31705 newCursor = 0;
31706 }
31707 // No mutations before this point.
31708 --this._size;
31709 this._cursor = newCursor;
31710 if (oldFront !== newFront) {
31711 this._front = newFront;
31712 }
31713 // Permit shifted element to be garbage collected.
31714 elements[oldCursor] = undefined;
31715 return element;
31716 }
31717 // The tricky thing about forEach() is that it can be called
31718 // re-entrantly. The queue may be mutated inside the callback. It is easy to
31719 // see that push() within the callback has no negative effects since the end
31720 // of the queue is checked for on every iteration. If shift() is called
31721 // repeatedly within the callback then the next iteration may return an
31722 // element that has been removed. In this case the callback will be called
31723 // with undefined values until we either "catch up" with elements that still
31724 // exist or reach the back of the queue.
31725 forEach(callback) {
31726 let i = this._cursor;
31727 let node = this._front;
31728 let elements = node._elements;
31729 while (i !== elements.length || node._next !== undefined) {
31730 if (i === elements.length) {
31731 node = node._next;
31732 elements = node._elements;
31733 i = 0;
31734 if (elements.length === 0) {
31735 break;
31736 }
31737 }
31738 callback(elements[i]);
31739 ++i;
31740 }
31741 }
31742 // Return the element that would be returned if shift() was called now,
31743 // without modifying the queue.
31744 peek() { // must not be called on an empty queue
31745 const front = this._front;
31746 const cursor = this._cursor;
31747 return front._elements[cursor];
31748 }
31749}
31750
31751function ReadableStreamReaderGenericInitialize(reader, stream) {
31752 reader._ownerReadableStream = stream;
31753 stream._reader = reader;
31754 if (stream._state === 'readable') {
31755 defaultReaderClosedPromiseInitialize(reader);
31756 }
31757 else if (stream._state === 'closed') {
31758 defaultReaderClosedPromiseInitializeAsResolved(reader);
31759 }
31760 else {
31761 defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
31762 }
31763}
31764// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state
31765// check.
31766function ReadableStreamReaderGenericCancel(reader, reason) {
31767 const stream = reader._ownerReadableStream;
31768 return ReadableStreamCancel(stream, reason);
31769}
31770function ReadableStreamReaderGenericRelease(reader) {
31771 if (reader._ownerReadableStream._state === 'readable') {
31772 defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
31773 }
31774 else {
31775 defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
31776 }
31777 reader._ownerReadableStream._reader = undefined;
31778 reader._ownerReadableStream = undefined;
31779}
31780// Helper functions for the readers.
31781function readerLockException(name) {
31782 return new TypeError('Cannot ' + name + ' a stream using a released reader');
31783}
31784// Helper functions for the ReadableStreamDefaultReader.
31785function defaultReaderClosedPromiseInitialize(reader) {
31786 reader._closedPromise = newPromise((resolve, reject) => {
31787 reader._closedPromise_resolve = resolve;
31788 reader._closedPromise_reject = reject;
31789 });
31790}
31791function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
31792 defaultReaderClosedPromiseInitialize(reader);
31793 defaultReaderClosedPromiseReject(reader, reason);
31794}
31795function defaultReaderClosedPromiseInitializeAsResolved(reader) {
31796 defaultReaderClosedPromiseInitialize(reader);
31797 defaultReaderClosedPromiseResolve(reader);
31798}
31799function defaultReaderClosedPromiseReject(reader, reason) {
31800 if (reader._closedPromise_reject === undefined) {
31801 return;
31802 }
31803 setPromiseIsHandledToTrue(reader._closedPromise);
31804 reader._closedPromise_reject(reason);
31805 reader._closedPromise_resolve = undefined;
31806 reader._closedPromise_reject = undefined;
31807}
31808function defaultReaderClosedPromiseResetToRejected(reader, reason) {
31809 defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
31810}
31811function defaultReaderClosedPromiseResolve(reader) {
31812 if (reader._closedPromise_resolve === undefined) {
31813 return;
31814 }
31815 reader._closedPromise_resolve(undefined);
31816 reader._closedPromise_resolve = undefined;
31817 reader._closedPromise_reject = undefined;
31818}
31819
31820const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
31821const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
31822const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
31823const PullSteps = SymbolPolyfill('[[PullSteps]]');
31824
31825/// <reference lib="es2015.core" />
31826// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
31827const NumberIsFinite = Number.isFinite || function (x) {
31828 return typeof x === 'number' && isFinite(x);
31829};
31830
31831/// <reference lib="es2015.core" />
31832// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill
31833const MathTrunc = Math.trunc || function (v) {
31834 return v < 0 ? Math.ceil(v) : Math.floor(v);
31835};
31836
31837// https://heycam.github.io/webidl/#idl-dictionaries
31838function isDictionary(x) {
31839 return typeof x === 'object' || typeof x === 'function';
31840}
31841function assertDictionary(obj, context) {
31842 if (obj !== undefined && !isDictionary(obj)) {
31843 throw new TypeError(`${context} is not an object.`);
31844 }
31845}
31846// https://heycam.github.io/webidl/#idl-callback-functions
31847function assertFunction(x, context) {
31848 if (typeof x !== 'function') {
31849 throw new TypeError(`${context} is not a function.`);
31850 }
31851}
31852// https://heycam.github.io/webidl/#idl-object
31853function isObject(x) {
31854 return (typeof x === 'object' && x !== null) || typeof x === 'function';
31855}
31856function assertObject(x, context) {
31857 if (!isObject(x)) {
31858 throw new TypeError(`${context} is not an object.`);
31859 }
31860}
31861function assertRequiredArgument(x, position, context) {
31862 if (x === undefined) {
31863 throw new TypeError(`Parameter ${position} is required in '${context}'.`);
31864 }
31865}
31866function assertRequiredField(x, field, context) {
31867 if (x === undefined) {
31868 throw new TypeError(`${field} is required in '${context}'.`);
31869 }
31870}
31871// https://heycam.github.io/webidl/#idl-unrestricted-double
31872function convertUnrestrictedDouble(value) {
31873 return Number(value);
31874}
31875function censorNegativeZero(x) {
31876 return x === 0 ? 0 : x;
31877}
31878function integerPart(x) {
31879 return censorNegativeZero(MathTrunc(x));
31880}
31881// https://heycam.github.io/webidl/#idl-unsigned-long-long
31882function convertUnsignedLongLongWithEnforceRange(value, context) {
31883 const lowerBound = 0;
31884 const upperBound = Number.MAX_SAFE_INTEGER;
31885 let x = Number(value);
31886 x = censorNegativeZero(x);
31887 if (!NumberIsFinite(x)) {
31888 throw new TypeError(`${context} is not a finite number`);
31889 }
31890 x = integerPart(x);
31891 if (x < lowerBound || x > upperBound) {
31892 throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
31893 }
31894 if (!NumberIsFinite(x) || x === 0) {
31895 return 0;
31896 }
31897 // TODO Use BigInt if supported?
31898 // let xBigInt = BigInt(integerPart(x));
31899 // xBigInt = BigInt.asUintN(64, xBigInt);
31900 // return Number(xBigInt);
31901 return x;
31902}
31903
31904function assertReadableStream(x, context) {
31905 if (!IsReadableStream(x)) {
31906 throw new TypeError(`${context} is not a ReadableStream.`);
31907 }
31908}
31909
31910// Abstract operations for the ReadableStream.
31911function AcquireReadableStreamDefaultReader(stream) {
31912 return new ReadableStreamDefaultReader(stream);
31913}
31914// ReadableStream API exposed for controllers.
31915function ReadableStreamAddReadRequest(stream, readRequest) {
31916 stream._reader._readRequests.push(readRequest);
31917}
31918function ReadableStreamFulfillReadRequest(stream, chunk, done) {
31919 const reader = stream._reader;
31920 const readRequest = reader._readRequests.shift();
31921 if (done) {
31922 readRequest._closeSteps();
31923 }
31924 else {
31925 readRequest._chunkSteps(chunk);
31926 }
31927}
31928function ReadableStreamGetNumReadRequests(stream) {
31929 return stream._reader._readRequests.length;
31930}
31931function ReadableStreamHasDefaultReader(stream) {
31932 const reader = stream._reader;
31933 if (reader === undefined) {
31934 return false;
31935 }
31936 if (!IsReadableStreamDefaultReader(reader)) {
31937 return false;
31938 }
31939 return true;
31940}
31941/**
31942 * A default reader vended by a {@link ReadableStream}.
31943 *
31944 * @public
31945 */
31946class ReadableStreamDefaultReader {
31947 constructor(stream) {
31948 assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');
31949 assertReadableStream(stream, 'First parameter');
31950 if (IsReadableStreamLocked(stream)) {
31951 throw new TypeError('This stream has already been locked for exclusive reading by another reader');
31952 }
31953 ReadableStreamReaderGenericInitialize(this, stream);
31954 this._readRequests = new SimpleQueue();
31955 }
31956 /**
31957 * Returns a promise that will be fulfilled when the stream becomes closed,
31958 * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
31959 */
31960 get closed() {
31961 if (!IsReadableStreamDefaultReader(this)) {
31962 return promiseRejectedWith(defaultReaderBrandCheckException('closed'));
31963 }
31964 return this._closedPromise;
31965 }
31966 /**
31967 * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
31968 */
31969 cancel(reason = undefined) {
31970 if (!IsReadableStreamDefaultReader(this)) {
31971 return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));
31972 }
31973 if (this._ownerReadableStream === undefined) {
31974 return promiseRejectedWith(readerLockException('cancel'));
31975 }
31976 return ReadableStreamReaderGenericCancel(this, reason);
31977 }
31978 /**
31979 * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
31980 *
31981 * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
31982 */
31983 read() {
31984 if (!IsReadableStreamDefaultReader(this)) {
31985 return promiseRejectedWith(defaultReaderBrandCheckException('read'));
31986 }
31987 if (this._ownerReadableStream === undefined) {
31988 return promiseRejectedWith(readerLockException('read from'));
31989 }
31990 let resolvePromise;
31991 let rejectPromise;
31992 const promise = newPromise((resolve, reject) => {
31993 resolvePromise = resolve;
31994 rejectPromise = reject;
31995 });
31996 const readRequest = {
31997 _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
31998 _closeSteps: () => resolvePromise({ value: undefined, done: true }),
31999 _errorSteps: e => rejectPromise(e)
32000 };
32001 ReadableStreamDefaultReaderRead(this, readRequest);
32002 return promise;
32003 }
32004 /**
32005 * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
32006 * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
32007 * from now on; otherwise, the reader will appear closed.
32008 *
32009 * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
32010 * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
32011 * do so will throw a `TypeError` and leave the reader locked to the stream.
32012 */
32013 releaseLock() {
32014 if (!IsReadableStreamDefaultReader(this)) {
32015 throw defaultReaderBrandCheckException('releaseLock');
32016 }
32017 if (this._ownerReadableStream === undefined) {
32018 return;
32019 }
32020 if (this._readRequests.length > 0) {
32021 throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
32022 }
32023 ReadableStreamReaderGenericRelease(this);
32024 }
32025}
32026Object.defineProperties(ReadableStreamDefaultReader.prototype, {
32027 cancel: { enumerable: true },
32028 read: { enumerable: true },
32029 releaseLock: { enumerable: true },
32030 closed: { enumerable: true }
32031});
32032if (typeof SymbolPolyfill.toStringTag === 'symbol') {
32033 Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
32034 value: 'ReadableStreamDefaultReader',
32035 configurable: true
32036 });
32037}
32038// Abstract operations for the readers.
32039function IsReadableStreamDefaultReader(x) {
32040 if (!typeIsObject(x)) {
32041 return false;
32042 }
32043 if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {
32044 return false;
32045 }
32046 return true;
32047}
32048function ReadableStreamDefaultReaderRead(reader, readRequest) {
32049 const stream = reader._ownerReadableStream;
32050 stream._disturbed = true;
32051 if (stream._state === 'closed') {
32052 readRequest._closeSteps();
32053 }
32054 else if (stream._state === 'errored') {
32055 readRequest._errorSteps(stream._storedError);
32056 }
32057 else {
32058 stream._readableStreamController[PullSteps](readRequest);
32059 }
32060}
32061// Helper functions for the ReadableStreamDefaultReader.
32062function defaultReaderBrandCheckException(name) {
32063 return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
32064}
32065
32066/// <reference lib="es2018.asynciterable" />
32067let AsyncIteratorPrototype;
32068if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
32069 // We're running inside a ES2018+ environment, but we're compiling to an older syntax.
32070 // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.
32071 AsyncIteratorPrototype = {
32072 // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )
32073 // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator
32074 [SymbolPolyfill.asyncIterator]() {
32075 return this;
32076 }
32077 };
32078 Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false });
32079}
32080
32081/// <reference lib="es2018.asynciterable" />
32082class ReadableStreamAsyncIteratorImpl {
32083 constructor(reader, preventCancel) {
32084 this._ongoingPromise = undefined;
32085 this._isFinished = false;
32086 this._reader = reader;
32087 this._preventCancel = preventCancel;
32088 }
32089 next() {
32090 const nextSteps = () => this._nextSteps();
32091 this._ongoingPromise = this._ongoingPromise ?
32092 transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :
32093 nextSteps();
32094 return this._ongoingPromise;
32095 }
32096 return(value) {
32097 const returnSteps = () => this._returnSteps(value);
32098 return this._ongoingPromise ?
32099 transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :
32100 returnSteps();
32101 }
32102 _nextSteps() {
32103 if (this._isFinished) {
32104 return Promise.resolve({ value: undefined, done: true });
32105 }
32106 const reader = this._reader;
32107 if (reader._ownerReadableStream === undefined) {
32108 return promiseRejectedWith(readerLockException('iterate'));
32109 }
32110 let resolvePromise;
32111 let rejectPromise;
32112 const promise = newPromise((resolve, reject) => {
32113 resolvePromise = resolve;
32114 rejectPromise = reject;
32115 });
32116 const readRequest = {
32117 _chunkSteps: chunk => {
32118 this._ongoingPromise = undefined;
32119 // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.
32120 // FIXME Is this a bug in the specification, or in the test?
32121 queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
32122 },
32123 _closeSteps: () => {
32124 this._ongoingPromise = undefined;
32125 this._isFinished = true;
32126 ReadableStreamReaderGenericRelease(reader);
32127 resolvePromise({ value: undefined, done: true });
32128 },
32129 _errorSteps: reason => {
32130 this._ongoingPromise = undefined;
32131 this._isFinished = true;
32132 ReadableStreamReaderGenericRelease(reader);
32133 rejectPromise(reason);
32134 }
32135 };
32136 ReadableStreamDefaultReaderRead(reader, readRequest);
32137 return promise;
32138 }
32139 _returnSteps(value) {
32140 if (this._isFinished) {
32141 return Promise.resolve({ value, done: true });
32142 }
32143 this._isFinished = true;
32144 const reader = this._reader;
32145 if (reader._ownerReadableStream === undefined) {
32146 return promiseRejectedWith(readerLockException('finish iterating'));
32147 }
32148 if (!this._preventCancel) {
32149 const result = ReadableStreamReaderGenericCancel(reader, value);
32150 ReadableStreamReaderGenericRelease(reader);
32151 return transformPromiseWith(result, () => ({ value, done: true }));
32152 }
32153 ReadableStreamReaderGenericRelease(reader);
32154 return promiseResolvedWith({ value, done: true });
32155 }
32156}
32157const ReadableStreamAsyncIteratorPrototype = {
32158 next() {
32159 if (!IsReadableStreamAsyncIterator(this)) {
32160 return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));
32161 }
32162 return this._asyncIteratorImpl.next();
32163 },
32164 return(value) {
32165 if (!IsReadableStreamAsyncIterator(this)) {
32166 return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));
32167 }
32168 return this._asyncIteratorImpl.return(value);
32169 }
32170};
32171if (AsyncIteratorPrototype !== undefined) {
32172 Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
32173}
32174// Abstract operations for the ReadableStream.
32175function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
32176 const reader = AcquireReadableStreamDefaultReader(stream);
32177 const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
32178 const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
32179 iterator._asyncIteratorImpl = impl;
32180 return iterator;
32181}
32182function IsReadableStreamAsyncIterator(x) {
32183 if (!typeIsObject(x)) {
32184 return false;
32185 }
32186 if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {
32187 return false;
32188 }
32189 return true;
32190}
32191// Helper functions for the ReadableStream.
32192function streamAsyncIteratorBrandCheckException(name) {
32193 return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
32194}
32195
32196/// <reference lib="es2015.core" />
32197// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill
32198const NumberIsNaN = Number.isNaN || function (x) {
32199 // eslint-disable-next-line no-self-compare
32200 return x !== x;
32201};
32202
32203function IsFiniteNonNegativeNumber(v) {
32204 if (!IsNonNegativeNumber(v)) {
32205 return false;
32206 }
32207 if (v === Infinity) {
32208 return false;
32209 }
32210 return true;
32211}
32212function IsNonNegativeNumber(v) {
32213 if (typeof v !== 'number') {
32214 return false;
32215 }
32216 if (NumberIsNaN(v)) {
32217 return false;
32218 }
32219 if (v < 0) {
32220 return false;
32221 }
32222 return true;
32223}
32224
32225function DequeueValue(container) {
32226 const pair = container._queue.shift();
32227 container._queueTotalSize -= pair.size;
32228 if (container._queueTotalSize < 0) {
32229 container._queueTotalSize = 0;
32230 }
32231 return pair.value;
32232}
32233function EnqueueValueWithSize(container, value, size) {
32234 size = Number(size);
32235 if (!IsFiniteNonNegativeNumber(size)) {
32236 throw new RangeError('Size must be a finite, non-NaN, non-negative number.');
32237 }
32238 container._queue.push({ value, size });
32239 container._queueTotalSize += size;
32240}
32241function PeekQueueValue(container) {
32242 const pair = container._queue.peek();
32243 return pair.value;
32244}
32245function ResetQueue(container) {
32246 container._queue = new SimpleQueue();
32247 container._queueTotalSize = 0;
32248}
32249
32250function CreateArrayFromList(elements) {
32251 // We use arrays to represent lists, so this is basically a no-op.
32252 // Do a slice though just in case we happen to depend on the unique-ness.
32253 return elements.slice();
32254}
32255function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
32256 new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
32257}
32258// Not implemented correctly
32259function TransferArrayBuffer(O) {
32260 return O;
32261}
32262// Not implemented correctly
32263function IsDetachedBuffer(O) {
32264 return false;
32265}
32266
32267/**
32268 * A pull-into request in a {@link ReadableByteStreamController}.
32269 *
32270 * @public
32271 */
32272class ReadableStreamBYOBRequest {
32273 constructor() {
32274 throw new TypeError('Illegal constructor');
32275 }
32276 /**
32277 * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
32278 */
32279 get view() {
32280 if (!IsReadableStreamBYOBRequest(this)) {
32281 throw byobRequestBrandCheckException('view');
32282 }
32283 return this._view;
32284 }
32285 respond(bytesWritten) {
32286 if (!IsReadableStreamBYOBRequest(this)) {
32287 throw byobRequestBrandCheckException('respond');
32288 }
32289 assertRequiredArgument(bytesWritten, 1, 'respond');
32290 bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');
32291 if (this._associatedReadableByteStreamController === undefined) {
32292 throw new TypeError('This BYOB request has been invalidated');
32293 }
32294 if (IsDetachedBuffer(this._view.buffer)) ;
32295 ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
32296 }
32297 respondWithNewView(view) {
32298 if (!IsReadableStreamBYOBRequest(this)) {
32299 throw byobRequestBrandCheckException('respondWithNewView');
32300 }
32301 assertRequiredArgument(view, 1, 'respondWithNewView');
32302 if (!ArrayBuffer.isView(view)) {
32303 throw new TypeError('You can only respond with array buffer views');
32304 }
32305 if (view.byteLength === 0) {
32306 throw new TypeError('chunk must have non-zero byteLength');
32307 }
32308 if (view.buffer.byteLength === 0) {
32309 throw new TypeError(`chunk's buffer must have non-zero byteLength`);
32310 }
32311 if (this._associatedReadableByteStreamController === undefined) {
32312 throw new TypeError('This BYOB request has been invalidated');
32313 }
32314 ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
32315 }
32316}
32317Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
32318 respond: { enumerable: true },
32319 respondWithNewView: { enumerable: true },
32320 view: { enumerable: true }
32321});
32322if (typeof SymbolPolyfill.toStringTag === 'symbol') {
32323 Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
32324 value: 'ReadableStreamBYOBRequest',
32325 configurable: true
32326 });
32327}
32328/**
32329 * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
32330 *
32331 * @public
32332 */
32333class ReadableByteStreamController {
32334 constructor() {
32335 throw new TypeError('Illegal constructor');
32336 }
32337 /**
32338 * Returns the current BYOB pull request, or `null` if there isn't one.
32339 */
32340 get byobRequest() {
32341 if (!IsReadableByteStreamController(this)) {
32342 throw byteStreamControllerBrandCheckException('byobRequest');
32343 }
32344 if (this._byobRequest === null && this._pendingPullIntos.length > 0) {
32345 const firstDescriptor = this._pendingPullIntos.peek();
32346 const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
32347 const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
32348 SetUpReadableStreamBYOBRequest(byobRequest, this, view);
32349 this._byobRequest = byobRequest;
32350 }
32351 return this._byobRequest;
32352 }
32353 /**
32354 * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
32355 * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
32356 */
32357 get desiredSize() {
32358 if (!IsReadableByteStreamController(this)) {
32359 throw byteStreamControllerBrandCheckException('desiredSize');
32360 }
32361 return ReadableByteStreamControllerGetDesiredSize(this);
32362 }
32363 /**
32364 * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
32365 * the stream, but once those are read, the stream will become closed.
32366 */
32367 close() {
32368 if (!IsReadableByteStreamController(this)) {
32369 throw byteStreamControllerBrandCheckException('close');
32370 }
32371 if (this._closeRequested) {
32372 throw new TypeError('The stream has already been closed; do not close it again!');
32373 }
32374 const state = this._controlledReadableByteStream._state;
32375 if (state !== 'readable') {
32376 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
32377 }
32378 ReadableByteStreamControllerClose(this);
32379 }
32380 enqueue(chunk) {
32381 if (!IsReadableByteStreamController(this)) {
32382 throw byteStreamControllerBrandCheckException('enqueue');
32383 }
32384 assertRequiredArgument(chunk, 1, 'enqueue');
32385 if (!ArrayBuffer.isView(chunk)) {
32386 throw new TypeError('chunk must be an array buffer view');
32387 }
32388 if (chunk.byteLength === 0) {
32389 throw new TypeError('chunk must have non-zero byteLength');
32390 }
32391 if (chunk.buffer.byteLength === 0) {
32392 throw new TypeError(`chunk's buffer must have non-zero byteLength`);
32393 }
32394 if (this._closeRequested) {
32395 throw new TypeError('stream is closed or draining');
32396 }
32397 const state = this._controlledReadableByteStream._state;
32398 if (state !== 'readable') {
32399 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
32400 }
32401 ReadableByteStreamControllerEnqueue(this, chunk);
32402 }
32403 /**
32404 * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
32405 */
32406 error(e = undefined) {
32407 if (!IsReadableByteStreamController(this)) {
32408 throw byteStreamControllerBrandCheckException('error');
32409 }
32410 ReadableByteStreamControllerError(this, e);
32411 }
32412 /** @internal */
32413 [CancelSteps](reason) {
32414 if (this._pendingPullIntos.length > 0) {
32415 const firstDescriptor = this._pendingPullIntos.peek();
32416 firstDescriptor.bytesFilled = 0;
32417 }
32418 ResetQueue(this);
32419 const result = this._cancelAlgorithm(reason);
32420 ReadableByteStreamControllerClearAlgorithms(this);
32421 return result;
32422 }
32423 /** @internal */
32424 [PullSteps](readRequest) {
32425 const stream = this._controlledReadableByteStream;
32426 if (this._queueTotalSize > 0) {
32427 const entry = this._queue.shift();
32428 this._queueTotalSize -= entry.byteLength;
32429 ReadableByteStreamControllerHandleQueueDrain(this);
32430 const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
32431 readRequest._chunkSteps(view);
32432 return;
32433 }
32434 const autoAllocateChunkSize = this._autoAllocateChunkSize;
32435 if (autoAllocateChunkSize !== undefined) {
32436 let buffer;
32437 try {
32438 buffer = new ArrayBuffer(autoAllocateChunkSize);
32439 }
32440 catch (bufferE) {
32441 readRequest._errorSteps(bufferE);
32442 return;
32443 }
32444 const pullIntoDescriptor = {
32445 buffer,
32446 byteOffset: 0,
32447 byteLength: autoAllocateChunkSize,
32448 bytesFilled: 0,
32449 elementSize: 1,
32450 viewConstructor: Uint8Array,
32451 readerType: 'default'
32452 };
32453 this._pendingPullIntos.push(pullIntoDescriptor);
32454 }
32455 ReadableStreamAddReadRequest(stream, readRequest);
32456 ReadableByteStreamControllerCallPullIfNeeded(this);
32457 }
32458}
32459Object.defineProperties(ReadableByteStreamController.prototype, {
32460 close: { enumerable: true },
32461 enqueue: { enumerable: true },
32462 error: { enumerable: true },
32463 byobRequest: { enumerable: true },
32464 desiredSize: { enumerable: true }
32465});
32466if (typeof SymbolPolyfill.toStringTag === 'symbol') {
32467 Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
32468 value: 'ReadableByteStreamController',
32469 configurable: true
32470 });
32471}
32472// Abstract operations for the ReadableByteStreamController.
32473function IsReadableByteStreamController(x) {
32474 if (!typeIsObject(x)) {
32475 return false;
32476 }
32477 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {
32478 return false;
32479 }
32480 return true;
32481}
32482function IsReadableStreamBYOBRequest(x) {
32483 if (!typeIsObject(x)) {
32484 return false;
32485 }
32486 if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {
32487 return false;
32488 }
32489 return true;
32490}
32491function ReadableByteStreamControllerCallPullIfNeeded(controller) {
32492 const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
32493 if (!shouldPull) {
32494 return;
32495 }
32496 if (controller._pulling) {
32497 controller._pullAgain = true;
32498 return;
32499 }
32500 controller._pulling = true;
32501 // TODO: Test controller argument
32502 const pullPromise = controller._pullAlgorithm();
32503 uponPromise(pullPromise, () => {
32504 controller._pulling = false;
32505 if (controller._pullAgain) {
32506 controller._pullAgain = false;
32507 ReadableByteStreamControllerCallPullIfNeeded(controller);
32508 }
32509 }, e => {
32510 ReadableByteStreamControllerError(controller, e);
32511 });
32512}
32513function ReadableByteStreamControllerClearPendingPullIntos(controller) {
32514 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
32515 controller._pendingPullIntos = new SimpleQueue();
32516}
32517function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
32518 let done = false;
32519 if (stream._state === 'closed') {
32520 done = true;
32521 }
32522 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
32523 if (pullIntoDescriptor.readerType === 'default') {
32524 ReadableStreamFulfillReadRequest(stream, filledView, done);
32525 }
32526 else {
32527 ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
32528 }
32529}
32530function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
32531 const bytesFilled = pullIntoDescriptor.bytesFilled;
32532 const elementSize = pullIntoDescriptor.elementSize;
32533 return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
32534}
32535function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
32536 controller._queue.push({ buffer, byteOffset, byteLength });
32537 controller._queueTotalSize += byteLength;
32538}
32539function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
32540 const elementSize = pullIntoDescriptor.elementSize;
32541 const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
32542 const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
32543 const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
32544 const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
32545 let totalBytesToCopyRemaining = maxBytesToCopy;
32546 let ready = false;
32547 if (maxAlignedBytes > currentAlignedBytes) {
32548 totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
32549 ready = true;
32550 }
32551 const queue = controller._queue;
32552 while (totalBytesToCopyRemaining > 0) {
32553 const headOfQueue = queue.peek();
32554 const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
32555 const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
32556 CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
32557 if (headOfQueue.byteLength === bytesToCopy) {
32558 queue.shift();
32559 }
32560 else {
32561 headOfQueue.byteOffset += bytesToCopy;
32562 headOfQueue.byteLength -= bytesToCopy;
32563 }
32564 controller._queueTotalSize -= bytesToCopy;
32565 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
32566 totalBytesToCopyRemaining -= bytesToCopy;
32567 }
32568 return ready;
32569}
32570function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
32571 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
32572 pullIntoDescriptor.bytesFilled += size;
32573}
32574function ReadableByteStreamControllerHandleQueueDrain(controller) {
32575 if (controller._queueTotalSize === 0 && controller._closeRequested) {
32576 ReadableByteStreamControllerClearAlgorithms(controller);
32577 ReadableStreamClose(controller._controlledReadableByteStream);
32578 }
32579 else {
32580 ReadableByteStreamControllerCallPullIfNeeded(controller);
32581 }
32582}
32583function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
32584 if (controller._byobRequest === null) {
32585 return;
32586 }
32587 controller._byobRequest._associatedReadableByteStreamController = undefined;
32588 controller._byobRequest._view = null;
32589 controller._byobRequest = null;
32590}
32591function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
32592 while (controller._pendingPullIntos.length > 0) {
32593 if (controller._queueTotalSize === 0) {
32594 return;
32595 }
32596 const pullIntoDescriptor = controller._pendingPullIntos.peek();
32597 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
32598 ReadableByteStreamControllerShiftPendingPullInto(controller);
32599 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
32600 }
32601 }
32602}
32603function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
32604 const stream = controller._controlledReadableByteStream;
32605 let elementSize = 1;
32606 if (view.constructor !== DataView) {
32607 elementSize = view.constructor.BYTES_PER_ELEMENT;
32608 }
32609 const ctor = view.constructor;
32610 const buffer = TransferArrayBuffer(view.buffer);
32611 const pullIntoDescriptor = {
32612 buffer,
32613 byteOffset: view.byteOffset,
32614 byteLength: view.byteLength,
32615 bytesFilled: 0,
32616 elementSize,
32617 viewConstructor: ctor,
32618 readerType: 'byob'
32619 };
32620 if (controller._pendingPullIntos.length > 0) {
32621 controller._pendingPullIntos.push(pullIntoDescriptor);
32622 // No ReadableByteStreamControllerCallPullIfNeeded() call since:
32623 // - No change happens on desiredSize
32624 // - The source has already been notified of that there's at least 1 pending read(view)
32625 ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
32626 return;
32627 }
32628 if (stream._state === 'closed') {
32629 const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
32630 readIntoRequest._closeSteps(emptyView);
32631 return;
32632 }
32633 if (controller._queueTotalSize > 0) {
32634 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
32635 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
32636 ReadableByteStreamControllerHandleQueueDrain(controller);
32637 readIntoRequest._chunkSteps(filledView);
32638 return;
32639 }
32640 if (controller._closeRequested) {
32641 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
32642 ReadableByteStreamControllerError(controller, e);
32643 readIntoRequest._errorSteps(e);
32644 return;
32645 }
32646 }
32647 controller._pendingPullIntos.push(pullIntoDescriptor);
32648 ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
32649 ReadableByteStreamControllerCallPullIfNeeded(controller);
32650}
32651function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
32652 firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
32653 const stream = controller._controlledReadableByteStream;
32654 if (ReadableStreamHasBYOBReader(stream)) {
32655 while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
32656 const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
32657 ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
32658 }
32659 }
32660}
32661function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
32662 if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {
32663 throw new RangeError('bytesWritten out of range');
32664 }
32665 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
32666 if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {
32667 // TODO: Figure out whether we should detach the buffer or not here.
32668 return;
32669 }
32670 ReadableByteStreamControllerShiftPendingPullInto(controller);
32671 const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
32672 if (remainderSize > 0) {
32673 const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
32674 const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);
32675 ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
32676 }
32677 pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);
32678 pullIntoDescriptor.bytesFilled -= remainderSize;
32679 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
32680 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
32681}
32682function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
32683 const firstDescriptor = controller._pendingPullIntos.peek();
32684 const state = controller._controlledReadableByteStream._state;
32685 if (state === 'closed') {
32686 if (bytesWritten !== 0) {
32687 throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');
32688 }
32689 ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
32690 }
32691 else {
32692 ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
32693 }
32694 ReadableByteStreamControllerCallPullIfNeeded(controller);
32695}
32696function ReadableByteStreamControllerShiftPendingPullInto(controller) {
32697 const descriptor = controller._pendingPullIntos.shift();
32698 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
32699 return descriptor;
32700}
32701function ReadableByteStreamControllerShouldCallPull(controller) {
32702 const stream = controller._controlledReadableByteStream;
32703 if (stream._state !== 'readable') {
32704 return false;
32705 }
32706 if (controller._closeRequested) {
32707 return false;
32708 }
32709 if (!controller._started) {
32710 return false;
32711 }
32712 if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
32713 return true;
32714 }
32715 if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
32716 return true;
32717 }
32718 const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
32719 if (desiredSize > 0) {
32720 return true;
32721 }
32722 return false;
32723}
32724function ReadableByteStreamControllerClearAlgorithms(controller) {
32725 controller._pullAlgorithm = undefined;
32726 controller._cancelAlgorithm = undefined;
32727}
32728// A client of ReadableByteStreamController may use these functions directly to bypass state check.
32729function ReadableByteStreamControllerClose(controller) {
32730 const stream = controller._controlledReadableByteStream;
32731 if (controller._closeRequested || stream._state !== 'readable') {
32732 return;
32733 }
32734 if (controller._queueTotalSize > 0) {
32735 controller._closeRequested = true;
32736 return;
32737 }
32738 if (controller._pendingPullIntos.length > 0) {
32739 const firstPendingPullInto = controller._pendingPullIntos.peek();
32740 if (firstPendingPullInto.bytesFilled > 0) {
32741 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
32742 ReadableByteStreamControllerError(controller, e);
32743 throw e;
32744 }
32745 }
32746 ReadableByteStreamControllerClearAlgorithms(controller);
32747 ReadableStreamClose(stream);
32748}
32749function ReadableByteStreamControllerEnqueue(controller, chunk) {
32750 const stream = controller._controlledReadableByteStream;
32751 if (controller._closeRequested || stream._state !== 'readable') {
32752 return;
32753 }
32754 const buffer = chunk.buffer;
32755 const byteOffset = chunk.byteOffset;
32756 const byteLength = chunk.byteLength;
32757 const transferredBuffer = TransferArrayBuffer(buffer);
32758 if (ReadableStreamHasDefaultReader(stream)) {
32759 if (ReadableStreamGetNumReadRequests(stream) === 0) {
32760 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
32761 }
32762 else {
32763 const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
32764 ReadableStreamFulfillReadRequest(stream, transferredView, false);
32765 }
32766 }
32767 else if (ReadableStreamHasBYOBReader(stream)) {
32768 // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.
32769 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
32770 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
32771 }
32772 else {
32773 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
32774 }
32775 ReadableByteStreamControllerCallPullIfNeeded(controller);
32776}
32777function ReadableByteStreamControllerError(controller, e) {
32778 const stream = controller._controlledReadableByteStream;
32779 if (stream._state !== 'readable') {
32780 return;
32781 }
32782 ReadableByteStreamControllerClearPendingPullIntos(controller);
32783 ResetQueue(controller);
32784 ReadableByteStreamControllerClearAlgorithms(controller);
32785 ReadableStreamError(stream, e);
32786}
32787function ReadableByteStreamControllerGetDesiredSize(controller) {
32788 const state = controller._controlledReadableByteStream._state;
32789 if (state === 'errored') {
32790 return null;
32791 }
32792 if (state === 'closed') {
32793 return 0;
32794 }
32795 return controller._strategyHWM - controller._queueTotalSize;
32796}
32797function ReadableByteStreamControllerRespond(controller, bytesWritten) {
32798 bytesWritten = Number(bytesWritten);
32799 if (!IsFiniteNonNegativeNumber(bytesWritten)) {
32800 throw new RangeError('bytesWritten must be a finite');
32801 }
32802 ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
32803}
32804function ReadableByteStreamControllerRespondWithNewView(controller, view) {
32805 const firstDescriptor = controller._pendingPullIntos.peek();
32806 if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
32807 throw new RangeError('The region specified by view does not match byobRequest');
32808 }
32809 if (firstDescriptor.byteLength !== view.byteLength) {
32810 throw new RangeError('The buffer of view has different capacity than byobRequest');
32811 }
32812 firstDescriptor.buffer = view.buffer;
32813 ReadableByteStreamControllerRespondInternal(controller, view.byteLength);
32814}
32815function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
32816 controller._controlledReadableByteStream = stream;
32817 controller._pullAgain = false;
32818 controller._pulling = false;
32819 controller._byobRequest = null;
32820 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
32821 controller._queue = controller._queueTotalSize = undefined;
32822 ResetQueue(controller);
32823 controller._closeRequested = false;
32824 controller._started = false;
32825 controller._strategyHWM = highWaterMark;
32826 controller._pullAlgorithm = pullAlgorithm;
32827 controller._cancelAlgorithm = cancelAlgorithm;
32828 controller._autoAllocateChunkSize = autoAllocateChunkSize;
32829 controller._pendingPullIntos = new SimpleQueue();
32830 stream._readableStreamController = controller;
32831 const startResult = startAlgorithm();
32832 uponPromise(promiseResolvedWith(startResult), () => {
32833 controller._started = true;
32834 ReadableByteStreamControllerCallPullIfNeeded(controller);
32835 }, r => {
32836 ReadableByteStreamControllerError(controller, r);
32837 });
32838}
32839function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
32840 const controller = Object.create(ReadableByteStreamController.prototype);
32841 let startAlgorithm = () => undefined;
32842 let pullAlgorithm = () => promiseResolvedWith(undefined);
32843 let cancelAlgorithm = () => promiseResolvedWith(undefined);
32844 if (underlyingByteSource.start !== undefined) {
32845 startAlgorithm = () => underlyingByteSource.start(controller);
32846 }
32847 if (underlyingByteSource.pull !== undefined) {
32848 pullAlgorithm = () => underlyingByteSource.pull(controller);
32849 }
32850 if (underlyingByteSource.cancel !== undefined) {
32851 cancelAlgorithm = reason => underlyingByteSource.cancel(reason);
32852 }
32853 const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
32854 if (autoAllocateChunkSize === 0) {
32855 throw new TypeError('autoAllocateChunkSize must be greater than 0');
32856 }
32857 SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
32858}
32859function SetUpReadableStreamBYOBRequest(request, controller, view) {
32860 request._associatedReadableByteStreamController = controller;
32861 request._view = view;
32862}
32863// Helper functions for the ReadableStreamBYOBRequest.
32864function byobRequestBrandCheckException(name) {
32865 return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
32866}
32867// Helper functions for the ReadableByteStreamController.
32868function byteStreamControllerBrandCheckException(name) {
32869 return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
32870}
32871
32872// Abstract operations for the ReadableStream.
32873function AcquireReadableStreamBYOBReader(stream) {
32874 return new ReadableStreamBYOBReader(stream);
32875}
32876// ReadableStream API exposed for controllers.
32877function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {
32878 stream._reader._readIntoRequests.push(readIntoRequest);
32879}
32880function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
32881 const reader = stream._reader;
32882 const readIntoRequest = reader._readIntoRequests.shift();
32883 if (done) {
32884 readIntoRequest._closeSteps(chunk);
32885 }
32886 else {
32887 readIntoRequest._chunkSteps(chunk);
32888 }
32889}
32890function ReadableStreamGetNumReadIntoRequests(stream) {
32891 return stream._reader._readIntoRequests.length;
32892}
32893function ReadableStreamHasBYOBReader(stream) {
32894 const reader = stream._reader;
32895 if (reader === undefined) {
32896 return false;
32897 }
32898 if (!IsReadableStreamBYOBReader(reader)) {
32899 return false;
32900 }
32901 return true;
32902}
32903/**
32904 * A BYOB reader vended by a {@link ReadableStream}.
32905 *
32906 * @public
32907 */
32908class ReadableStreamBYOBReader {
32909 constructor(stream) {
32910 assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');
32911 assertReadableStream(stream, 'First parameter');
32912 if (IsReadableStreamLocked(stream)) {
32913 throw new TypeError('This stream has already been locked for exclusive reading by another reader');
32914 }
32915 if (!IsReadableByteStreamController(stream._readableStreamController)) {
32916 throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +
32917 'source');
32918 }
32919 ReadableStreamReaderGenericInitialize(this, stream);
32920 this._readIntoRequests = new SimpleQueue();
32921 }
32922 /**
32923 * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
32924 * the reader's lock is released before the stream finishes closing.
32925 */
32926 get closed() {
32927 if (!IsReadableStreamBYOBReader(this)) {
32928 return promiseRejectedWith(byobReaderBrandCheckException('closed'));
32929 }
32930 return this._closedPromise;
32931 }
32932 /**
32933 * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
32934 */
32935 cancel(reason = undefined) {
32936 if (!IsReadableStreamBYOBReader(this)) {
32937 return promiseRejectedWith(byobReaderBrandCheckException('cancel'));
32938 }
32939 if (this._ownerReadableStream === undefined) {
32940 return promiseRejectedWith(readerLockException('cancel'));
32941 }
32942 return ReadableStreamReaderGenericCancel(this, reason);
32943 }
32944 /**
32945 * Attempts to reads bytes into view, and returns a promise resolved with the result.
32946 *
32947 * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
32948 */
32949 read(view) {
32950 if (!IsReadableStreamBYOBReader(this)) {
32951 return promiseRejectedWith(byobReaderBrandCheckException('read'));
32952 }
32953 if (!ArrayBuffer.isView(view)) {
32954 return promiseRejectedWith(new TypeError('view must be an array buffer view'));
32955 }
32956 if (view.byteLength === 0) {
32957 return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));
32958 }
32959 if (view.buffer.byteLength === 0) {
32960 return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
32961 }
32962 if (this._ownerReadableStream === undefined) {
32963 return promiseRejectedWith(readerLockException('read from'));
32964 }
32965 let resolvePromise;
32966 let rejectPromise;
32967 const promise = newPromise((resolve, reject) => {
32968 resolvePromise = resolve;
32969 rejectPromise = reject;
32970 });
32971 const readIntoRequest = {
32972 _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
32973 _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),
32974 _errorSteps: e => rejectPromise(e)
32975 };
32976 ReadableStreamBYOBReaderRead(this, view, readIntoRequest);
32977 return promise;
32978 }
32979 /**
32980 * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
32981 * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
32982 * from now on; otherwise, the reader will appear closed.
32983 *
32984 * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
32985 * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
32986 * do so will throw a `TypeError` and leave the reader locked to the stream.
32987 */
32988 releaseLock() {
32989 if (!IsReadableStreamBYOBReader(this)) {
32990 throw byobReaderBrandCheckException('releaseLock');
32991 }
32992 if (this._ownerReadableStream === undefined) {
32993 return;
32994 }
32995 if (this._readIntoRequests.length > 0) {
32996 throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
32997 }
32998 ReadableStreamReaderGenericRelease(this);
32999 }
33000}
33001Object.defineProperties(ReadableStreamBYOBReader.prototype, {
33002 cancel: { enumerable: true },
33003 read: { enumerable: true },
33004 releaseLock: { enumerable: true },
33005 closed: { enumerable: true }
33006});
33007if (typeof SymbolPolyfill.toStringTag === 'symbol') {
33008 Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
33009 value: 'ReadableStreamBYOBReader',
33010 configurable: true
33011 });
33012}
33013// Abstract operations for the readers.
33014function IsReadableStreamBYOBReader(x) {
33015 if (!typeIsObject(x)) {
33016 return false;
33017 }
33018 if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {
33019 return false;
33020 }
33021 return true;
33022}
33023function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
33024 const stream = reader._ownerReadableStream;
33025 stream._disturbed = true;
33026 if (stream._state === 'errored') {
33027 readIntoRequest._errorSteps(stream._storedError);
33028 }
33029 else {
33030 ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
33031 }
33032}
33033// Helper functions for the ReadableStreamBYOBReader.
33034function byobReaderBrandCheckException(name) {
33035 return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
33036}
33037
33038function ExtractHighWaterMark(strategy, defaultHWM) {
33039 const { highWaterMark } = strategy;
33040 if (highWaterMark === undefined) {
33041 return defaultHWM;
33042 }
33043 if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
33044 throw new RangeError('Invalid highWaterMark');
33045 }
33046 return highWaterMark;
33047}
33048function ExtractSizeAlgorithm(strategy) {
33049 const { size } = strategy;
33050 if (!size) {
33051 return () => 1;
33052 }
33053 return size;
33054}
33055
33056function convertQueuingStrategy(init, context) {
33057 assertDictionary(init, context);
33058 const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
33059 const size = init === null || init === void 0 ? void 0 : init.size;
33060 return {
33061 highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),
33062 size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)
33063 };
33064}
33065function convertQueuingStrategySize(fn, context) {
33066 assertFunction(fn, context);
33067 return chunk => convertUnrestrictedDouble(fn(chunk));
33068}
33069
33070function convertUnderlyingSink(original, context) {
33071 assertDictionary(original, context);
33072 const abort = original === null || original === void 0 ? void 0 : original.abort;
33073 const close = original === null || original === void 0 ? void 0 : original.close;
33074 const start = original === null || original === void 0 ? void 0 : original.start;
33075 const type = original === null || original === void 0 ? void 0 : original.type;
33076 const write = original === null || original === void 0 ? void 0 : original.write;
33077 return {
33078 abort: abort === undefined ?
33079 undefined :
33080 convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),
33081 close: close === undefined ?
33082 undefined :
33083 convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),
33084 start: start === undefined ?
33085 undefined :
33086 convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),
33087 write: write === undefined ?
33088 undefined :
33089 convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),
33090 type
33091 };
33092}
33093function convertUnderlyingSinkAbortCallback(fn, original, context) {
33094 assertFunction(fn, context);
33095 return (reason) => promiseCall(fn, original, [reason]);
33096}
33097function convertUnderlyingSinkCloseCallback(fn, original, context) {
33098 assertFunction(fn, context);
33099 return () => promiseCall(fn, original, []);
33100}
33101function convertUnderlyingSinkStartCallback(fn, original, context) {
33102 assertFunction(fn, context);
33103 return (controller) => reflectCall(fn, original, [controller]);
33104}
33105function convertUnderlyingSinkWriteCallback(fn, original, context) {
33106 assertFunction(fn, context);
33107 return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
33108}
33109
33110function assertWritableStream(x, context) {
33111 if (!IsWritableStream(x)) {
33112 throw new TypeError(`${context} is not a WritableStream.`);
33113 }
33114}
33115
33116/**
33117 * A writable stream represents a destination for data, into which you can write.
33118 *
33119 * @public
33120 */
33121class WritableStream$1 {
33122 constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
33123 if (rawUnderlyingSink === undefined) {
33124 rawUnderlyingSink = null;
33125 }
33126 else {
33127 assertObject(rawUnderlyingSink, 'First parameter');
33128 }
33129 const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
33130 const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');
33131 InitializeWritableStream(this);
33132 const type = underlyingSink.type;
33133 if (type !== undefined) {
33134 throw new RangeError('Invalid type is specified');
33135 }
33136 const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
33137 const highWaterMark = ExtractHighWaterMark(strategy, 1);
33138 SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
33139 }
33140 /**
33141 * Returns whether or not the writable stream is locked to a writer.
33142 */
33143 get locked() {
33144 if (!IsWritableStream(this)) {
33145 throw streamBrandCheckException$2('locked');
33146 }
33147 return IsWritableStreamLocked(this);
33148 }
33149 /**
33150 * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
33151 * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
33152 * mechanism of the underlying sink.
33153 *
33154 * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
33155 * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
33156 * the stream) if the stream is currently locked.
33157 */
33158 abort(reason = undefined) {
33159 if (!IsWritableStream(this)) {
33160 return promiseRejectedWith(streamBrandCheckException$2('abort'));
33161 }
33162 if (IsWritableStreamLocked(this)) {
33163 return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));
33164 }
33165 return WritableStreamAbort(this, reason);
33166 }
33167 /**
33168 * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
33169 * close behavior. During this time any further attempts to write will fail (without erroring the stream).
33170 *
33171 * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
33172 * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
33173 * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
33174 */
33175 close() {
33176 if (!IsWritableStream(this)) {
33177 return promiseRejectedWith(streamBrandCheckException$2('close'));
33178 }
33179 if (IsWritableStreamLocked(this)) {
33180 return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));
33181 }
33182 if (WritableStreamCloseQueuedOrInFlight(this)) {
33183 return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
33184 }
33185 return WritableStreamClose(this);
33186 }
33187 /**
33188 * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
33189 * is locked, no other writer can be acquired until this one is released.
33190 *
33191 * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
33192 * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
33193 * the same time, which would cause the resulting written data to be unpredictable and probably useless.
33194 */
33195 getWriter() {
33196 if (!IsWritableStream(this)) {
33197 throw streamBrandCheckException$2('getWriter');
33198 }
33199 return AcquireWritableStreamDefaultWriter(this);
33200 }
33201}
33202Object.defineProperties(WritableStream$1.prototype, {
33203 abort: { enumerable: true },
33204 close: { enumerable: true },
33205 getWriter: { enumerable: true },
33206 locked: { enumerable: true }
33207});
33208if (typeof SymbolPolyfill.toStringTag === 'symbol') {
33209 Object.defineProperty(WritableStream$1.prototype, SymbolPolyfill.toStringTag, {
33210 value: 'WritableStream',
33211 configurable: true
33212 });
33213}
33214// Abstract operations for the WritableStream.
33215function AcquireWritableStreamDefaultWriter(stream) {
33216 return new WritableStreamDefaultWriter(stream);
33217}
33218// Throws if and only if startAlgorithm throws.
33219function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
33220 const stream = Object.create(WritableStream$1.prototype);
33221 InitializeWritableStream(stream);
33222 const controller = Object.create(WritableStreamDefaultController.prototype);
33223 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
33224 return stream;
33225}
33226function InitializeWritableStream(stream) {
33227 stream._state = 'writable';
33228 // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is
33229 // 'erroring' or 'errored'. May be set to an undefined value.
33230 stream._storedError = undefined;
33231 stream._writer = undefined;
33232 // Initialize to undefined first because the constructor of the controller checks this
33233 // variable to validate the caller.
33234 stream._writableStreamController = undefined;
33235 // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data
33236 // producer without waiting for the queued writes to finish.
33237 stream._writeRequests = new SimpleQueue();
33238 // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents
33239 // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.
33240 stream._inFlightWriteRequest = undefined;
33241 // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer
33242 // has been detached.
33243 stream._closeRequest = undefined;
33244 // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it
33245 // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.
33246 stream._inFlightCloseRequest = undefined;
33247 // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.
33248 stream._pendingAbortRequest = undefined;
33249 // The backpressure signal set by the controller.
33250 stream._backpressure = false;
33251}
33252function IsWritableStream(x) {
33253 if (!typeIsObject(x)) {
33254 return false;
33255 }
33256 if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {
33257 return false;
33258 }
33259 return true;
33260}
33261function IsWritableStreamLocked(stream) {
33262 if (stream._writer === undefined) {
33263 return false;
33264 }
33265 return true;
33266}
33267function WritableStreamAbort(stream, reason) {
33268 const state = stream._state;
33269 if (state === 'closed' || state === 'errored') {
33270 return promiseResolvedWith(undefined);
33271 }
33272 if (stream._pendingAbortRequest !== undefined) {
33273 return stream._pendingAbortRequest._promise;
33274 }
33275 let wasAlreadyErroring = false;
33276 if (state === 'erroring') {
33277 wasAlreadyErroring = true;
33278 // reason will not be used, so don't keep a reference to it.
33279 reason = undefined;
33280 }
33281 const promise = newPromise((resolve, reject) => {
33282 stream._pendingAbortRequest = {
33283 _promise: undefined,
33284 _resolve: resolve,
33285 _reject: reject,
33286 _reason: reason,
33287 _wasAlreadyErroring: wasAlreadyErroring
33288 };
33289 });
33290 stream._pendingAbortRequest._promise = promise;
33291 if (!wasAlreadyErroring) {
33292 WritableStreamStartErroring(stream, reason);
33293 }
33294 return promise;
33295}
33296function WritableStreamClose(stream) {
33297 const state = stream._state;
33298 if (state === 'closed' || state === 'errored') {
33299 return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
33300 }
33301 const promise = newPromise((resolve, reject) => {
33302 const closeRequest = {
33303 _resolve: resolve,
33304 _reject: reject
33305 };
33306 stream._closeRequest = closeRequest;
33307 });
33308 const writer = stream._writer;
33309 if (writer !== undefined && stream._backpressure && state === 'writable') {
33310 defaultWriterReadyPromiseResolve(writer);
33311 }
33312 WritableStreamDefaultControllerClose(stream._writableStreamController);
33313 return promise;
33314}
33315// WritableStream API exposed for controllers.
33316function WritableStreamAddWriteRequest(stream) {
33317 const promise = newPromise((resolve, reject) => {
33318 const writeRequest = {
33319 _resolve: resolve,
33320 _reject: reject
33321 };
33322 stream._writeRequests.push(writeRequest);
33323 });
33324 return promise;
33325}
33326function WritableStreamDealWithRejection(stream, error) {
33327 const state = stream._state;
33328 if (state === 'writable') {
33329 WritableStreamStartErroring(stream, error);
33330 return;
33331 }
33332 WritableStreamFinishErroring(stream);
33333}
33334function WritableStreamStartErroring(stream, reason) {
33335 const controller = stream._writableStreamController;
33336 stream._state = 'erroring';
33337 stream._storedError = reason;
33338 const writer = stream._writer;
33339 if (writer !== undefined) {
33340 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
33341 }
33342 if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {
33343 WritableStreamFinishErroring(stream);
33344 }
33345}
33346function WritableStreamFinishErroring(stream) {
33347 stream._state = 'errored';
33348 stream._writableStreamController[ErrorSteps]();
33349 const storedError = stream._storedError;
33350 stream._writeRequests.forEach(writeRequest => {
33351 writeRequest._reject(storedError);
33352 });
33353 stream._writeRequests = new SimpleQueue();
33354 if (stream._pendingAbortRequest === undefined) {
33355 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
33356 return;
33357 }
33358 const abortRequest = stream._pendingAbortRequest;
33359 stream._pendingAbortRequest = undefined;
33360 if (abortRequest._wasAlreadyErroring) {
33361 abortRequest._reject(storedError);
33362 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
33363 return;
33364 }
33365 const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
33366 uponPromise(promise, () => {
33367 abortRequest._resolve();
33368 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
33369 }, (reason) => {
33370 abortRequest._reject(reason);
33371 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
33372 });
33373}
33374function WritableStreamFinishInFlightWrite(stream) {
33375 stream._inFlightWriteRequest._resolve(undefined);
33376 stream._inFlightWriteRequest = undefined;
33377}
33378function WritableStreamFinishInFlightWriteWithError(stream, error) {
33379 stream._inFlightWriteRequest._reject(error);
33380 stream._inFlightWriteRequest = undefined;
33381 WritableStreamDealWithRejection(stream, error);
33382}
33383function WritableStreamFinishInFlightClose(stream) {
33384 stream._inFlightCloseRequest._resolve(undefined);
33385 stream._inFlightCloseRequest = undefined;
33386 const state = stream._state;
33387 if (state === 'erroring') {
33388 // The error was too late to do anything, so it is ignored.
33389 stream._storedError = undefined;
33390 if (stream._pendingAbortRequest !== undefined) {
33391 stream._pendingAbortRequest._resolve();
33392 stream._pendingAbortRequest = undefined;
33393 }
33394 }
33395 stream._state = 'closed';
33396 const writer = stream._writer;
33397 if (writer !== undefined) {
33398 defaultWriterClosedPromiseResolve(writer);
33399 }
33400}
33401function WritableStreamFinishInFlightCloseWithError(stream, error) {
33402 stream._inFlightCloseRequest._reject(error);
33403 stream._inFlightCloseRequest = undefined;
33404 // Never execute sink abort() after sink close().
33405 if (stream._pendingAbortRequest !== undefined) {
33406 stream._pendingAbortRequest._reject(error);
33407 stream._pendingAbortRequest = undefined;
33408 }
33409 WritableStreamDealWithRejection(stream, error);
33410}
33411// TODO(ricea): Fix alphabetical order.
33412function WritableStreamCloseQueuedOrInFlight(stream) {
33413 if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {
33414 return false;
33415 }
33416 return true;
33417}
33418function WritableStreamHasOperationMarkedInFlight(stream) {
33419 if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {
33420 return false;
33421 }
33422 return true;
33423}
33424function WritableStreamMarkCloseRequestInFlight(stream) {
33425 stream._inFlightCloseRequest = stream._closeRequest;
33426 stream._closeRequest = undefined;
33427}
33428function WritableStreamMarkFirstWriteRequestInFlight(stream) {
33429 stream._inFlightWriteRequest = stream._writeRequests.shift();
33430}
33431function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
33432 if (stream._closeRequest !== undefined) {
33433 stream._closeRequest._reject(stream._storedError);
33434 stream._closeRequest = undefined;
33435 }
33436 const writer = stream._writer;
33437 if (writer !== undefined) {
33438 defaultWriterClosedPromiseReject(writer, stream._storedError);
33439 }
33440}
33441function WritableStreamUpdateBackpressure(stream, backpressure) {
33442 const writer = stream._writer;
33443 if (writer !== undefined && backpressure !== stream._backpressure) {
33444 if (backpressure) {
33445 defaultWriterReadyPromiseReset(writer);
33446 }
33447 else {
33448 defaultWriterReadyPromiseResolve(writer);
33449 }
33450 }
33451 stream._backpressure = backpressure;
33452}
33453/**
33454 * A default writer vended by a {@link WritableStream}.
33455 *
33456 * @public
33457 */
33458class WritableStreamDefaultWriter {
33459 constructor(stream) {
33460 assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');
33461 assertWritableStream(stream, 'First parameter');
33462 if (IsWritableStreamLocked(stream)) {
33463 throw new TypeError('This stream has already been locked for exclusive writing by another writer');
33464 }
33465 this._ownerWritableStream = stream;
33466 stream._writer = this;
33467 const state = stream._state;
33468 if (state === 'writable') {
33469 if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
33470 defaultWriterReadyPromiseInitialize(this);
33471 }
33472 else {
33473 defaultWriterReadyPromiseInitializeAsResolved(this);
33474 }
33475 defaultWriterClosedPromiseInitialize(this);
33476 }
33477 else if (state === 'erroring') {
33478 defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
33479 defaultWriterClosedPromiseInitialize(this);
33480 }
33481 else if (state === 'closed') {
33482 defaultWriterReadyPromiseInitializeAsResolved(this);
33483 defaultWriterClosedPromiseInitializeAsResolved(this);
33484 }
33485 else {
33486 const storedError = stream._storedError;
33487 defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
33488 defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
33489 }
33490 }
33491 /**
33492 * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
33493 * the writer’s lock is released before the stream finishes closing.
33494 */
33495 get closed() {
33496 if (!IsWritableStreamDefaultWriter(this)) {
33497 return promiseRejectedWith(defaultWriterBrandCheckException('closed'));
33498 }
33499 return this._closedPromise;
33500 }
33501 /**
33502 * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
33503 * A producer can use this information to determine the right amount of data to write.
33504 *
33505 * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
33506 * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
33507 * the writer’s lock is released.
33508 */
33509 get desiredSize() {
33510 if (!IsWritableStreamDefaultWriter(this)) {
33511 throw defaultWriterBrandCheckException('desiredSize');
33512 }
33513 if (this._ownerWritableStream === undefined) {
33514 throw defaultWriterLockException('desiredSize');
33515 }
33516 return WritableStreamDefaultWriterGetDesiredSize(this);
33517 }
33518 /**
33519 * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
33520 * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
33521 * back to zero or below, the getter will return a new promise that stays pending until the next transition.
33522 *
33523 * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
33524 * rejected.
33525 */
33526 get ready() {
33527 if (!IsWritableStreamDefaultWriter(this)) {
33528 return promiseRejectedWith(defaultWriterBrandCheckException('ready'));
33529 }
33530 return this._readyPromise;
33531 }
33532 /**
33533 * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
33534 */
33535 abort(reason = undefined) {
33536 if (!IsWritableStreamDefaultWriter(this)) {
33537 return promiseRejectedWith(defaultWriterBrandCheckException('abort'));
33538 }
33539 if (this._ownerWritableStream === undefined) {
33540 return promiseRejectedWith(defaultWriterLockException('abort'));
33541 }
33542 return WritableStreamDefaultWriterAbort(this, reason);
33543 }
33544 /**
33545 * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
33546 */
33547 close() {
33548 if (!IsWritableStreamDefaultWriter(this)) {
33549 return promiseRejectedWith(defaultWriterBrandCheckException('close'));
33550 }
33551 const stream = this._ownerWritableStream;
33552 if (stream === undefined) {
33553 return promiseRejectedWith(defaultWriterLockException('close'));
33554 }
33555 if (WritableStreamCloseQueuedOrInFlight(stream)) {
33556 return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
33557 }
33558 return WritableStreamDefaultWriterClose(this);
33559 }
33560 /**
33561 * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
33562 * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
33563 * now on; otherwise, the writer will appear closed.
33564 *
33565 * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
33566 * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
33567 * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
33568 * other producers from writing in an interleaved manner.
33569 */
33570 releaseLock() {
33571 if (!IsWritableStreamDefaultWriter(this)) {
33572 throw defaultWriterBrandCheckException('releaseLock');
33573 }
33574 const stream = this._ownerWritableStream;
33575 if (stream === undefined) {
33576 return;
33577 }
33578 WritableStreamDefaultWriterRelease(this);
33579 }
33580 write(chunk = undefined) {
33581 if (!IsWritableStreamDefaultWriter(this)) {
33582 return promiseRejectedWith(defaultWriterBrandCheckException('write'));
33583 }
33584 if (this._ownerWritableStream === undefined) {
33585 return promiseRejectedWith(defaultWriterLockException('write to'));
33586 }
33587 return WritableStreamDefaultWriterWrite(this, chunk);
33588 }
33589}
33590Object.defineProperties(WritableStreamDefaultWriter.prototype, {
33591 abort: { enumerable: true },
33592 close: { enumerable: true },
33593 releaseLock: { enumerable: true },
33594 write: { enumerable: true },
33595 closed: { enumerable: true },
33596 desiredSize: { enumerable: true },
33597 ready: { enumerable: true }
33598});
33599if (typeof SymbolPolyfill.toStringTag === 'symbol') {
33600 Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
33601 value: 'WritableStreamDefaultWriter',
33602 configurable: true
33603 });
33604}
33605// Abstract operations for the WritableStreamDefaultWriter.
33606function IsWritableStreamDefaultWriter(x) {
33607 if (!typeIsObject(x)) {
33608 return false;
33609 }
33610 if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {
33611 return false;
33612 }
33613 return true;
33614}
33615// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.
33616function WritableStreamDefaultWriterAbort(writer, reason) {
33617 const stream = writer._ownerWritableStream;
33618 return WritableStreamAbort(stream, reason);
33619}
33620function WritableStreamDefaultWriterClose(writer) {
33621 const stream = writer._ownerWritableStream;
33622 return WritableStreamClose(stream);
33623}
33624function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
33625 const stream = writer._ownerWritableStream;
33626 const state = stream._state;
33627 if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
33628 return promiseResolvedWith(undefined);
33629 }
33630 if (state === 'errored') {
33631 return promiseRejectedWith(stream._storedError);
33632 }
33633 return WritableStreamDefaultWriterClose(writer);
33634}
33635function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
33636 if (writer._closedPromiseState === 'pending') {
33637 defaultWriterClosedPromiseReject(writer, error);
33638 }
33639 else {
33640 defaultWriterClosedPromiseResetToRejected(writer, error);
33641 }
33642}
33643function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
33644 if (writer._readyPromiseState === 'pending') {
33645 defaultWriterReadyPromiseReject(writer, error);
33646 }
33647 else {
33648 defaultWriterReadyPromiseResetToRejected(writer, error);
33649 }
33650}
33651function WritableStreamDefaultWriterGetDesiredSize(writer) {
33652 const stream = writer._ownerWritableStream;
33653 const state = stream._state;
33654 if (state === 'errored' || state === 'erroring') {
33655 return null;
33656 }
33657 if (state === 'closed') {
33658 return 0;
33659 }
33660 return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
33661}
33662function WritableStreamDefaultWriterRelease(writer) {
33663 const stream = writer._ownerWritableStream;
33664 const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
33665 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
33666 // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not
33667 // rejected until afterwards. This means that simply testing state will not work.
33668 WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
33669 stream._writer = undefined;
33670 writer._ownerWritableStream = undefined;
33671}
33672function WritableStreamDefaultWriterWrite(writer, chunk) {
33673 const stream = writer._ownerWritableStream;
33674 const controller = stream._writableStreamController;
33675 const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
33676 if (stream !== writer._ownerWritableStream) {
33677 return promiseRejectedWith(defaultWriterLockException('write to'));
33678 }
33679 const state = stream._state;
33680 if (state === 'errored') {
33681 return promiseRejectedWith(stream._storedError);
33682 }
33683 if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
33684 return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));
33685 }
33686 if (state === 'erroring') {
33687 return promiseRejectedWith(stream._storedError);
33688 }
33689 const promise = WritableStreamAddWriteRequest(stream);
33690 WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
33691 return promise;
33692}
33693const closeSentinel = {};
33694/**
33695 * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
33696 *
33697 * @public
33698 */
33699class WritableStreamDefaultController {
33700 constructor() {
33701 throw new TypeError('Illegal constructor');
33702 }
33703 /**
33704 * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
33705 *
33706 * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
33707 * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
33708 * normal lifecycle of interactions with the underlying sink.
33709 */
33710 error(e = undefined) {
33711 if (!IsWritableStreamDefaultController(this)) {
33712 throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');
33713 }
33714 const state = this._controlledWritableStream._state;
33715 if (state !== 'writable') {
33716 // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so
33717 // just treat it as a no-op.
33718 return;
33719 }
33720 WritableStreamDefaultControllerError(this, e);
33721 }
33722 /** @internal */
33723 [AbortSteps](reason) {
33724 const result = this._abortAlgorithm(reason);
33725 WritableStreamDefaultControllerClearAlgorithms(this);
33726 return result;
33727 }
33728 /** @internal */
33729 [ErrorSteps]() {
33730 ResetQueue(this);
33731 }
33732}
33733Object.defineProperties(WritableStreamDefaultController.prototype, {
33734 error: { enumerable: true }
33735});
33736if (typeof SymbolPolyfill.toStringTag === 'symbol') {
33737 Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
33738 value: 'WritableStreamDefaultController',
33739 configurable: true
33740 });
33741}
33742// Abstract operations implementing interface required by the WritableStream.
33743function IsWritableStreamDefaultController(x) {
33744 if (!typeIsObject(x)) {
33745 return false;
33746 }
33747 if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {
33748 return false;
33749 }
33750 return true;
33751}
33752function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
33753 controller._controlledWritableStream = stream;
33754 stream._writableStreamController = controller;
33755 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
33756 controller._queue = undefined;
33757 controller._queueTotalSize = undefined;
33758 ResetQueue(controller);
33759 controller._started = false;
33760 controller._strategySizeAlgorithm = sizeAlgorithm;
33761 controller._strategyHWM = highWaterMark;
33762 controller._writeAlgorithm = writeAlgorithm;
33763 controller._closeAlgorithm = closeAlgorithm;
33764 controller._abortAlgorithm = abortAlgorithm;
33765 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
33766 WritableStreamUpdateBackpressure(stream, backpressure);
33767 const startResult = startAlgorithm();
33768 const startPromise = promiseResolvedWith(startResult);
33769 uponPromise(startPromise, () => {
33770 controller._started = true;
33771 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
33772 }, r => {
33773 controller._started = true;
33774 WritableStreamDealWithRejection(stream, r);
33775 });
33776}
33777function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
33778 const controller = Object.create(WritableStreamDefaultController.prototype);
33779 let startAlgorithm = () => undefined;
33780 let writeAlgorithm = () => promiseResolvedWith(undefined);
33781 let closeAlgorithm = () => promiseResolvedWith(undefined);
33782 let abortAlgorithm = () => promiseResolvedWith(undefined);
33783 if (underlyingSink.start !== undefined) {
33784 startAlgorithm = () => underlyingSink.start(controller);
33785 }
33786 if (underlyingSink.write !== undefined) {
33787 writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
33788 }
33789 if (underlyingSink.close !== undefined) {
33790 closeAlgorithm = () => underlyingSink.close();
33791 }
33792 if (underlyingSink.abort !== undefined) {
33793 abortAlgorithm = reason => underlyingSink.abort(reason);
33794 }
33795 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
33796}
33797// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
33798function WritableStreamDefaultControllerClearAlgorithms(controller) {
33799 controller._writeAlgorithm = undefined;
33800 controller._closeAlgorithm = undefined;
33801 controller._abortAlgorithm = undefined;
33802 controller._strategySizeAlgorithm = undefined;
33803}
33804function WritableStreamDefaultControllerClose(controller) {
33805 EnqueueValueWithSize(controller, closeSentinel, 0);
33806 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
33807}
33808function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
33809 try {
33810 return controller._strategySizeAlgorithm(chunk);
33811 }
33812 catch (chunkSizeE) {
33813 WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
33814 return 1;
33815 }
33816}
33817function WritableStreamDefaultControllerGetDesiredSize(controller) {
33818 return controller._strategyHWM - controller._queueTotalSize;
33819}
33820function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
33821 try {
33822 EnqueueValueWithSize(controller, chunk, chunkSize);
33823 }
33824 catch (enqueueE) {
33825 WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
33826 return;
33827 }
33828 const stream = controller._controlledWritableStream;
33829 if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {
33830 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
33831 WritableStreamUpdateBackpressure(stream, backpressure);
33832 }
33833 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
33834}
33835// Abstract operations for the WritableStreamDefaultController.
33836function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
33837 const stream = controller._controlledWritableStream;
33838 if (!controller._started) {
33839 return;
33840 }
33841 if (stream._inFlightWriteRequest !== undefined) {
33842 return;
33843 }
33844 const state = stream._state;
33845 if (state === 'erroring') {
33846 WritableStreamFinishErroring(stream);
33847 return;
33848 }
33849 if (controller._queue.length === 0) {
33850 return;
33851 }
33852 const value = PeekQueueValue(controller);
33853 if (value === closeSentinel) {
33854 WritableStreamDefaultControllerProcessClose(controller);
33855 }
33856 else {
33857 WritableStreamDefaultControllerProcessWrite(controller, value);
33858 }
33859}
33860function WritableStreamDefaultControllerErrorIfNeeded(controller, error) {
33861 if (controller._controlledWritableStream._state === 'writable') {
33862 WritableStreamDefaultControllerError(controller, error);
33863 }
33864}
33865function WritableStreamDefaultControllerProcessClose(controller) {
33866 const stream = controller._controlledWritableStream;
33867 WritableStreamMarkCloseRequestInFlight(stream);
33868 DequeueValue(controller);
33869 const sinkClosePromise = controller._closeAlgorithm();
33870 WritableStreamDefaultControllerClearAlgorithms(controller);
33871 uponPromise(sinkClosePromise, () => {
33872 WritableStreamFinishInFlightClose(stream);
33873 }, reason => {
33874 WritableStreamFinishInFlightCloseWithError(stream, reason);
33875 });
33876}
33877function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
33878 const stream = controller._controlledWritableStream;
33879 WritableStreamMarkFirstWriteRequestInFlight(stream);
33880 const sinkWritePromise = controller._writeAlgorithm(chunk);
33881 uponPromise(sinkWritePromise, () => {
33882 WritableStreamFinishInFlightWrite(stream);
33883 const state = stream._state;
33884 DequeueValue(controller);
33885 if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {
33886 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
33887 WritableStreamUpdateBackpressure(stream, backpressure);
33888 }
33889 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
33890 }, reason => {
33891 if (stream._state === 'writable') {
33892 WritableStreamDefaultControllerClearAlgorithms(controller);
33893 }
33894 WritableStreamFinishInFlightWriteWithError(stream, reason);
33895 });
33896}
33897function WritableStreamDefaultControllerGetBackpressure(controller) {
33898 const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
33899 return desiredSize <= 0;
33900}
33901// A client of WritableStreamDefaultController may use these functions directly to bypass state check.
33902function WritableStreamDefaultControllerError(controller, error) {
33903 const stream = controller._controlledWritableStream;
33904 WritableStreamDefaultControllerClearAlgorithms(controller);
33905 WritableStreamStartErroring(stream, error);
33906}
33907// Helper functions for the WritableStream.
33908function streamBrandCheckException$2(name) {
33909 return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
33910}
33911// Helper functions for the WritableStreamDefaultWriter.
33912function defaultWriterBrandCheckException(name) {
33913 return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
33914}
33915function defaultWriterLockException(name) {
33916 return new TypeError('Cannot ' + name + ' a stream using a released writer');
33917}
33918function defaultWriterClosedPromiseInitialize(writer) {
33919 writer._closedPromise = newPromise((resolve, reject) => {
33920 writer._closedPromise_resolve = resolve;
33921 writer._closedPromise_reject = reject;
33922 writer._closedPromiseState = 'pending';
33923 });
33924}
33925function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
33926 defaultWriterClosedPromiseInitialize(writer);
33927 defaultWriterClosedPromiseReject(writer, reason);
33928}
33929function defaultWriterClosedPromiseInitializeAsResolved(writer) {
33930 defaultWriterClosedPromiseInitialize(writer);
33931 defaultWriterClosedPromiseResolve(writer);
33932}
33933function defaultWriterClosedPromiseReject(writer, reason) {
33934 if (writer._closedPromise_reject === undefined) {
33935 return;
33936 }
33937 setPromiseIsHandledToTrue(writer._closedPromise);
33938 writer._closedPromise_reject(reason);
33939 writer._closedPromise_resolve = undefined;
33940 writer._closedPromise_reject = undefined;
33941 writer._closedPromiseState = 'rejected';
33942}
33943function defaultWriterClosedPromiseResetToRejected(writer, reason) {
33944 defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
33945}
33946function defaultWriterClosedPromiseResolve(writer) {
33947 if (writer._closedPromise_resolve === undefined) {
33948 return;
33949 }
33950 writer._closedPromise_resolve(undefined);
33951 writer._closedPromise_resolve = undefined;
33952 writer._closedPromise_reject = undefined;
33953 writer._closedPromiseState = 'resolved';
33954}
33955function defaultWriterReadyPromiseInitialize(writer) {
33956 writer._readyPromise = newPromise((resolve, reject) => {
33957 writer._readyPromise_resolve = resolve;
33958 writer._readyPromise_reject = reject;
33959 });
33960 writer._readyPromiseState = 'pending';
33961}
33962function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
33963 defaultWriterReadyPromiseInitialize(writer);
33964 defaultWriterReadyPromiseReject(writer, reason);
33965}
33966function defaultWriterReadyPromiseInitializeAsResolved(writer) {
33967 defaultWriterReadyPromiseInitialize(writer);
33968 defaultWriterReadyPromiseResolve(writer);
33969}
33970function defaultWriterReadyPromiseReject(writer, reason) {
33971 if (writer._readyPromise_reject === undefined) {
33972 return;
33973 }
33974 setPromiseIsHandledToTrue(writer._readyPromise);
33975 writer._readyPromise_reject(reason);
33976 writer._readyPromise_resolve = undefined;
33977 writer._readyPromise_reject = undefined;
33978 writer._readyPromiseState = 'rejected';
33979}
33980function defaultWriterReadyPromiseReset(writer) {
33981 defaultWriterReadyPromiseInitialize(writer);
33982}
33983function defaultWriterReadyPromiseResetToRejected(writer, reason) {
33984 defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
33985}
33986function defaultWriterReadyPromiseResolve(writer) {
33987 if (writer._readyPromise_resolve === undefined) {
33988 return;
33989 }
33990 writer._readyPromise_resolve(undefined);
33991 writer._readyPromise_resolve = undefined;
33992 writer._readyPromise_reject = undefined;
33993 writer._readyPromiseState = 'fulfilled';
33994}
33995
33996function isAbortSignal(value) {
33997 if (typeof value !== 'object' || value === null) {
33998 return false;
33999 }
34000 try {
34001 return typeof value.aborted === 'boolean';
34002 }
34003 catch (_a) {
34004 // AbortSignal.prototype.aborted throws if its brand check fails
34005 return false;
34006 }
34007}
34008
34009/// <reference lib="dom" />
34010const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;
34011
34012/// <reference types="node" />
34013function isDOMExceptionConstructor(ctor) {
34014 if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
34015 return false;
34016 }
34017 try {
34018 new ctor();
34019 return true;
34020 }
34021 catch (_a) {
34022 return false;
34023 }
34024}
34025function createDOMExceptionPolyfill() {
34026 // eslint-disable-next-line no-shadow
34027 const ctor = function DOMException(message, name) {
34028 this.message = message || '';
34029 this.name = name || 'Error';
34030 if (Error.captureStackTrace) {
34031 Error.captureStackTrace(this, this.constructor);
34032 }
34033 };
34034 ctor.prototype = Object.create(Error.prototype);
34035 Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
34036 return ctor;
34037}
34038// eslint-disable-next-line no-redeclare
34039const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();
34040
34041function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
34042 const reader = AcquireReadableStreamDefaultReader(source);
34043 const writer = AcquireWritableStreamDefaultWriter(dest);
34044 source._disturbed = true;
34045 let shuttingDown = false;
34046 // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.
34047 let currentWrite = promiseResolvedWith(undefined);
34048 return newPromise((resolve, reject) => {
34049 let abortAlgorithm;
34050 if (signal !== undefined) {
34051 abortAlgorithm = () => {
34052 const error = new DOMException$1('Aborted', 'AbortError');
34053 const actions = [];
34054 if (!preventAbort) {
34055 actions.push(() => {
34056 if (dest._state === 'writable') {
34057 return WritableStreamAbort(dest, error);
34058 }
34059 return promiseResolvedWith(undefined);
34060 });
34061 }
34062 if (!preventCancel) {
34063 actions.push(() => {
34064 if (source._state === 'readable') {
34065 return ReadableStreamCancel(source, error);
34066 }
34067 return promiseResolvedWith(undefined);
34068 });
34069 }
34070 shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);
34071 };
34072 if (signal.aborted) {
34073 abortAlgorithm();
34074 return;
34075 }
34076 signal.addEventListener('abort', abortAlgorithm);
34077 }
34078 // Using reader and writer, read all chunks from this and write them to dest
34079 // - Backpressure must be enforced
34080 // - Shutdown must stop all activity
34081 function pipeLoop() {
34082 return newPromise((resolveLoop, rejectLoop) => {
34083 function next(done) {
34084 if (done) {
34085 resolveLoop();
34086 }
34087 else {
34088 // Use `PerformPromiseThen` instead of `uponPromise` to avoid
34089 // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers
34090 PerformPromiseThen(pipeStep(), next, rejectLoop);
34091 }
34092 }
34093 next(false);
34094 });
34095 }
34096 function pipeStep() {
34097 if (shuttingDown) {
34098 return promiseResolvedWith(true);
34099 }
34100 return PerformPromiseThen(writer._readyPromise, () => {
34101 return newPromise((resolveRead, rejectRead) => {
34102 ReadableStreamDefaultReaderRead(reader, {
34103 _chunkSteps: chunk => {
34104 currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);
34105 resolveRead(false);
34106 },
34107 _closeSteps: () => resolveRead(true),
34108 _errorSteps: rejectRead
34109 });
34110 });
34111 });
34112 }
34113 // Errors must be propagated forward
34114 isOrBecomesErrored(source, reader._closedPromise, storedError => {
34115 if (!preventAbort) {
34116 shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
34117 }
34118 else {
34119 shutdown(true, storedError);
34120 }
34121 });
34122 // Errors must be propagated backward
34123 isOrBecomesErrored(dest, writer._closedPromise, storedError => {
34124 if (!preventCancel) {
34125 shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
34126 }
34127 else {
34128 shutdown(true, storedError);
34129 }
34130 });
34131 // Closing must be propagated forward
34132 isOrBecomesClosed(source, reader._closedPromise, () => {
34133 if (!preventClose) {
34134 shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
34135 }
34136 else {
34137 shutdown();
34138 }
34139 });
34140 // Closing must be propagated backward
34141 if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {
34142 const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');
34143 if (!preventCancel) {
34144 shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
34145 }
34146 else {
34147 shutdown(true, destClosed);
34148 }
34149 }
34150 setPromiseIsHandledToTrue(pipeLoop());
34151 function waitForWritesToFinish() {
34152 // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait
34153 // for that too.
34154 const oldCurrentWrite = currentWrite;
34155 return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);
34156 }
34157 function isOrBecomesErrored(stream, promise, action) {
34158 if (stream._state === 'errored') {
34159 action(stream._storedError);
34160 }
34161 else {
34162 uponRejection(promise, action);
34163 }
34164 }
34165 function isOrBecomesClosed(stream, promise, action) {
34166 if (stream._state === 'closed') {
34167 action();
34168 }
34169 else {
34170 uponFulfillment(promise, action);
34171 }
34172 }
34173 function shutdownWithAction(action, originalIsError, originalError) {
34174 if (shuttingDown) {
34175 return;
34176 }
34177 shuttingDown = true;
34178 if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
34179 uponFulfillment(waitForWritesToFinish(), doTheRest);
34180 }
34181 else {
34182 doTheRest();
34183 }
34184 function doTheRest() {
34185 uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
34186 }
34187 }
34188 function shutdown(isError, error) {
34189 if (shuttingDown) {
34190 return;
34191 }
34192 shuttingDown = true;
34193 if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
34194 uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));
34195 }
34196 else {
34197 finalize(isError, error);
34198 }
34199 }
34200 function finalize(isError, error) {
34201 WritableStreamDefaultWriterRelease(writer);
34202 ReadableStreamReaderGenericRelease(reader);
34203 if (signal !== undefined) {
34204 signal.removeEventListener('abort', abortAlgorithm);
34205 }
34206 if (isError) {
34207 reject(error);
34208 }
34209 else {
34210 resolve(undefined);
34211 }
34212 }
34213 });
34214}
34215
34216/**
34217 * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
34218 *
34219 * @public
34220 */
34221class ReadableStreamDefaultController {
34222 constructor() {
34223 throw new TypeError('Illegal constructor');
34224 }
34225 /**
34226 * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
34227 * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
34228 */
34229 get desiredSize() {
34230 if (!IsReadableStreamDefaultController(this)) {
34231 throw defaultControllerBrandCheckException$1('desiredSize');
34232 }
34233 return ReadableStreamDefaultControllerGetDesiredSize(this);
34234 }
34235 /**
34236 * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
34237 * the stream, but once those are read, the stream will become closed.
34238 */
34239 close() {
34240 if (!IsReadableStreamDefaultController(this)) {
34241 throw defaultControllerBrandCheckException$1('close');
34242 }
34243 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
34244 throw new TypeError('The stream is not in a state that permits close');
34245 }
34246 ReadableStreamDefaultControllerClose(this);
34247 }
34248 enqueue(chunk = undefined) {
34249 if (!IsReadableStreamDefaultController(this)) {
34250 throw defaultControllerBrandCheckException$1('enqueue');
34251 }
34252 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
34253 throw new TypeError('The stream is not in a state that permits enqueue');
34254 }
34255 return ReadableStreamDefaultControllerEnqueue(this, chunk);
34256 }
34257 /**
34258 * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
34259 */
34260 error(e = undefined) {
34261 if (!IsReadableStreamDefaultController(this)) {
34262 throw defaultControllerBrandCheckException$1('error');
34263 }
34264 ReadableStreamDefaultControllerError(this, e);
34265 }
34266 /** @internal */
34267 [CancelSteps](reason) {
34268 ResetQueue(this);
34269 const result = this._cancelAlgorithm(reason);
34270 ReadableStreamDefaultControllerClearAlgorithms(this);
34271 return result;
34272 }
34273 /** @internal */
34274 [PullSteps](readRequest) {
34275 const stream = this._controlledReadableStream;
34276 if (this._queue.length > 0) {
34277 const chunk = DequeueValue(this);
34278 if (this._closeRequested && this._queue.length === 0) {
34279 ReadableStreamDefaultControllerClearAlgorithms(this);
34280 ReadableStreamClose(stream);
34281 }
34282 else {
34283 ReadableStreamDefaultControllerCallPullIfNeeded(this);
34284 }
34285 readRequest._chunkSteps(chunk);
34286 }
34287 else {
34288 ReadableStreamAddReadRequest(stream, readRequest);
34289 ReadableStreamDefaultControllerCallPullIfNeeded(this);
34290 }
34291 }
34292}
34293Object.defineProperties(ReadableStreamDefaultController.prototype, {
34294 close: { enumerable: true },
34295 enqueue: { enumerable: true },
34296 error: { enumerable: true },
34297 desiredSize: { enumerable: true }
34298});
34299if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34300 Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
34301 value: 'ReadableStreamDefaultController',
34302 configurable: true
34303 });
34304}
34305// Abstract operations for the ReadableStreamDefaultController.
34306function IsReadableStreamDefaultController(x) {
34307 if (!typeIsObject(x)) {
34308 return false;
34309 }
34310 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {
34311 return false;
34312 }
34313 return true;
34314}
34315function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
34316 const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
34317 if (!shouldPull) {
34318 return;
34319 }
34320 if (controller._pulling) {
34321 controller._pullAgain = true;
34322 return;
34323 }
34324 controller._pulling = true;
34325 const pullPromise = controller._pullAlgorithm();
34326 uponPromise(pullPromise, () => {
34327 controller._pulling = false;
34328 if (controller._pullAgain) {
34329 controller._pullAgain = false;
34330 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
34331 }
34332 }, e => {
34333 ReadableStreamDefaultControllerError(controller, e);
34334 });
34335}
34336function ReadableStreamDefaultControllerShouldCallPull(controller) {
34337 const stream = controller._controlledReadableStream;
34338 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
34339 return false;
34340 }
34341 if (!controller._started) {
34342 return false;
34343 }
34344 if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
34345 return true;
34346 }
34347 const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
34348 if (desiredSize > 0) {
34349 return true;
34350 }
34351 return false;
34352}
34353function ReadableStreamDefaultControllerClearAlgorithms(controller) {
34354 controller._pullAlgorithm = undefined;
34355 controller._cancelAlgorithm = undefined;
34356 controller._strategySizeAlgorithm = undefined;
34357}
34358// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.
34359function ReadableStreamDefaultControllerClose(controller) {
34360 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
34361 return;
34362 }
34363 const stream = controller._controlledReadableStream;
34364 controller._closeRequested = true;
34365 if (controller._queue.length === 0) {
34366 ReadableStreamDefaultControllerClearAlgorithms(controller);
34367 ReadableStreamClose(stream);
34368 }
34369}
34370function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
34371 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
34372 return;
34373 }
34374 const stream = controller._controlledReadableStream;
34375 if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
34376 ReadableStreamFulfillReadRequest(stream, chunk, false);
34377 }
34378 else {
34379 let chunkSize;
34380 try {
34381 chunkSize = controller._strategySizeAlgorithm(chunk);
34382 }
34383 catch (chunkSizeE) {
34384 ReadableStreamDefaultControllerError(controller, chunkSizeE);
34385 throw chunkSizeE;
34386 }
34387 try {
34388 EnqueueValueWithSize(controller, chunk, chunkSize);
34389 }
34390 catch (enqueueE) {
34391 ReadableStreamDefaultControllerError(controller, enqueueE);
34392 throw enqueueE;
34393 }
34394 }
34395 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
34396}
34397function ReadableStreamDefaultControllerError(controller, e) {
34398 const stream = controller._controlledReadableStream;
34399 if (stream._state !== 'readable') {
34400 return;
34401 }
34402 ResetQueue(controller);
34403 ReadableStreamDefaultControllerClearAlgorithms(controller);
34404 ReadableStreamError(stream, e);
34405}
34406function ReadableStreamDefaultControllerGetDesiredSize(controller) {
34407 const state = controller._controlledReadableStream._state;
34408 if (state === 'errored') {
34409 return null;
34410 }
34411 if (state === 'closed') {
34412 return 0;
34413 }
34414 return controller._strategyHWM - controller._queueTotalSize;
34415}
34416// This is used in the implementation of TransformStream.
34417function ReadableStreamDefaultControllerHasBackpressure(controller) {
34418 if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
34419 return false;
34420 }
34421 return true;
34422}
34423function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
34424 const state = controller._controlledReadableStream._state;
34425 if (!controller._closeRequested && state === 'readable') {
34426 return true;
34427 }
34428 return false;
34429}
34430function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
34431 controller._controlledReadableStream = stream;
34432 controller._queue = undefined;
34433 controller._queueTotalSize = undefined;
34434 ResetQueue(controller);
34435 controller._started = false;
34436 controller._closeRequested = false;
34437 controller._pullAgain = false;
34438 controller._pulling = false;
34439 controller._strategySizeAlgorithm = sizeAlgorithm;
34440 controller._strategyHWM = highWaterMark;
34441 controller._pullAlgorithm = pullAlgorithm;
34442 controller._cancelAlgorithm = cancelAlgorithm;
34443 stream._readableStreamController = controller;
34444 const startResult = startAlgorithm();
34445 uponPromise(promiseResolvedWith(startResult), () => {
34446 controller._started = true;
34447 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
34448 }, r => {
34449 ReadableStreamDefaultControllerError(controller, r);
34450 });
34451}
34452function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
34453 const controller = Object.create(ReadableStreamDefaultController.prototype);
34454 let startAlgorithm = () => undefined;
34455 let pullAlgorithm = () => promiseResolvedWith(undefined);
34456 let cancelAlgorithm = () => promiseResolvedWith(undefined);
34457 if (underlyingSource.start !== undefined) {
34458 startAlgorithm = () => underlyingSource.start(controller);
34459 }
34460 if (underlyingSource.pull !== undefined) {
34461 pullAlgorithm = () => underlyingSource.pull(controller);
34462 }
34463 if (underlyingSource.cancel !== undefined) {
34464 cancelAlgorithm = reason => underlyingSource.cancel(reason);
34465 }
34466 SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
34467}
34468// Helper functions for the ReadableStreamDefaultController.
34469function defaultControllerBrandCheckException$1(name) {
34470 return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
34471}
34472
34473function ReadableStreamTee(stream, cloneForBranch2) {
34474 const reader = AcquireReadableStreamDefaultReader(stream);
34475 let reading = false;
34476 let canceled1 = false;
34477 let canceled2 = false;
34478 let reason1;
34479 let reason2;
34480 let branch1;
34481 let branch2;
34482 let resolveCancelPromise;
34483 const cancelPromise = newPromise(resolve => {
34484 resolveCancelPromise = resolve;
34485 });
34486 function pullAlgorithm() {
34487 if (reading) {
34488 return promiseResolvedWith(undefined);
34489 }
34490 reading = true;
34491 const readRequest = {
34492 _chunkSteps: value => {
34493 // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
34494 // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
34495 // successful synchronously-available reads get ahead of asynchronously-available errors.
34496 queueMicrotask(() => {
34497 reading = false;
34498 const value1 = value;
34499 const value2 = value;
34500 // There is no way to access the cloning code right now in the reference implementation.
34501 // If we add one then we'll need an implementation for serializable objects.
34502 // if (!canceled2 && cloneForBranch2) {
34503 // value2 = StructuredDeserialize(StructuredSerialize(value2));
34504 // }
34505 if (!canceled1) {
34506 ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1);
34507 }
34508 if (!canceled2) {
34509 ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2);
34510 }
34511 });
34512 },
34513 _closeSteps: () => {
34514 reading = false;
34515 if (!canceled1) {
34516 ReadableStreamDefaultControllerClose(branch1._readableStreamController);
34517 }
34518 if (!canceled2) {
34519 ReadableStreamDefaultControllerClose(branch2._readableStreamController);
34520 }
34521 if (!canceled1 || !canceled2) {
34522 resolveCancelPromise(undefined);
34523 }
34524 },
34525 _errorSteps: () => {
34526 reading = false;
34527 }
34528 };
34529 ReadableStreamDefaultReaderRead(reader, readRequest);
34530 return promiseResolvedWith(undefined);
34531 }
34532 function cancel1Algorithm(reason) {
34533 canceled1 = true;
34534 reason1 = reason;
34535 if (canceled2) {
34536 const compositeReason = CreateArrayFromList([reason1, reason2]);
34537 const cancelResult = ReadableStreamCancel(stream, compositeReason);
34538 resolveCancelPromise(cancelResult);
34539 }
34540 return cancelPromise;
34541 }
34542 function cancel2Algorithm(reason) {
34543 canceled2 = true;
34544 reason2 = reason;
34545 if (canceled1) {
34546 const compositeReason = CreateArrayFromList([reason1, reason2]);
34547 const cancelResult = ReadableStreamCancel(stream, compositeReason);
34548 resolveCancelPromise(cancelResult);
34549 }
34550 return cancelPromise;
34551 }
34552 function startAlgorithm() {
34553 // do nothing
34554 }
34555 branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
34556 branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
34557 uponRejection(reader._closedPromise, (r) => {
34558 ReadableStreamDefaultControllerError(branch1._readableStreamController, r);
34559 ReadableStreamDefaultControllerError(branch2._readableStreamController, r);
34560 if (!canceled1 || !canceled2) {
34561 resolveCancelPromise(undefined);
34562 }
34563 });
34564 return [branch1, branch2];
34565}
34566
34567function convertUnderlyingDefaultOrByteSource(source, context) {
34568 assertDictionary(source, context);
34569 const original = source;
34570 const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
34571 const cancel = original === null || original === void 0 ? void 0 : original.cancel;
34572 const pull = original === null || original === void 0 ? void 0 : original.pull;
34573 const start = original === null || original === void 0 ? void 0 : original.start;
34574 const type = original === null || original === void 0 ? void 0 : original.type;
34575 return {
34576 autoAllocateChunkSize: autoAllocateChunkSize === undefined ?
34577 undefined :
34578 convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),
34579 cancel: cancel === undefined ?
34580 undefined :
34581 convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),
34582 pull: pull === undefined ?
34583 undefined :
34584 convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),
34585 start: start === undefined ?
34586 undefined :
34587 convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),
34588 type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)
34589 };
34590}
34591function convertUnderlyingSourceCancelCallback(fn, original, context) {
34592 assertFunction(fn, context);
34593 return (reason) => promiseCall(fn, original, [reason]);
34594}
34595function convertUnderlyingSourcePullCallback(fn, original, context) {
34596 assertFunction(fn, context);
34597 return (controller) => promiseCall(fn, original, [controller]);
34598}
34599function convertUnderlyingSourceStartCallback(fn, original, context) {
34600 assertFunction(fn, context);
34601 return (controller) => reflectCall(fn, original, [controller]);
34602}
34603function convertReadableStreamType(type, context) {
34604 type = `${type}`;
34605 if (type !== 'bytes') {
34606 throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);
34607 }
34608 return type;
34609}
34610
34611function convertReaderOptions(options, context) {
34612 assertDictionary(options, context);
34613 const mode = options === null || options === void 0 ? void 0 : options.mode;
34614 return {
34615 mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
34616 };
34617}
34618function convertReadableStreamReaderMode(mode, context) {
34619 mode = `${mode}`;
34620 if (mode !== 'byob') {
34621 throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
34622 }
34623 return mode;
34624}
34625
34626function convertIteratorOptions(options, context) {
34627 assertDictionary(options, context);
34628 const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
34629 return { preventCancel: Boolean(preventCancel) };
34630}
34631
34632function convertPipeOptions(options, context) {
34633 assertDictionary(options, context);
34634 const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;
34635 const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
34636 const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;
34637 const signal = options === null || options === void 0 ? void 0 : options.signal;
34638 if (signal !== undefined) {
34639 assertAbortSignal(signal, `${context} has member 'signal' that`);
34640 }
34641 return {
34642 preventAbort: Boolean(preventAbort),
34643 preventCancel: Boolean(preventCancel),
34644 preventClose: Boolean(preventClose),
34645 signal
34646 };
34647}
34648function assertAbortSignal(signal, context) {
34649 if (!isAbortSignal(signal)) {
34650 throw new TypeError(`${context} is not an AbortSignal.`);
34651 }
34652}
34653
34654function convertReadableWritablePair(pair, context) {
34655 assertDictionary(pair, context);
34656 const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
34657 assertRequiredField(readable, 'readable', 'ReadableWritablePair');
34658 assertReadableStream(readable, `${context} has member 'readable' that`);
34659 const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
34660 assertRequiredField(writable, 'writable', 'ReadableWritablePair');
34661 assertWritableStream(writable, `${context} has member 'writable' that`);
34662 return { readable, writable };
34663}
34664
34665/**
34666 * A readable stream represents a source of data, from which you can read.
34667 *
34668 * @public
34669 */
34670class ReadableStream$1 {
34671 constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
34672 if (rawUnderlyingSource === undefined) {
34673 rawUnderlyingSource = null;
34674 }
34675 else {
34676 assertObject(rawUnderlyingSource, 'First parameter');
34677 }
34678 const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
34679 const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');
34680 InitializeReadableStream(this);
34681 if (underlyingSource.type === 'bytes') {
34682 if (strategy.size !== undefined) {
34683 throw new RangeError('The strategy for a byte stream cannot have a size function');
34684 }
34685 const highWaterMark = ExtractHighWaterMark(strategy, 0);
34686 SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
34687 }
34688 else {
34689 const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
34690 const highWaterMark = ExtractHighWaterMark(strategy, 1);
34691 SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
34692 }
34693 }
34694 /**
34695 * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
34696 */
34697 get locked() {
34698 if (!IsReadableStream(this)) {
34699 throw streamBrandCheckException$1('locked');
34700 }
34701 return IsReadableStreamLocked(this);
34702 }
34703 /**
34704 * Cancels the stream, signaling a loss of interest in the stream by a consumer.
34705 *
34706 * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
34707 * method, which might or might not use it.
34708 */
34709 cancel(reason = undefined) {
34710 if (!IsReadableStream(this)) {
34711 return promiseRejectedWith(streamBrandCheckException$1('cancel'));
34712 }
34713 if (IsReadableStreamLocked(this)) {
34714 return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));
34715 }
34716 return ReadableStreamCancel(this, reason);
34717 }
34718 getReader(rawOptions = undefined) {
34719 if (!IsReadableStream(this)) {
34720 throw streamBrandCheckException$1('getReader');
34721 }
34722 const options = convertReaderOptions(rawOptions, 'First parameter');
34723 if (options.mode === undefined) {
34724 return AcquireReadableStreamDefaultReader(this);
34725 }
34726 return AcquireReadableStreamBYOBReader(this);
34727 }
34728 pipeThrough(rawTransform, rawOptions = {}) {
34729 if (!IsReadableStream(this)) {
34730 throw streamBrandCheckException$1('pipeThrough');
34731 }
34732 assertRequiredArgument(rawTransform, 1, 'pipeThrough');
34733 const transform = convertReadableWritablePair(rawTransform, 'First parameter');
34734 const options = convertPipeOptions(rawOptions, 'Second parameter');
34735 if (IsReadableStreamLocked(this)) {
34736 throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');
34737 }
34738 if (IsWritableStreamLocked(transform.writable)) {
34739 throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');
34740 }
34741 const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
34742 setPromiseIsHandledToTrue(promise);
34743 return transform.readable;
34744 }
34745 pipeTo(destination, rawOptions = {}) {
34746 if (!IsReadableStream(this)) {
34747 return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));
34748 }
34749 if (destination === undefined) {
34750 return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
34751 }
34752 if (!IsWritableStream(destination)) {
34753 return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
34754 }
34755 let options;
34756 try {
34757 options = convertPipeOptions(rawOptions, 'Second parameter');
34758 }
34759 catch (e) {
34760 return promiseRejectedWith(e);
34761 }
34762 if (IsReadableStreamLocked(this)) {
34763 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));
34764 }
34765 if (IsWritableStreamLocked(destination)) {
34766 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));
34767 }
34768 return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
34769 }
34770 /**
34771 * Tees this readable stream, returning a two-element array containing the two resulting branches as
34772 * new {@link ReadableStream} instances.
34773 *
34774 * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
34775 * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
34776 * propagated to the stream's underlying source.
34777 *
34778 * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
34779 * this could allow interference between the two branches.
34780 */
34781 tee() {
34782 if (!IsReadableStream(this)) {
34783 throw streamBrandCheckException$1('tee');
34784 }
34785 const branches = ReadableStreamTee(this);
34786 return CreateArrayFromList(branches);
34787 }
34788 values(rawOptions = undefined) {
34789 if (!IsReadableStream(this)) {
34790 throw streamBrandCheckException$1('values');
34791 }
34792 const options = convertIteratorOptions(rawOptions, 'First parameter');
34793 return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
34794 }
34795}
34796Object.defineProperties(ReadableStream$1.prototype, {
34797 cancel: { enumerable: true },
34798 getReader: { enumerable: true },
34799 pipeThrough: { enumerable: true },
34800 pipeTo: { enumerable: true },
34801 tee: { enumerable: true },
34802 values: { enumerable: true },
34803 locked: { enumerable: true }
34804});
34805if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34806 Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.toStringTag, {
34807 value: 'ReadableStream',
34808 configurable: true
34809 });
34810}
34811if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
34812 Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.asyncIterator, {
34813 value: ReadableStream$1.prototype.values,
34814 writable: true,
34815 configurable: true
34816 });
34817}
34818// Abstract operations for the ReadableStream.
34819// Throws if and only if startAlgorithm throws.
34820function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
34821 const stream = Object.create(ReadableStream$1.prototype);
34822 InitializeReadableStream(stream);
34823 const controller = Object.create(ReadableStreamDefaultController.prototype);
34824 SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
34825 return stream;
34826}
34827function InitializeReadableStream(stream) {
34828 stream._state = 'readable';
34829 stream._reader = undefined;
34830 stream._storedError = undefined;
34831 stream._disturbed = false;
34832}
34833function IsReadableStream(x) {
34834 if (!typeIsObject(x)) {
34835 return false;
34836 }
34837 if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {
34838 return false;
34839 }
34840 return true;
34841}
34842function IsReadableStreamLocked(stream) {
34843 if (stream._reader === undefined) {
34844 return false;
34845 }
34846 return true;
34847}
34848// ReadableStream API exposed for controllers.
34849function ReadableStreamCancel(stream, reason) {
34850 stream._disturbed = true;
34851 if (stream._state === 'closed') {
34852 return promiseResolvedWith(undefined);
34853 }
34854 if (stream._state === 'errored') {
34855 return promiseRejectedWith(stream._storedError);
34856 }
34857 ReadableStreamClose(stream);
34858 const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
34859 return transformPromiseWith(sourceCancelPromise, noop);
34860}
34861function ReadableStreamClose(stream) {
34862 stream._state = 'closed';
34863 const reader = stream._reader;
34864 if (reader === undefined) {
34865 return;
34866 }
34867 defaultReaderClosedPromiseResolve(reader);
34868 if (IsReadableStreamDefaultReader(reader)) {
34869 reader._readRequests.forEach(readRequest => {
34870 readRequest._closeSteps();
34871 });
34872 reader._readRequests = new SimpleQueue();
34873 }
34874}
34875function ReadableStreamError(stream, e) {
34876 stream._state = 'errored';
34877 stream._storedError = e;
34878 const reader = stream._reader;
34879 if (reader === undefined) {
34880 return;
34881 }
34882 defaultReaderClosedPromiseReject(reader, e);
34883 if (IsReadableStreamDefaultReader(reader)) {
34884 reader._readRequests.forEach(readRequest => {
34885 readRequest._errorSteps(e);
34886 });
34887 reader._readRequests = new SimpleQueue();
34888 }
34889 else {
34890 reader._readIntoRequests.forEach(readIntoRequest => {
34891 readIntoRequest._errorSteps(e);
34892 });
34893 reader._readIntoRequests = new SimpleQueue();
34894 }
34895}
34896// Helper functions for the ReadableStream.
34897function streamBrandCheckException$1(name) {
34898 return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
34899}
34900
34901function convertQueuingStrategyInit(init, context) {
34902 assertDictionary(init, context);
34903 const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
34904 assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');
34905 return {
34906 highWaterMark: convertUnrestrictedDouble(highWaterMark)
34907 };
34908}
34909
34910const byteLengthSizeFunction = function size(chunk) {
34911 return chunk.byteLength;
34912};
34913/**
34914 * A queuing strategy that counts the number of bytes in each chunk.
34915 *
34916 * @public
34917 */
34918class ByteLengthQueuingStrategy {
34919 constructor(options) {
34920 assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');
34921 options = convertQueuingStrategyInit(options, 'First parameter');
34922 this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;
34923 }
34924 /**
34925 * Returns the high water mark provided to the constructor.
34926 */
34927 get highWaterMark() {
34928 if (!IsByteLengthQueuingStrategy(this)) {
34929 throw byteLengthBrandCheckException('highWaterMark');
34930 }
34931 return this._byteLengthQueuingStrategyHighWaterMark;
34932 }
34933 /**
34934 * Measures the size of `chunk` by returning the value of its `byteLength` property.
34935 */
34936 get size() {
34937 if (!IsByteLengthQueuingStrategy(this)) {
34938 throw byteLengthBrandCheckException('size');
34939 }
34940 return byteLengthSizeFunction;
34941 }
34942}
34943Object.defineProperties(ByteLengthQueuingStrategy.prototype, {
34944 highWaterMark: { enumerable: true },
34945 size: { enumerable: true }
34946});
34947if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34948 Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
34949 value: 'ByteLengthQueuingStrategy',
34950 configurable: true
34951 });
34952}
34953// Helper functions for the ByteLengthQueuingStrategy.
34954function byteLengthBrandCheckException(name) {
34955 return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
34956}
34957function IsByteLengthQueuingStrategy(x) {
34958 if (!typeIsObject(x)) {
34959 return false;
34960 }
34961 if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {
34962 return false;
34963 }
34964 return true;
34965}
34966
34967const countSizeFunction = function size() {
34968 return 1;
34969};
34970/**
34971 * A queuing strategy that counts the number of chunks.
34972 *
34973 * @public
34974 */
34975class CountQueuingStrategy {
34976 constructor(options) {
34977 assertRequiredArgument(options, 1, 'CountQueuingStrategy');
34978 options = convertQueuingStrategyInit(options, 'First parameter');
34979 this._countQueuingStrategyHighWaterMark = options.highWaterMark;
34980 }
34981 /**
34982 * Returns the high water mark provided to the constructor.
34983 */
34984 get highWaterMark() {
34985 if (!IsCountQueuingStrategy(this)) {
34986 throw countBrandCheckException('highWaterMark');
34987 }
34988 return this._countQueuingStrategyHighWaterMark;
34989 }
34990 /**
34991 * Measures the size of `chunk` by always returning 1.
34992 * This ensures that the total queue size is a count of the number of chunks in the queue.
34993 */
34994 get size() {
34995 if (!IsCountQueuingStrategy(this)) {
34996 throw countBrandCheckException('size');
34997 }
34998 return countSizeFunction;
34999 }
35000}
35001Object.defineProperties(CountQueuingStrategy.prototype, {
35002 highWaterMark: { enumerable: true },
35003 size: { enumerable: true }
35004});
35005if (typeof SymbolPolyfill.toStringTag === 'symbol') {
35006 Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
35007 value: 'CountQueuingStrategy',
35008 configurable: true
35009 });
35010}
35011// Helper functions for the CountQueuingStrategy.
35012function countBrandCheckException(name) {
35013 return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
35014}
35015function IsCountQueuingStrategy(x) {
35016 if (!typeIsObject(x)) {
35017 return false;
35018 }
35019 if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {
35020 return false;
35021 }
35022 return true;
35023}
35024
35025function convertTransformer(original, context) {
35026 assertDictionary(original, context);
35027 const flush = original === null || original === void 0 ? void 0 : original.flush;
35028 const readableType = original === null || original === void 0 ? void 0 : original.readableType;
35029 const start = original === null || original === void 0 ? void 0 : original.start;
35030 const transform = original === null || original === void 0 ? void 0 : original.transform;
35031 const writableType = original === null || original === void 0 ? void 0 : original.writableType;
35032 return {
35033 flush: flush === undefined ?
35034 undefined :
35035 convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
35036 readableType,
35037 start: start === undefined ?
35038 undefined :
35039 convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
35040 transform: transform === undefined ?
35041 undefined :
35042 convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),
35043 writableType
35044 };
35045}
35046function convertTransformerFlushCallback(fn, original, context) {
35047 assertFunction(fn, context);
35048 return (controller) => promiseCall(fn, original, [controller]);
35049}
35050function convertTransformerStartCallback(fn, original, context) {
35051 assertFunction(fn, context);
35052 return (controller) => reflectCall(fn, original, [controller]);
35053}
35054function convertTransformerTransformCallback(fn, original, context) {
35055 assertFunction(fn, context);
35056 return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
35057}
35058
35059// Class TransformStream
35060/**
35061 * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
35062 * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
35063 * In a manner specific to the transform stream in question, writes to the writable side result in new data being
35064 * made available for reading from the readable side.
35065 *
35066 * @public
35067 */
35068class TransformStream$1 {
35069 constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
35070 if (rawTransformer === undefined) {
35071 rawTransformer = null;
35072 }
35073 const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');
35074 const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');
35075 const transformer = convertTransformer(rawTransformer, 'First parameter');
35076 if (transformer.readableType !== undefined) {
35077 throw new RangeError('Invalid readableType specified');
35078 }
35079 if (transformer.writableType !== undefined) {
35080 throw new RangeError('Invalid writableType specified');
35081 }
35082 const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
35083 const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
35084 const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
35085 const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
35086 let startPromise_resolve;
35087 const startPromise = newPromise(resolve => {
35088 startPromise_resolve = resolve;
35089 });
35090 InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
35091 SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
35092 if (transformer.start !== undefined) {
35093 startPromise_resolve(transformer.start(this._transformStreamController));
35094 }
35095 else {
35096 startPromise_resolve(undefined);
35097 }
35098 }
35099 /**
35100 * The readable side of the transform stream.
35101 */
35102 get readable() {
35103 if (!IsTransformStream(this)) {
35104 throw streamBrandCheckException('readable');
35105 }
35106 return this._readable;
35107 }
35108 /**
35109 * The writable side of the transform stream.
35110 */
35111 get writable() {
35112 if (!IsTransformStream(this)) {
35113 throw streamBrandCheckException('writable');
35114 }
35115 return this._writable;
35116 }
35117}
35118Object.defineProperties(TransformStream$1.prototype, {
35119 readable: { enumerable: true },
35120 writable: { enumerable: true }
35121});
35122if (typeof SymbolPolyfill.toStringTag === 'symbol') {
35123 Object.defineProperty(TransformStream$1.prototype, SymbolPolyfill.toStringTag, {
35124 value: 'TransformStream',
35125 configurable: true
35126 });
35127}
35128function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
35129 function startAlgorithm() {
35130 return startPromise;
35131 }
35132 function writeAlgorithm(chunk) {
35133 return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
35134 }
35135 function abortAlgorithm(reason) {
35136 return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
35137 }
35138 function closeAlgorithm() {
35139 return TransformStreamDefaultSinkCloseAlgorithm(stream);
35140 }
35141 stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
35142 function pullAlgorithm() {
35143 return TransformStreamDefaultSourcePullAlgorithm(stream);
35144 }
35145 function cancelAlgorithm(reason) {
35146 TransformStreamErrorWritableAndUnblockWrite(stream, reason);
35147 return promiseResolvedWith(undefined);
35148 }
35149 stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
35150 // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
35151 stream._backpressure = undefined;
35152 stream._backpressureChangePromise = undefined;
35153 stream._backpressureChangePromise_resolve = undefined;
35154 TransformStreamSetBackpressure(stream, true);
35155 stream._transformStreamController = undefined;
35156}
35157function IsTransformStream(x) {
35158 if (!typeIsObject(x)) {
35159 return false;
35160 }
35161 if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {
35162 return false;
35163 }
35164 return true;
35165}
35166// This is a no-op if both sides are already errored.
35167function TransformStreamError(stream, e) {
35168 ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);
35169 TransformStreamErrorWritableAndUnblockWrite(stream, e);
35170}
35171function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
35172 TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
35173 WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
35174 if (stream._backpressure) {
35175 // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
35176 // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
35177 // _backpressure is set.
35178 TransformStreamSetBackpressure(stream, false);
35179 }
35180}
35181function TransformStreamSetBackpressure(stream, backpressure) {
35182 // Passes also when called during construction.
35183 if (stream._backpressureChangePromise !== undefined) {
35184 stream._backpressureChangePromise_resolve();
35185 }
35186 stream._backpressureChangePromise = newPromise(resolve => {
35187 stream._backpressureChangePromise_resolve = resolve;
35188 });
35189 stream._backpressure = backpressure;
35190}
35191// Class TransformStreamDefaultController
35192/**
35193 * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
35194 *
35195 * @public
35196 */
35197class TransformStreamDefaultController {
35198 constructor() {
35199 throw new TypeError('Illegal constructor');
35200 }
35201 /**
35202 * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
35203 */
35204 get desiredSize() {
35205 if (!IsTransformStreamDefaultController(this)) {
35206 throw defaultControllerBrandCheckException('desiredSize');
35207 }
35208 const readableController = this._controlledTransformStream._readable._readableStreamController;
35209 return ReadableStreamDefaultControllerGetDesiredSize(readableController);
35210 }
35211 enqueue(chunk = undefined) {
35212 if (!IsTransformStreamDefaultController(this)) {
35213 throw defaultControllerBrandCheckException('enqueue');
35214 }
35215 TransformStreamDefaultControllerEnqueue(this, chunk);
35216 }
35217 /**
35218 * Errors both the readable side and the writable side of the controlled transform stream, making all future
35219 * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
35220 */
35221 error(reason = undefined) {
35222 if (!IsTransformStreamDefaultController(this)) {
35223 throw defaultControllerBrandCheckException('error');
35224 }
35225 TransformStreamDefaultControllerError(this, reason);
35226 }
35227 /**
35228 * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
35229 * transformer only needs to consume a portion of the chunks written to the writable side.
35230 */
35231 terminate() {
35232 if (!IsTransformStreamDefaultController(this)) {
35233 throw defaultControllerBrandCheckException('terminate');
35234 }
35235 TransformStreamDefaultControllerTerminate(this);
35236 }
35237}
35238Object.defineProperties(TransformStreamDefaultController.prototype, {
35239 enqueue: { enumerable: true },
35240 error: { enumerable: true },
35241 terminate: { enumerable: true },
35242 desiredSize: { enumerable: true }
35243});
35244if (typeof SymbolPolyfill.toStringTag === 'symbol') {
35245 Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
35246 value: 'TransformStreamDefaultController',
35247 configurable: true
35248 });
35249}
35250// Transform Stream Default Controller Abstract Operations
35251function IsTransformStreamDefaultController(x) {
35252 if (!typeIsObject(x)) {
35253 return false;
35254 }
35255 if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {
35256 return false;
35257 }
35258 return true;
35259}
35260function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {
35261 controller._controlledTransformStream = stream;
35262 stream._transformStreamController = controller;
35263 controller._transformAlgorithm = transformAlgorithm;
35264 controller._flushAlgorithm = flushAlgorithm;
35265}
35266function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
35267 const controller = Object.create(TransformStreamDefaultController.prototype);
35268 let transformAlgorithm = (chunk) => {
35269 try {
35270 TransformStreamDefaultControllerEnqueue(controller, chunk);
35271 return promiseResolvedWith(undefined);
35272 }
35273 catch (transformResultE) {
35274 return promiseRejectedWith(transformResultE);
35275 }
35276 };
35277 let flushAlgorithm = () => promiseResolvedWith(undefined);
35278 if (transformer.transform !== undefined) {
35279 transformAlgorithm = chunk => transformer.transform(chunk, controller);
35280 }
35281 if (transformer.flush !== undefined) {
35282 flushAlgorithm = () => transformer.flush(controller);
35283 }
35284 SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);
35285}
35286function TransformStreamDefaultControllerClearAlgorithms(controller) {
35287 controller._transformAlgorithm = undefined;
35288 controller._flushAlgorithm = undefined;
35289}
35290function TransformStreamDefaultControllerEnqueue(controller, chunk) {
35291 const stream = controller._controlledTransformStream;
35292 const readableController = stream._readable._readableStreamController;
35293 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
35294 throw new TypeError('Readable side is not in a state that permits enqueue');
35295 }
35296 // We throttle transform invocations based on the backpressure of the ReadableStream, but we still
35297 // accept TransformStreamDefaultControllerEnqueue() calls.
35298 try {
35299 ReadableStreamDefaultControllerEnqueue(readableController, chunk);
35300 }
35301 catch (e) {
35302 // This happens when readableStrategy.size() throws.
35303 TransformStreamErrorWritableAndUnblockWrite(stream, e);
35304 throw stream._readable._storedError;
35305 }
35306 const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
35307 if (backpressure !== stream._backpressure) {
35308 TransformStreamSetBackpressure(stream, true);
35309 }
35310}
35311function TransformStreamDefaultControllerError(controller, e) {
35312 TransformStreamError(controller._controlledTransformStream, e);
35313}
35314function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
35315 const transformPromise = controller._transformAlgorithm(chunk);
35316 return transformPromiseWith(transformPromise, undefined, r => {
35317 TransformStreamError(controller._controlledTransformStream, r);
35318 throw r;
35319 });
35320}
35321function TransformStreamDefaultControllerTerminate(controller) {
35322 const stream = controller._controlledTransformStream;
35323 const readableController = stream._readable._readableStreamController;
35324 ReadableStreamDefaultControllerClose(readableController);
35325 const error = new TypeError('TransformStream terminated');
35326 TransformStreamErrorWritableAndUnblockWrite(stream, error);
35327}
35328// TransformStreamDefaultSink Algorithms
35329function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
35330 const controller = stream._transformStreamController;
35331 if (stream._backpressure) {
35332 const backpressureChangePromise = stream._backpressureChangePromise;
35333 return transformPromiseWith(backpressureChangePromise, () => {
35334 const writable = stream._writable;
35335 const state = writable._state;
35336 if (state === 'erroring') {
35337 throw writable._storedError;
35338 }
35339 return TransformStreamDefaultControllerPerformTransform(controller, chunk);
35340 });
35341 }
35342 return TransformStreamDefaultControllerPerformTransform(controller, chunk);
35343}
35344function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
35345 // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already
35346 // errored.
35347 TransformStreamError(stream, reason);
35348 return promiseResolvedWith(undefined);
35349}
35350function TransformStreamDefaultSinkCloseAlgorithm(stream) {
35351 // stream._readable cannot change after construction, so caching it across a call to user code is safe.
35352 const readable = stream._readable;
35353 const controller = stream._transformStreamController;
35354 const flushPromise = controller._flushAlgorithm();
35355 TransformStreamDefaultControllerClearAlgorithms(controller);
35356 // Return a promise that is fulfilled with undefined on success.
35357 return transformPromiseWith(flushPromise, () => {
35358 if (readable._state === 'errored') {
35359 throw readable._storedError;
35360 }
35361 ReadableStreamDefaultControllerClose(readable._readableStreamController);
35362 }, r => {
35363 TransformStreamError(stream, r);
35364 throw readable._storedError;
35365 });
35366}
35367// TransformStreamDefaultSource Algorithms
35368function TransformStreamDefaultSourcePullAlgorithm(stream) {
35369 // Invariant. Enforced by the promises returned by start() and pull().
35370 TransformStreamSetBackpressure(stream, false);
35371 // Prevent the next pull() call until there is backpressure.
35372 return stream._backpressureChangePromise;
35373}
35374// Helper functions for the TransformStreamDefaultController.
35375function defaultControllerBrandCheckException(name) {
35376 return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
35377}
35378// Helper functions for the TransformStream.
35379function streamBrandCheckException(name) {
35380 return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
35381}
35382
35383var ponyfill_es6 = /*#__PURE__*/Object.freeze({
35384 __proto__: null,
35385 ByteLengthQueuingStrategy: ByteLengthQueuingStrategy,
35386 CountQueuingStrategy: CountQueuingStrategy,
35387 ReadableByteStreamController: ReadableByteStreamController,
35388 ReadableStream: ReadableStream$1,
35389 ReadableStreamBYOBReader: ReadableStreamBYOBReader,
35390 ReadableStreamBYOBRequest: ReadableStreamBYOBRequest,
35391 ReadableStreamDefaultController: ReadableStreamDefaultController,
35392 ReadableStreamDefaultReader: ReadableStreamDefaultReader,
35393 TransformStream: TransformStream$1,
35394 TransformStreamDefaultController: TransformStreamDefaultController,
35395 WritableStream: WritableStream$1,
35396 WritableStreamDefaultController: WritableStreamDefaultController,
35397 WritableStreamDefaultWriter: WritableStreamDefaultWriter
35398});
35399
35400/*! *****************************************************************************
35401Copyright (c) Microsoft Corporation.
35402
35403Permission to use, copy, modify, and/or distribute this software for any
35404purpose with or without fee is hereby granted.
35405
35406THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
35407REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
35408AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
35409INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
35410LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
35411OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
35412PERFORMANCE OF THIS SOFTWARE.
35413***************************************************************************** */
35414/* global Reflect, Promise */
35415
35416var extendStatics = function(d, b) {
35417 extendStatics = Object.setPrototypeOf ||
35418 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35419 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
35420 return extendStatics(d, b);
35421};
35422
35423function __extends(d, b) {
35424 if (typeof b !== "function" && b !== null)
35425 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
35426 extendStatics(d, b);
35427 function __() { this.constructor = d; }
35428 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35429}
35430
35431function assert$1(test) {
35432 if (!test) {
35433 throw new TypeError('Assertion failed');
35434 }
35435}
35436
35437function noop$1() {
35438 return;
35439}
35440function typeIsObject$1(x) {
35441 return (typeof x === 'object' && x !== null) || typeof x === 'function';
35442}
35443
35444function isStreamConstructor(ctor) {
35445 if (typeof ctor !== 'function') {
35446 return false;
35447 }
35448 var startCalled = false;
35449 try {
35450 new ctor({
35451 start: function () {
35452 startCalled = true;
35453 }
35454 });
35455 }
35456 catch (e) {
35457 // ignore
35458 }
35459 return startCalled;
35460}
35461function isReadableStream(readable) {
35462 if (!typeIsObject$1(readable)) {
35463 return false;
35464 }
35465 if (typeof readable.getReader !== 'function') {
35466 return false;
35467 }
35468 return true;
35469}
35470function isReadableStreamConstructor(ctor) {
35471 if (!isStreamConstructor(ctor)) {
35472 return false;
35473 }
35474 if (!isReadableStream(new ctor())) {
35475 return false;
35476 }
35477 return true;
35478}
35479function isWritableStream(writable) {
35480 if (!typeIsObject$1(writable)) {
35481 return false;
35482 }
35483 if (typeof writable.getWriter !== 'function') {
35484 return false;
35485 }
35486 return true;
35487}
35488function isWritableStreamConstructor(ctor) {
35489 if (!isStreamConstructor(ctor)) {
35490 return false;
35491 }
35492 if (!isWritableStream(new ctor())) {
35493 return false;
35494 }
35495 return true;
35496}
35497function isTransformStream(transform) {
35498 if (!typeIsObject$1(transform)) {
35499 return false;
35500 }
35501 if (!isReadableStream(transform.readable)) {
35502 return false;
35503 }
35504 if (!isWritableStream(transform.writable)) {
35505 return false;
35506 }
35507 return true;
35508}
35509function isTransformStreamConstructor(ctor) {
35510 if (!isStreamConstructor(ctor)) {
35511 return false;
35512 }
35513 if (!isTransformStream(new ctor())) {
35514 return false;
35515 }
35516 return true;
35517}
35518function supportsByobReader(readable) {
35519 try {
35520 var reader = readable.getReader({ mode: 'byob' });
35521 reader.releaseLock();
35522 return true;
35523 }
35524 catch (_a) {
35525 return false;
35526 }
35527}
35528function supportsByteSource(ctor) {
35529 try {
35530 new ctor({ type: 'bytes' });
35531 return true;
35532 }
35533 catch (_a) {
35534 return false;
35535 }
35536}
35537
35538function createReadableStreamWrapper(ctor) {
35539 assert$1(isReadableStreamConstructor(ctor));
35540 var byteSourceSupported = supportsByteSource(ctor);
35541 return function (readable, _a) {
35542 var _b = _a === void 0 ? {} : _a, type = _b.type;
35543 type = parseReadableType(type);
35544 if (type === 'bytes' && !byteSourceSupported) {
35545 type = undefined;
35546 }
35547 if (readable.constructor === ctor) {
35548 if (type !== 'bytes' || supportsByobReader(readable)) {
35549 return readable;
35550 }
35551 }
35552 if (type === 'bytes') {
35553 var source = createWrappingReadableSource(readable, { type: type });
35554 return new ctor(source);
35555 }
35556 else {
35557 var source = createWrappingReadableSource(readable);
35558 return new ctor(source);
35559 }
35560 };
35561}
35562function createWrappingReadableSource(readable, _a) {
35563 var _b = _a === void 0 ? {} : _a, type = _b.type;
35564 assert$1(isReadableStream(readable));
35565 assert$1(readable.locked === false);
35566 type = parseReadableType(type);
35567 var source;
35568 if (type === 'bytes') {
35569 source = new WrappingReadableByteStreamSource(readable);
35570 }
35571 else {
35572 source = new WrappingReadableStreamDefaultSource(readable);
35573 }
35574 return source;
35575}
35576function parseReadableType(type) {
35577 var typeString = String(type);
35578 if (typeString === 'bytes') {
35579 return typeString;
35580 }
35581 else if (type === undefined) {
35582 return type;
35583 }
35584 else {
35585 throw new RangeError('Invalid type is specified');
35586 }
35587}
35588var AbstractWrappingReadableStreamSource = /** @class */ (function () {
35589 function AbstractWrappingReadableStreamSource(underlyingStream) {
35590 this._underlyingReader = undefined;
35591 this._readerMode = undefined;
35592 this._readableStreamController = undefined;
35593 this._pendingRead = undefined;
35594 this._underlyingStream = underlyingStream;
35595 // always keep a reader attached to detect close/error
35596 this._attachDefaultReader();
35597 }
35598 AbstractWrappingReadableStreamSource.prototype.start = function (controller) {
35599 this._readableStreamController = controller;
35600 };
35601 AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) {
35602 assert$1(this._underlyingReader !== undefined);
35603 return this._underlyingReader.cancel(reason);
35604 };
35605 AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () {
35606 if (this._readerMode === "default" /* DEFAULT */) {
35607 return;
35608 }
35609 this._detachReader();
35610 var reader = this._underlyingStream.getReader();
35611 this._readerMode = "default" /* DEFAULT */;
35612 this._attachReader(reader);
35613 };
35614 AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) {
35615 var _this = this;
35616 assert$1(this._underlyingReader === undefined);
35617 this._underlyingReader = reader;
35618 var closed = this._underlyingReader.closed;
35619 if (!closed) {
35620 return;
35621 }
35622 closed
35623 .then(function () { return _this._finishPendingRead(); })
35624 .then(function () {
35625 if (reader === _this._underlyingReader) {
35626 _this._readableStreamController.close();
35627 }
35628 }, function (reason) {
35629 if (reader === _this._underlyingReader) {
35630 _this._readableStreamController.error(reason);
35631 }
35632 })
35633 .catch(noop$1);
35634 };
35635 AbstractWrappingReadableStreamSource.prototype._detachReader = function () {
35636 if (this._underlyingReader === undefined) {
35637 return;
35638 }
35639 this._underlyingReader.releaseLock();
35640 this._underlyingReader = undefined;
35641 this._readerMode = undefined;
35642 };
35643 AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () {
35644 var _this = this;
35645 this._attachDefaultReader();
35646 // TODO Backpressure?
35647 var read = this._underlyingReader.read()
35648 .then(function (result) {
35649 var controller = _this._readableStreamController;
35650 if (result.done) {
35651 _this._tryClose();
35652 }
35653 else {
35654 controller.enqueue(result.value);
35655 }
35656 });
35657 this._setPendingRead(read);
35658 return read;
35659 };
35660 AbstractWrappingReadableStreamSource.prototype._tryClose = function () {
35661 try {
35662 this._readableStreamController.close();
35663 }
35664 catch (_a) {
35665 // already errored or closed
35666 }
35667 };
35668 AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) {
35669 var _this = this;
35670 var pendingRead;
35671 var finishRead = function () {
35672 if (_this._pendingRead === pendingRead) {
35673 _this._pendingRead = undefined;
35674 }
35675 };
35676 this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead);
35677 };
35678 AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () {
35679 var _this = this;
35680 if (!this._pendingRead) {
35681 return undefined;
35682 }
35683 var afterRead = function () { return _this._finishPendingRead(); };
35684 return this._pendingRead.then(afterRead, afterRead);
35685 };
35686 return AbstractWrappingReadableStreamSource;
35687}());
35688var WrappingReadableStreamDefaultSource = /** @class */ (function (_super) {
35689 __extends(WrappingReadableStreamDefaultSource, _super);
35690 function WrappingReadableStreamDefaultSource() {
35691 return _super !== null && _super.apply(this, arguments) || this;
35692 }
35693 WrappingReadableStreamDefaultSource.prototype.pull = function () {
35694 return this._pullWithDefaultReader();
35695 };
35696 return WrappingReadableStreamDefaultSource;
35697}(AbstractWrappingReadableStreamSource));
35698function toUint8Array(view) {
35699 return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
35700}
35701function copyArrayBufferView(from, to) {
35702 var fromArray = toUint8Array(from);
35703 var toArray = toUint8Array(to);
35704 toArray.set(fromArray, 0);
35705}
35706var WrappingReadableByteStreamSource = /** @class */ (function (_super) {
35707 __extends(WrappingReadableByteStreamSource, _super);
35708 function WrappingReadableByteStreamSource(underlyingStream) {
35709 var _this = this;
35710 var supportsByob = supportsByobReader(underlyingStream);
35711 _this = _super.call(this, underlyingStream) || this;
35712 _this._supportsByob = supportsByob;
35713 return _this;
35714 }
35715 Object.defineProperty(WrappingReadableByteStreamSource.prototype, "type", {
35716 get: function () {
35717 return 'bytes';
35718 },
35719 enumerable: false,
35720 configurable: true
35721 });
35722 WrappingReadableByteStreamSource.prototype._attachByobReader = function () {
35723 if (this._readerMode === "byob" /* BYOB */) {
35724 return;
35725 }
35726 assert$1(this._supportsByob);
35727 this._detachReader();
35728 var reader = this._underlyingStream.getReader({ mode: 'byob' });
35729 this._readerMode = "byob" /* BYOB */;
35730 this._attachReader(reader);
35731 };
35732 WrappingReadableByteStreamSource.prototype.pull = function () {
35733 if (this._supportsByob) {
35734 var byobRequest = this._readableStreamController.byobRequest;
35735 if (byobRequest) {
35736 return this._pullWithByobRequest(byobRequest);
35737 }
35738 }
35739 return this._pullWithDefaultReader();
35740 };
35741 WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) {
35742 var _this = this;
35743 this._attachByobReader();
35744 // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly
35745 // create a separate buffer to read into, then copy that to byobRequest.view
35746 var buffer = new Uint8Array(byobRequest.view.byteLength);
35747 // TODO Backpressure?
35748 var read = this._underlyingReader.read(buffer)
35749 .then(function (result) {
35750 _this._readableStreamController;
35751 if (result.done) {
35752 _this._tryClose();
35753 byobRequest.respond(0);
35754 }
35755 else {
35756 copyArrayBufferView(result.value, byobRequest.view);
35757 byobRequest.respond(result.value.byteLength);
35758 }
35759 });
35760 this._setPendingRead(read);
35761 return read;
35762 };
35763 return WrappingReadableByteStreamSource;
35764}(AbstractWrappingReadableStreamSource));
35765
35766function createWritableStreamWrapper(ctor) {
35767 assert$1(isWritableStreamConstructor(ctor));
35768 return function (writable) {
35769 if (writable.constructor === ctor) {
35770 return writable;
35771 }
35772 var sink = createWrappingWritableSink(writable);
35773 return new ctor(sink);
35774 };
35775}
35776function createWrappingWritableSink(writable) {
35777 assert$1(isWritableStream(writable));
35778 assert$1(writable.locked === false);
35779 var writer = writable.getWriter();
35780 return new WrappingWritableStreamSink(writer);
35781}
35782var WrappingWritableStreamSink = /** @class */ (function () {
35783 function WrappingWritableStreamSink(underlyingWriter) {
35784 var _this = this;
35785 this._writableStreamController = undefined;
35786 this._pendingWrite = undefined;
35787 this._state = "writable" /* WRITABLE */;
35788 this._storedError = undefined;
35789 this._underlyingWriter = underlyingWriter;
35790 this._errorPromise = new Promise(function (resolve, reject) {
35791 _this._errorPromiseReject = reject;
35792 });
35793 this._errorPromise.catch(noop$1);
35794 }
35795 WrappingWritableStreamSink.prototype.start = function (controller) {
35796 var _this = this;
35797 this._writableStreamController = controller;
35798 this._underlyingWriter.closed
35799 .then(function () {
35800 _this._state = "closed" /* CLOSED */;
35801 })
35802 .catch(function (reason) { return _this._finishErroring(reason); });
35803 };
35804 WrappingWritableStreamSink.prototype.write = function (chunk) {
35805 var _this = this;
35806 var writer = this._underlyingWriter;
35807 // Detect past errors
35808 if (writer.desiredSize === null) {
35809 return writer.ready;
35810 }
35811 var writeRequest = writer.write(chunk);
35812 // Detect future errors
35813 writeRequest.catch(function (reason) { return _this._finishErroring(reason); });
35814 writer.ready.catch(function (reason) { return _this._startErroring(reason); });
35815 // Reject write when errored
35816 var write = Promise.race([writeRequest, this._errorPromise]);
35817 this._setPendingWrite(write);
35818 return write;
35819 };
35820 WrappingWritableStreamSink.prototype.close = function () {
35821 var _this = this;
35822 if (this._pendingWrite === undefined) {
35823 return this._underlyingWriter.close();
35824 }
35825 return this._finishPendingWrite().then(function () { return _this.close(); });
35826 };
35827 WrappingWritableStreamSink.prototype.abort = function (reason) {
35828 if (this._state === "errored" /* ERRORED */) {
35829 return undefined;
35830 }
35831 var writer = this._underlyingWriter;
35832 return writer.abort(reason);
35833 };
35834 WrappingWritableStreamSink.prototype._setPendingWrite = function (writePromise) {
35835 var _this = this;
35836 var pendingWrite;
35837 var finishWrite = function () {
35838 if (_this._pendingWrite === pendingWrite) {
35839 _this._pendingWrite = undefined;
35840 }
35841 };
35842 this._pendingWrite = pendingWrite = writePromise.then(finishWrite, finishWrite);
35843 };
35844 WrappingWritableStreamSink.prototype._finishPendingWrite = function () {
35845 var _this = this;
35846 if (this._pendingWrite === undefined) {
35847 return Promise.resolve();
35848 }
35849 var afterWrite = function () { return _this._finishPendingWrite(); };
35850 return this._pendingWrite.then(afterWrite, afterWrite);
35851 };
35852 WrappingWritableStreamSink.prototype._startErroring = function (reason) {
35853 var _this = this;
35854 if (this._state === "writable" /* WRITABLE */) {
35855 this._state = "erroring" /* ERRORING */;
35856 this._storedError = reason;
35857 var afterWrite = function () { return _this._finishErroring(reason); };
35858 if (this._pendingWrite === undefined) {
35859 afterWrite();
35860 }
35861 else {
35862 this._finishPendingWrite().then(afterWrite, afterWrite);
35863 }
35864 this._writableStreamController.error(reason);
35865 }
35866 };
35867 WrappingWritableStreamSink.prototype._finishErroring = function (reason) {
35868 if (this._state === "writable" /* WRITABLE */) {
35869 this._startErroring(reason);
35870 }
35871 if (this._state === "erroring" /* ERRORING */) {
35872 this._state = "errored" /* ERRORED */;
35873 this._errorPromiseReject(this._storedError);
35874 }
35875 };
35876 return WrappingWritableStreamSink;
35877}());
35878
35879function createTransformStreamWrapper(ctor) {
35880 assert$1(isTransformStreamConstructor(ctor));
35881 return function (transform) {
35882 if (transform.constructor === ctor) {
35883 return transform;
35884 }
35885 var transformer = createWrappingTransformer(transform);
35886 return new ctor(transformer);
35887 };
35888}
35889function createWrappingTransformer(transform) {
35890 assert$1(isTransformStream(transform));
35891 var readable = transform.readable, writable = transform.writable;
35892 assert$1(readable.locked === false);
35893 assert$1(writable.locked === false);
35894 var reader = readable.getReader();
35895 var writer;
35896 try {
35897 writer = writable.getWriter();
35898 }
35899 catch (e) {
35900 reader.releaseLock(); // do not leak reader
35901 throw e;
35902 }
35903 return new WrappingTransformStreamTransformer(reader, writer);
35904}
35905var WrappingTransformStreamTransformer = /** @class */ (function () {
35906 function WrappingTransformStreamTransformer(reader, writer) {
35907 var _this = this;
35908 this._transformStreamController = undefined;
35909 this._onRead = function (result) {
35910 if (result.done) {
35911 return;
35912 }
35913 _this._transformStreamController.enqueue(result.value);
35914 return _this._reader.read().then(_this._onRead);
35915 };
35916 this._onError = function (reason) {
35917 _this._flushReject(reason);
35918 _this._transformStreamController.error(reason);
35919 _this._reader.cancel(reason).catch(noop$1);
35920 _this._writer.abort(reason).catch(noop$1);
35921 };
35922 this._onTerminate = function () {
35923 _this._flushResolve();
35924 _this._transformStreamController.terminate();
35925 var error = new TypeError('TransformStream terminated');
35926 _this._writer.abort(error).catch(noop$1);
35927 };
35928 this._reader = reader;
35929 this._writer = writer;
35930 this._flushPromise = new Promise(function (resolve, reject) {
35931 _this._flushResolve = resolve;
35932 _this._flushReject = reject;
35933 });
35934 }
35935 WrappingTransformStreamTransformer.prototype.start = function (controller) {
35936 this._transformStreamController = controller;
35937 this._reader.read()
35938 .then(this._onRead)
35939 .then(this._onTerminate, this._onError);
35940 var readerClosed = this._reader.closed;
35941 if (readerClosed) {
35942 readerClosed
35943 .then(this._onTerminate, this._onError);
35944 }
35945 };
35946 WrappingTransformStreamTransformer.prototype.transform = function (chunk) {
35947 return this._writer.write(chunk);
35948 };
35949 WrappingTransformStreamTransformer.prototype.flush = function () {
35950 var _this = this;
35951 return this._writer.close()
35952 .then(function () { return _this._flushPromise; });
35953 };
35954 return WrappingTransformStreamTransformer;
35955}());
35956
35957var webStreamsAdapter = /*#__PURE__*/Object.freeze({
35958 __proto__: null,
35959 createReadableStreamWrapper: createReadableStreamWrapper,
35960 createTransformStreamWrapper: createTransformStreamWrapper,
35961 createWrappingReadableSource: createWrappingReadableSource,
35962 createWrappingTransformer: createWrappingTransformer,
35963 createWrappingWritableSink: createWrappingWritableSink,
35964 createWritableStreamWrapper: createWritableStreamWrapper
35965});
35966
35967var bn = createCommonjsModule(function (module) {
35968(function (module, exports) {
35969
35970 // Utils
35971 function assert (val, msg) {
35972 if (!val) throw new Error(msg || 'Assertion failed');
35973 }
35974
35975 // Could use `inherits` module, but don't want to move from single file
35976 // architecture yet.
35977 function inherits (ctor, superCtor) {
35978 ctor.super_ = superCtor;
35979 var TempCtor = function () {};
35980 TempCtor.prototype = superCtor.prototype;
35981 ctor.prototype = new TempCtor();
35982 ctor.prototype.constructor = ctor;
35983 }
35984
35985 // BN
35986
35987 function BN (number, base, endian) {
35988 if (BN.isBN(number)) {
35989 return number;
35990 }
35991
35992 this.negative = 0;
35993 this.words = null;
35994 this.length = 0;
35995
35996 // Reduction context
35997 this.red = null;
35998
35999 if (number !== null) {
36000 if (base === 'le' || base === 'be') {
36001 endian = base;
36002 base = 10;
36003 }
36004
36005 this._init(number || 0, base || 10, endian || 'be');
36006 }
36007 }
36008 if (typeof module === 'object') {
36009 module.exports = BN;
36010 } else {
36011 exports.BN = BN;
36012 }
36013
36014 BN.BN = BN;
36015 BN.wordSize = 26;
36016
36017 var Buffer;
36018 try {
36019 Buffer = void('buffer').Buffer;
36020 } catch (e) {
36021 }
36022
36023 BN.isBN = function isBN (num) {
36024 if (num instanceof BN) {
36025 return true;
36026 }
36027
36028 return num !== null && typeof num === 'object' &&
36029 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
36030 };
36031
36032 BN.max = function max (left, right) {
36033 if (left.cmp(right) > 0) return left;
36034 return right;
36035 };
36036
36037 BN.min = function min (left, right) {
36038 if (left.cmp(right) < 0) return left;
36039 return right;
36040 };
36041
36042 BN.prototype._init = function init (number, base, endian) {
36043 if (typeof number === 'number') {
36044 return this._initNumber(number, base, endian);
36045 }
36046
36047 if (typeof number === 'object') {
36048 return this._initArray(number, base, endian);
36049 }
36050
36051 if (base === 'hex') {
36052 base = 16;
36053 }
36054 assert(base === (base | 0) && base >= 2 && base <= 36);
36055
36056 number = number.toString().replace(/\s+/g, '');
36057 var start = 0;
36058 if (number[0] === '-') {
36059 start++;
36060 }
36061
36062 if (base === 16) {
36063 this._parseHex(number, start);
36064 } else {
36065 this._parseBase(number, base, start);
36066 }
36067
36068 if (number[0] === '-') {
36069 this.negative = 1;
36070 }
36071
36072 this.strip();
36073
36074 if (endian !== 'le') return;
36075
36076 this._initArray(this.toArray(), base, endian);
36077 };
36078
36079 BN.prototype._initNumber = function _initNumber (number, base, endian) {
36080 if (number < 0) {
36081 this.negative = 1;
36082 number = -number;
36083 }
36084 if (number < 0x4000000) {
36085 this.words = [ number & 0x3ffffff ];
36086 this.length = 1;
36087 } else if (number < 0x10000000000000) {
36088 this.words = [
36089 number & 0x3ffffff,
36090 (number / 0x4000000) & 0x3ffffff
36091 ];
36092 this.length = 2;
36093 } else {
36094 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
36095 this.words = [
36096 number & 0x3ffffff,
36097 (number / 0x4000000) & 0x3ffffff,
36098 1
36099 ];
36100 this.length = 3;
36101 }
36102
36103 if (endian !== 'le') return;
36104
36105 // Reverse the bytes
36106 this._initArray(this.toArray(), base, endian);
36107 };
36108
36109 BN.prototype._initArray = function _initArray (number, base, endian) {
36110 // Perhaps a Uint8Array
36111 assert(typeof number.length === 'number');
36112 if (number.length <= 0) {
36113 this.words = [ 0 ];
36114 this.length = 1;
36115 return this;
36116 }
36117
36118 this.length = Math.ceil(number.length / 3);
36119 this.words = new Array(this.length);
36120 for (var i = 0; i < this.length; i++) {
36121 this.words[i] = 0;
36122 }
36123
36124 var j, w;
36125 var off = 0;
36126 if (endian === 'be') {
36127 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
36128 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
36129 this.words[j] |= (w << off) & 0x3ffffff;
36130 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
36131 off += 24;
36132 if (off >= 26) {
36133 off -= 26;
36134 j++;
36135 }
36136 }
36137 } else if (endian === 'le') {
36138 for (i = 0, j = 0; i < number.length; i += 3) {
36139 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
36140 this.words[j] |= (w << off) & 0x3ffffff;
36141 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
36142 off += 24;
36143 if (off >= 26) {
36144 off -= 26;
36145 j++;
36146 }
36147 }
36148 }
36149 return this.strip();
36150 };
36151
36152 function parseHex (str, start, end) {
36153 var r = 0;
36154 var len = Math.min(str.length, end);
36155 for (var i = start; i < len; i++) {
36156 var c = str.charCodeAt(i) - 48;
36157
36158 r <<= 4;
36159
36160 // 'a' - 'f'
36161 if (c >= 49 && c <= 54) {
36162 r |= c - 49 + 0xa;
36163
36164 // 'A' - 'F'
36165 } else if (c >= 17 && c <= 22) {
36166 r |= c - 17 + 0xa;
36167
36168 // '0' - '9'
36169 } else {
36170 r |= c & 0xf;
36171 }
36172 }
36173 return r;
36174 }
36175
36176 BN.prototype._parseHex = function _parseHex (number, start) {
36177 // Create possibly bigger array to ensure that it fits the number
36178 this.length = Math.ceil((number.length - start) / 6);
36179 this.words = new Array(this.length);
36180 for (var i = 0; i < this.length; i++) {
36181 this.words[i] = 0;
36182 }
36183
36184 var j, w;
36185 // Scan 24-bit chunks and add them to the number
36186 var off = 0;
36187 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
36188 w = parseHex(number, i, i + 6);
36189 this.words[j] |= (w << off) & 0x3ffffff;
36190 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
36191 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
36192 off += 24;
36193 if (off >= 26) {
36194 off -= 26;
36195 j++;
36196 }
36197 }
36198 if (i + 6 !== start) {
36199 w = parseHex(number, start, i + 6);
36200 this.words[j] |= (w << off) & 0x3ffffff;
36201 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
36202 }
36203 this.strip();
36204 };
36205
36206 function parseBase (str, start, end, mul) {
36207 var r = 0;
36208 var len = Math.min(str.length, end);
36209 for (var i = start; i < len; i++) {
36210 var c = str.charCodeAt(i) - 48;
36211
36212 r *= mul;
36213
36214 // 'a'
36215 if (c >= 49) {
36216 r += c - 49 + 0xa;
36217
36218 // 'A'
36219 } else if (c >= 17) {
36220 r += c - 17 + 0xa;
36221
36222 // '0' - '9'
36223 } else {
36224 r += c;
36225 }
36226 }
36227 return r;
36228 }
36229
36230 BN.prototype._parseBase = function _parseBase (number, base, start) {
36231 // Initialize as zero
36232 this.words = [ 0 ];
36233 this.length = 1;
36234
36235 // Find length of limb in base
36236 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
36237 limbLen++;
36238 }
36239 limbLen--;
36240 limbPow = (limbPow / base) | 0;
36241
36242 var total = number.length - start;
36243 var mod = total % limbLen;
36244 var end = Math.min(total, total - mod) + start;
36245
36246 var word = 0;
36247 for (var i = start; i < end; i += limbLen) {
36248 word = parseBase(number, i, i + limbLen, base);
36249
36250 this.imuln(limbPow);
36251 if (this.words[0] + word < 0x4000000) {
36252 this.words[0] += word;
36253 } else {
36254 this._iaddn(word);
36255 }
36256 }
36257
36258 if (mod !== 0) {
36259 var pow = 1;
36260 word = parseBase(number, i, number.length, base);
36261
36262 for (i = 0; i < mod; i++) {
36263 pow *= base;
36264 }
36265
36266 this.imuln(pow);
36267 if (this.words[0] + word < 0x4000000) {
36268 this.words[0] += word;
36269 } else {
36270 this._iaddn(word);
36271 }
36272 }
36273 };
36274
36275 BN.prototype.copy = function copy (dest) {
36276 dest.words = new Array(this.length);
36277 for (var i = 0; i < this.length; i++) {
36278 dest.words[i] = this.words[i];
36279 }
36280 dest.length = this.length;
36281 dest.negative = this.negative;
36282 dest.red = this.red;
36283 };
36284
36285 BN.prototype.clone = function clone () {
36286 var r = new BN(null);
36287 this.copy(r);
36288 return r;
36289 };
36290
36291 BN.prototype._expand = function _expand (size) {
36292 while (this.length < size) {
36293 this.words[this.length++] = 0;
36294 }
36295 return this;
36296 };
36297
36298 // Remove leading `0` from `this`
36299 BN.prototype.strip = function strip () {
36300 while (this.length > 1 && this.words[this.length - 1] === 0) {
36301 this.length--;
36302 }
36303 return this._normSign();
36304 };
36305
36306 BN.prototype._normSign = function _normSign () {
36307 // -0 = 0
36308 if (this.length === 1 && this.words[0] === 0) {
36309 this.negative = 0;
36310 }
36311 return this;
36312 };
36313
36314 BN.prototype.inspect = function inspect () {
36315 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
36316 };
36317
36318 /*
36319
36320 var zeros = [];
36321 var groupSizes = [];
36322 var groupBases = [];
36323
36324 var s = '';
36325 var i = -1;
36326 while (++i < BN.wordSize) {
36327 zeros[i] = s;
36328 s += '0';
36329 }
36330 groupSizes[0] = 0;
36331 groupSizes[1] = 0;
36332 groupBases[0] = 0;
36333 groupBases[1] = 0;
36334 var base = 2 - 1;
36335 while (++base < 36 + 1) {
36336 var groupSize = 0;
36337 var groupBase = 1;
36338 while (groupBase < (1 << BN.wordSize) / base) {
36339 groupBase *= base;
36340 groupSize += 1;
36341 }
36342 groupSizes[base] = groupSize;
36343 groupBases[base] = groupBase;
36344 }
36345
36346 */
36347
36348 var zeros = [
36349 '',
36350 '0',
36351 '00',
36352 '000',
36353 '0000',
36354 '00000',
36355 '000000',
36356 '0000000',
36357 '00000000',
36358 '000000000',
36359 '0000000000',
36360 '00000000000',
36361 '000000000000',
36362 '0000000000000',
36363 '00000000000000',
36364 '000000000000000',
36365 '0000000000000000',
36366 '00000000000000000',
36367 '000000000000000000',
36368 '0000000000000000000',
36369 '00000000000000000000',
36370 '000000000000000000000',
36371 '0000000000000000000000',
36372 '00000000000000000000000',
36373 '000000000000000000000000',
36374 '0000000000000000000000000'
36375 ];
36376
36377 var groupSizes = [
36378 0, 0,
36379 25, 16, 12, 11, 10, 9, 8,
36380 8, 7, 7, 7, 7, 6, 6,
36381 6, 6, 6, 6, 6, 5, 5,
36382 5, 5, 5, 5, 5, 5, 5,
36383 5, 5, 5, 5, 5, 5, 5
36384 ];
36385
36386 var groupBases = [
36387 0, 0,
36388 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
36389 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
36390 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
36391 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
36392 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
36393 ];
36394
36395 BN.prototype.toString = function toString (base, padding) {
36396 base = base || 10;
36397 padding = padding | 0 || 1;
36398
36399 var out;
36400 if (base === 16 || base === 'hex') {
36401 out = '';
36402 var off = 0;
36403 var carry = 0;
36404 for (var i = 0; i < this.length; i++) {
36405 var w = this.words[i];
36406 var word = (((w << off) | carry) & 0xffffff).toString(16);
36407 carry = (w >>> (24 - off)) & 0xffffff;
36408 if (carry !== 0 || i !== this.length - 1) {
36409 out = zeros[6 - word.length] + word + out;
36410 } else {
36411 out = word + out;
36412 }
36413 off += 2;
36414 if (off >= 26) {
36415 off -= 26;
36416 i--;
36417 }
36418 }
36419 if (carry !== 0) {
36420 out = carry.toString(16) + out;
36421 }
36422 while (out.length % padding !== 0) {
36423 out = '0' + out;
36424 }
36425 if (this.negative !== 0) {
36426 out = '-' + out;
36427 }
36428 return out;
36429 }
36430
36431 if (base === (base | 0) && base >= 2 && base <= 36) {
36432 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
36433 var groupSize = groupSizes[base];
36434 // var groupBase = Math.pow(base, groupSize);
36435 var groupBase = groupBases[base];
36436 out = '';
36437 var c = this.clone();
36438 c.negative = 0;
36439 while (!c.isZero()) {
36440 var r = c.modn(groupBase).toString(base);
36441 c = c.idivn(groupBase);
36442
36443 if (!c.isZero()) {
36444 out = zeros[groupSize - r.length] + r + out;
36445 } else {
36446 out = r + out;
36447 }
36448 }
36449 if (this.isZero()) {
36450 out = '0' + out;
36451 }
36452 while (out.length % padding !== 0) {
36453 out = '0' + out;
36454 }
36455 if (this.negative !== 0) {
36456 out = '-' + out;
36457 }
36458 return out;
36459 }
36460
36461 assert(false, 'Base should be between 2 and 36');
36462 };
36463
36464 BN.prototype.toNumber = function toNumber () {
36465 var ret = this.words[0];
36466 if (this.length === 2) {
36467 ret += this.words[1] * 0x4000000;
36468 } else if (this.length === 3 && this.words[2] === 0x01) {
36469 // NOTE: at this stage it is known that the top bit is set
36470 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
36471 } else if (this.length > 2) {
36472 assert(false, 'Number can only safely store up to 53 bits');
36473 }
36474 return (this.negative !== 0) ? -ret : ret;
36475 };
36476
36477 BN.prototype.toJSON = function toJSON () {
36478 return this.toString(16);
36479 };
36480
36481 BN.prototype.toBuffer = function toBuffer (endian, length) {
36482 assert(typeof Buffer !== 'undefined');
36483 return this.toArrayLike(Buffer, endian, length);
36484 };
36485
36486 BN.prototype.toArray = function toArray (endian, length) {
36487 return this.toArrayLike(Array, endian, length);
36488 };
36489
36490 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
36491 var byteLength = this.byteLength();
36492 var reqLength = length || Math.max(1, byteLength);
36493 assert(byteLength <= reqLength, 'byte array longer than desired length');
36494 assert(reqLength > 0, 'Requested array length <= 0');
36495
36496 this.strip();
36497 var littleEndian = endian === 'le';
36498 var res = new ArrayType(reqLength);
36499
36500 var b, i;
36501 var q = this.clone();
36502 if (!littleEndian) {
36503 // Assume big-endian
36504 for (i = 0; i < reqLength - byteLength; i++) {
36505 res[i] = 0;
36506 }
36507
36508 for (i = 0; !q.isZero(); i++) {
36509 b = q.andln(0xff);
36510 q.iushrn(8);
36511
36512 res[reqLength - i - 1] = b;
36513 }
36514 } else {
36515 for (i = 0; !q.isZero(); i++) {
36516 b = q.andln(0xff);
36517 q.iushrn(8);
36518
36519 res[i] = b;
36520 }
36521
36522 for (; i < reqLength; i++) {
36523 res[i] = 0;
36524 }
36525 }
36526
36527 return res;
36528 };
36529
36530 if (Math.clz32) {
36531 BN.prototype._countBits = function _countBits (w) {
36532 return 32 - Math.clz32(w);
36533 };
36534 } else {
36535 BN.prototype._countBits = function _countBits (w) {
36536 var t = w;
36537 var r = 0;
36538 if (t >= 0x1000) {
36539 r += 13;
36540 t >>>= 13;
36541 }
36542 if (t >= 0x40) {
36543 r += 7;
36544 t >>>= 7;
36545 }
36546 if (t >= 0x8) {
36547 r += 4;
36548 t >>>= 4;
36549 }
36550 if (t >= 0x02) {
36551 r += 2;
36552 t >>>= 2;
36553 }
36554 return r + t;
36555 };
36556 }
36557
36558 BN.prototype._zeroBits = function _zeroBits (w) {
36559 // Short-cut
36560 if (w === 0) return 26;
36561
36562 var t = w;
36563 var r = 0;
36564 if ((t & 0x1fff) === 0) {
36565 r += 13;
36566 t >>>= 13;
36567 }
36568 if ((t & 0x7f) === 0) {
36569 r += 7;
36570 t >>>= 7;
36571 }
36572 if ((t & 0xf) === 0) {
36573 r += 4;
36574 t >>>= 4;
36575 }
36576 if ((t & 0x3) === 0) {
36577 r += 2;
36578 t >>>= 2;
36579 }
36580 if ((t & 0x1) === 0) {
36581 r++;
36582 }
36583 return r;
36584 };
36585
36586 // Return number of used bits in a BN
36587 BN.prototype.bitLength = function bitLength () {
36588 var w = this.words[this.length - 1];
36589 var hi = this._countBits(w);
36590 return (this.length - 1) * 26 + hi;
36591 };
36592
36593 function toBitArray (num) {
36594 var w = new Array(num.bitLength());
36595
36596 for (var bit = 0; bit < w.length; bit++) {
36597 var off = (bit / 26) | 0;
36598 var wbit = bit % 26;
36599
36600 w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
36601 }
36602
36603 return w;
36604 }
36605
36606 // Number of trailing zero bits
36607 BN.prototype.zeroBits = function zeroBits () {
36608 if (this.isZero()) return 0;
36609
36610 var r = 0;
36611 for (var i = 0; i < this.length; i++) {
36612 var b = this._zeroBits(this.words[i]);
36613 r += b;
36614 if (b !== 26) break;
36615 }
36616 return r;
36617 };
36618
36619 BN.prototype.byteLength = function byteLength () {
36620 return Math.ceil(this.bitLength() / 8);
36621 };
36622
36623 BN.prototype.toTwos = function toTwos (width) {
36624 if (this.negative !== 0) {
36625 return this.abs().inotn(width).iaddn(1);
36626 }
36627 return this.clone();
36628 };
36629
36630 BN.prototype.fromTwos = function fromTwos (width) {
36631 if (this.testn(width - 1)) {
36632 return this.notn(width).iaddn(1).ineg();
36633 }
36634 return this.clone();
36635 };
36636
36637 BN.prototype.isNeg = function isNeg () {
36638 return this.negative !== 0;
36639 };
36640
36641 // Return negative clone of `this`
36642 BN.prototype.neg = function neg () {
36643 return this.clone().ineg();
36644 };
36645
36646 BN.prototype.ineg = function ineg () {
36647 if (!this.isZero()) {
36648 this.negative ^= 1;
36649 }
36650
36651 return this;
36652 };
36653
36654 // Or `num` with `this` in-place
36655 BN.prototype.iuor = function iuor (num) {
36656 while (this.length < num.length) {
36657 this.words[this.length++] = 0;
36658 }
36659
36660 for (var i = 0; i < num.length; i++) {
36661 this.words[i] = this.words[i] | num.words[i];
36662 }
36663
36664 return this.strip();
36665 };
36666
36667 BN.prototype.ior = function ior (num) {
36668 assert((this.negative | num.negative) === 0);
36669 return this.iuor(num);
36670 };
36671
36672 // Or `num` with `this`
36673 BN.prototype.or = function or (num) {
36674 if (this.length > num.length) return this.clone().ior(num);
36675 return num.clone().ior(this);
36676 };
36677
36678 BN.prototype.uor = function uor (num) {
36679 if (this.length > num.length) return this.clone().iuor(num);
36680 return num.clone().iuor(this);
36681 };
36682
36683 // And `num` with `this` in-place
36684 BN.prototype.iuand = function iuand (num) {
36685 // b = min-length(num, this)
36686 var b;
36687 if (this.length > num.length) {
36688 b = num;
36689 } else {
36690 b = this;
36691 }
36692
36693 for (var i = 0; i < b.length; i++) {
36694 this.words[i] = this.words[i] & num.words[i];
36695 }
36696
36697 this.length = b.length;
36698
36699 return this.strip();
36700 };
36701
36702 BN.prototype.iand = function iand (num) {
36703 assert((this.negative | num.negative) === 0);
36704 return this.iuand(num);
36705 };
36706
36707 // And `num` with `this`
36708 BN.prototype.and = function and (num) {
36709 if (this.length > num.length) return this.clone().iand(num);
36710 return num.clone().iand(this);
36711 };
36712
36713 BN.prototype.uand = function uand (num) {
36714 if (this.length > num.length) return this.clone().iuand(num);
36715 return num.clone().iuand(this);
36716 };
36717
36718 // Xor `num` with `this` in-place
36719 BN.prototype.iuxor = function iuxor (num) {
36720 // a.length > b.length
36721 var a;
36722 var b;
36723 if (this.length > num.length) {
36724 a = this;
36725 b = num;
36726 } else {
36727 a = num;
36728 b = this;
36729 }
36730
36731 for (var i = 0; i < b.length; i++) {
36732 this.words[i] = a.words[i] ^ b.words[i];
36733 }
36734
36735 if (this !== a) {
36736 for (; i < a.length; i++) {
36737 this.words[i] = a.words[i];
36738 }
36739 }
36740
36741 this.length = a.length;
36742
36743 return this.strip();
36744 };
36745
36746 BN.prototype.ixor = function ixor (num) {
36747 assert((this.negative | num.negative) === 0);
36748 return this.iuxor(num);
36749 };
36750
36751 // Xor `num` with `this`
36752 BN.prototype.xor = function xor (num) {
36753 if (this.length > num.length) return this.clone().ixor(num);
36754 return num.clone().ixor(this);
36755 };
36756
36757 BN.prototype.uxor = function uxor (num) {
36758 if (this.length > num.length) return this.clone().iuxor(num);
36759 return num.clone().iuxor(this);
36760 };
36761
36762 // Not ``this`` with ``width`` bitwidth
36763 BN.prototype.inotn = function inotn (width) {
36764 assert(typeof width === 'number' && width >= 0);
36765
36766 var bytesNeeded = Math.ceil(width / 26) | 0;
36767 var bitsLeft = width % 26;
36768
36769 // Extend the buffer with leading zeroes
36770 this._expand(bytesNeeded);
36771
36772 if (bitsLeft > 0) {
36773 bytesNeeded--;
36774 }
36775
36776 // Handle complete words
36777 for (var i = 0; i < bytesNeeded; i++) {
36778 this.words[i] = ~this.words[i] & 0x3ffffff;
36779 }
36780
36781 // Handle the residue
36782 if (bitsLeft > 0) {
36783 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
36784 }
36785
36786 // And remove leading zeroes
36787 return this.strip();
36788 };
36789
36790 BN.prototype.notn = function notn (width) {
36791 return this.clone().inotn(width);
36792 };
36793
36794 // Set `bit` of `this`
36795 BN.prototype.setn = function setn (bit, val) {
36796 assert(typeof bit === 'number' && bit >= 0);
36797
36798 var off = (bit / 26) | 0;
36799 var wbit = bit % 26;
36800
36801 this._expand(off + 1);
36802
36803 if (val) {
36804 this.words[off] = this.words[off] | (1 << wbit);
36805 } else {
36806 this.words[off] = this.words[off] & ~(1 << wbit);
36807 }
36808
36809 return this.strip();
36810 };
36811
36812 // Add `num` to `this` in-place
36813 BN.prototype.iadd = function iadd (num) {
36814 var r;
36815
36816 // negative + positive
36817 if (this.negative !== 0 && num.negative === 0) {
36818 this.negative = 0;
36819 r = this.isub(num);
36820 this.negative ^= 1;
36821 return this._normSign();
36822
36823 // positive + negative
36824 } else if (this.negative === 0 && num.negative !== 0) {
36825 num.negative = 0;
36826 r = this.isub(num);
36827 num.negative = 1;
36828 return r._normSign();
36829 }
36830
36831 // a.length > b.length
36832 var a, b;
36833 if (this.length > num.length) {
36834 a = this;
36835 b = num;
36836 } else {
36837 a = num;
36838 b = this;
36839 }
36840
36841 var carry = 0;
36842 for (var i = 0; i < b.length; i++) {
36843 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
36844 this.words[i] = r & 0x3ffffff;
36845 carry = r >>> 26;
36846 }
36847 for (; carry !== 0 && i < a.length; i++) {
36848 r = (a.words[i] | 0) + carry;
36849 this.words[i] = r & 0x3ffffff;
36850 carry = r >>> 26;
36851 }
36852
36853 this.length = a.length;
36854 if (carry !== 0) {
36855 this.words[this.length] = carry;
36856 this.length++;
36857 // Copy the rest of the words
36858 } else if (a !== this) {
36859 for (; i < a.length; i++) {
36860 this.words[i] = a.words[i];
36861 }
36862 }
36863
36864 return this;
36865 };
36866
36867 // Add `num` to `this`
36868 BN.prototype.add = function add (num) {
36869 var res;
36870 if (num.negative !== 0 && this.negative === 0) {
36871 num.negative = 0;
36872 res = this.sub(num);
36873 num.negative ^= 1;
36874 return res;
36875 } else if (num.negative === 0 && this.negative !== 0) {
36876 this.negative = 0;
36877 res = num.sub(this);
36878 this.negative = 1;
36879 return res;
36880 }
36881
36882 if (this.length > num.length) return this.clone().iadd(num);
36883
36884 return num.clone().iadd(this);
36885 };
36886
36887 // Subtract `num` from `this` in-place
36888 BN.prototype.isub = function isub (num) {
36889 // this - (-num) = this + num
36890 if (num.negative !== 0) {
36891 num.negative = 0;
36892 var r = this.iadd(num);
36893 num.negative = 1;
36894 return r._normSign();
36895
36896 // -this - num = -(this + num)
36897 } else if (this.negative !== 0) {
36898 this.negative = 0;
36899 this.iadd(num);
36900 this.negative = 1;
36901 return this._normSign();
36902 }
36903
36904 // At this point both numbers are positive
36905 var cmp = this.cmp(num);
36906
36907 // Optimization - zeroify
36908 if (cmp === 0) {
36909 this.negative = 0;
36910 this.length = 1;
36911 this.words[0] = 0;
36912 return this;
36913 }
36914
36915 // a > b
36916 var a, b;
36917 if (cmp > 0) {
36918 a = this;
36919 b = num;
36920 } else {
36921 a = num;
36922 b = this;
36923 }
36924
36925 var carry = 0;
36926 for (var i = 0; i < b.length; i++) {
36927 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
36928 carry = r >> 26;
36929 this.words[i] = r & 0x3ffffff;
36930 }
36931 for (; carry !== 0 && i < a.length; i++) {
36932 r = (a.words[i] | 0) + carry;
36933 carry = r >> 26;
36934 this.words[i] = r & 0x3ffffff;
36935 }
36936
36937 // Copy rest of the words
36938 if (carry === 0 && i < a.length && a !== this) {
36939 for (; i < a.length; i++) {
36940 this.words[i] = a.words[i];
36941 }
36942 }
36943
36944 this.length = Math.max(this.length, i);
36945
36946 if (a !== this) {
36947 this.negative = 1;
36948 }
36949
36950 return this.strip();
36951 };
36952
36953 // Subtract `num` from `this`
36954 BN.prototype.sub = function sub (num) {
36955 return this.clone().isub(num);
36956 };
36957
36958 function smallMulTo (self, num, out) {
36959 out.negative = num.negative ^ self.negative;
36960 var len = (self.length + num.length) | 0;
36961 out.length = len;
36962 len = (len - 1) | 0;
36963
36964 // Peel one iteration (compiler can't do it, because of code complexity)
36965 var a = self.words[0] | 0;
36966 var b = num.words[0] | 0;
36967 var r = a * b;
36968
36969 var lo = r & 0x3ffffff;
36970 var carry = (r / 0x4000000) | 0;
36971 out.words[0] = lo;
36972
36973 for (var k = 1; k < len; k++) {
36974 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
36975 // note that ncarry could be >= 0x3ffffff
36976 var ncarry = carry >>> 26;
36977 var rword = carry & 0x3ffffff;
36978 var maxJ = Math.min(k, num.length - 1);
36979 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
36980 var i = (k - j) | 0;
36981 a = self.words[i] | 0;
36982 b = num.words[j] | 0;
36983 r = a * b + rword;
36984 ncarry += (r / 0x4000000) | 0;
36985 rword = r & 0x3ffffff;
36986 }
36987 out.words[k] = rword | 0;
36988 carry = ncarry | 0;
36989 }
36990 if (carry !== 0) {
36991 out.words[k] = carry | 0;
36992 } else {
36993 out.length--;
36994 }
36995
36996 return out.strip();
36997 }
36998
36999 // TODO(indutny): it may be reasonable to omit it for users who don't need
37000 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
37001 // multiplication (like elliptic secp256k1).
37002 var comb10MulTo = function comb10MulTo (self, num, out) {
37003 var a = self.words;
37004 var b = num.words;
37005 var o = out.words;
37006 var c = 0;
37007 var lo;
37008 var mid;
37009 var hi;
37010 var a0 = a[0] | 0;
37011 var al0 = a0 & 0x1fff;
37012 var ah0 = a0 >>> 13;
37013 var a1 = a[1] | 0;
37014 var al1 = a1 & 0x1fff;
37015 var ah1 = a1 >>> 13;
37016 var a2 = a[2] | 0;
37017 var al2 = a2 & 0x1fff;
37018 var ah2 = a2 >>> 13;
37019 var a3 = a[3] | 0;
37020 var al3 = a3 & 0x1fff;
37021 var ah3 = a3 >>> 13;
37022 var a4 = a[4] | 0;
37023 var al4 = a4 & 0x1fff;
37024 var ah4 = a4 >>> 13;
37025 var a5 = a[5] | 0;
37026 var al5 = a5 & 0x1fff;
37027 var ah5 = a5 >>> 13;
37028 var a6 = a[6] | 0;
37029 var al6 = a6 & 0x1fff;
37030 var ah6 = a6 >>> 13;
37031 var a7 = a[7] | 0;
37032 var al7 = a7 & 0x1fff;
37033 var ah7 = a7 >>> 13;
37034 var a8 = a[8] | 0;
37035 var al8 = a8 & 0x1fff;
37036 var ah8 = a8 >>> 13;
37037 var a9 = a[9] | 0;
37038 var al9 = a9 & 0x1fff;
37039 var ah9 = a9 >>> 13;
37040 var b0 = b[0] | 0;
37041 var bl0 = b0 & 0x1fff;
37042 var bh0 = b0 >>> 13;
37043 var b1 = b[1] | 0;
37044 var bl1 = b1 & 0x1fff;
37045 var bh1 = b1 >>> 13;
37046 var b2 = b[2] | 0;
37047 var bl2 = b2 & 0x1fff;
37048 var bh2 = b2 >>> 13;
37049 var b3 = b[3] | 0;
37050 var bl3 = b3 & 0x1fff;
37051 var bh3 = b3 >>> 13;
37052 var b4 = b[4] | 0;
37053 var bl4 = b4 & 0x1fff;
37054 var bh4 = b4 >>> 13;
37055 var b5 = b[5] | 0;
37056 var bl5 = b5 & 0x1fff;
37057 var bh5 = b5 >>> 13;
37058 var b6 = b[6] | 0;
37059 var bl6 = b6 & 0x1fff;
37060 var bh6 = b6 >>> 13;
37061 var b7 = b[7] | 0;
37062 var bl7 = b7 & 0x1fff;
37063 var bh7 = b7 >>> 13;
37064 var b8 = b[8] | 0;
37065 var bl8 = b8 & 0x1fff;
37066 var bh8 = b8 >>> 13;
37067 var b9 = b[9] | 0;
37068 var bl9 = b9 & 0x1fff;
37069 var bh9 = b9 >>> 13;
37070
37071 out.negative = self.negative ^ num.negative;
37072 out.length = 19;
37073 /* k = 0 */
37074 lo = Math.imul(al0, bl0);
37075 mid = Math.imul(al0, bh0);
37076 mid = (mid + Math.imul(ah0, bl0)) | 0;
37077 hi = Math.imul(ah0, bh0);
37078 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37079 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
37080 w0 &= 0x3ffffff;
37081 /* k = 1 */
37082 lo = Math.imul(al1, bl0);
37083 mid = Math.imul(al1, bh0);
37084 mid = (mid + Math.imul(ah1, bl0)) | 0;
37085 hi = Math.imul(ah1, bh0);
37086 lo = (lo + Math.imul(al0, bl1)) | 0;
37087 mid = (mid + Math.imul(al0, bh1)) | 0;
37088 mid = (mid + Math.imul(ah0, bl1)) | 0;
37089 hi = (hi + Math.imul(ah0, bh1)) | 0;
37090 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37091 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
37092 w1 &= 0x3ffffff;
37093 /* k = 2 */
37094 lo = Math.imul(al2, bl0);
37095 mid = Math.imul(al2, bh0);
37096 mid = (mid + Math.imul(ah2, bl0)) | 0;
37097 hi = Math.imul(ah2, bh0);
37098 lo = (lo + Math.imul(al1, bl1)) | 0;
37099 mid = (mid + Math.imul(al1, bh1)) | 0;
37100 mid = (mid + Math.imul(ah1, bl1)) | 0;
37101 hi = (hi + Math.imul(ah1, bh1)) | 0;
37102 lo = (lo + Math.imul(al0, bl2)) | 0;
37103 mid = (mid + Math.imul(al0, bh2)) | 0;
37104 mid = (mid + Math.imul(ah0, bl2)) | 0;
37105 hi = (hi + Math.imul(ah0, bh2)) | 0;
37106 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37107 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
37108 w2 &= 0x3ffffff;
37109 /* k = 3 */
37110 lo = Math.imul(al3, bl0);
37111 mid = Math.imul(al3, bh0);
37112 mid = (mid + Math.imul(ah3, bl0)) | 0;
37113 hi = Math.imul(ah3, bh0);
37114 lo = (lo + Math.imul(al2, bl1)) | 0;
37115 mid = (mid + Math.imul(al2, bh1)) | 0;
37116 mid = (mid + Math.imul(ah2, bl1)) | 0;
37117 hi = (hi + Math.imul(ah2, bh1)) | 0;
37118 lo = (lo + Math.imul(al1, bl2)) | 0;
37119 mid = (mid + Math.imul(al1, bh2)) | 0;
37120 mid = (mid + Math.imul(ah1, bl2)) | 0;
37121 hi = (hi + Math.imul(ah1, bh2)) | 0;
37122 lo = (lo + Math.imul(al0, bl3)) | 0;
37123 mid = (mid + Math.imul(al0, bh3)) | 0;
37124 mid = (mid + Math.imul(ah0, bl3)) | 0;
37125 hi = (hi + Math.imul(ah0, bh3)) | 0;
37126 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37127 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
37128 w3 &= 0x3ffffff;
37129 /* k = 4 */
37130 lo = Math.imul(al4, bl0);
37131 mid = Math.imul(al4, bh0);
37132 mid = (mid + Math.imul(ah4, bl0)) | 0;
37133 hi = Math.imul(ah4, bh0);
37134 lo = (lo + Math.imul(al3, bl1)) | 0;
37135 mid = (mid + Math.imul(al3, bh1)) | 0;
37136 mid = (mid + Math.imul(ah3, bl1)) | 0;
37137 hi = (hi + Math.imul(ah3, bh1)) | 0;
37138 lo = (lo + Math.imul(al2, bl2)) | 0;
37139 mid = (mid + Math.imul(al2, bh2)) | 0;
37140 mid = (mid + Math.imul(ah2, bl2)) | 0;
37141 hi = (hi + Math.imul(ah2, bh2)) | 0;
37142 lo = (lo + Math.imul(al1, bl3)) | 0;
37143 mid = (mid + Math.imul(al1, bh3)) | 0;
37144 mid = (mid + Math.imul(ah1, bl3)) | 0;
37145 hi = (hi + Math.imul(ah1, bh3)) | 0;
37146 lo = (lo + Math.imul(al0, bl4)) | 0;
37147 mid = (mid + Math.imul(al0, bh4)) | 0;
37148 mid = (mid + Math.imul(ah0, bl4)) | 0;
37149 hi = (hi + Math.imul(ah0, bh4)) | 0;
37150 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37151 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
37152 w4 &= 0x3ffffff;
37153 /* k = 5 */
37154 lo = Math.imul(al5, bl0);
37155 mid = Math.imul(al5, bh0);
37156 mid = (mid + Math.imul(ah5, bl0)) | 0;
37157 hi = Math.imul(ah5, bh0);
37158 lo = (lo + Math.imul(al4, bl1)) | 0;
37159 mid = (mid + Math.imul(al4, bh1)) | 0;
37160 mid = (mid + Math.imul(ah4, bl1)) | 0;
37161 hi = (hi + Math.imul(ah4, bh1)) | 0;
37162 lo = (lo + Math.imul(al3, bl2)) | 0;
37163 mid = (mid + Math.imul(al3, bh2)) | 0;
37164 mid = (mid + Math.imul(ah3, bl2)) | 0;
37165 hi = (hi + Math.imul(ah3, bh2)) | 0;
37166 lo = (lo + Math.imul(al2, bl3)) | 0;
37167 mid = (mid + Math.imul(al2, bh3)) | 0;
37168 mid = (mid + Math.imul(ah2, bl3)) | 0;
37169 hi = (hi + Math.imul(ah2, bh3)) | 0;
37170 lo = (lo + Math.imul(al1, bl4)) | 0;
37171 mid = (mid + Math.imul(al1, bh4)) | 0;
37172 mid = (mid + Math.imul(ah1, bl4)) | 0;
37173 hi = (hi + Math.imul(ah1, bh4)) | 0;
37174 lo = (lo + Math.imul(al0, bl5)) | 0;
37175 mid = (mid + Math.imul(al0, bh5)) | 0;
37176 mid = (mid + Math.imul(ah0, bl5)) | 0;
37177 hi = (hi + Math.imul(ah0, bh5)) | 0;
37178 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37179 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
37180 w5 &= 0x3ffffff;
37181 /* k = 6 */
37182 lo = Math.imul(al6, bl0);
37183 mid = Math.imul(al6, bh0);
37184 mid = (mid + Math.imul(ah6, bl0)) | 0;
37185 hi = Math.imul(ah6, bh0);
37186 lo = (lo + Math.imul(al5, bl1)) | 0;
37187 mid = (mid + Math.imul(al5, bh1)) | 0;
37188 mid = (mid + Math.imul(ah5, bl1)) | 0;
37189 hi = (hi + Math.imul(ah5, bh1)) | 0;
37190 lo = (lo + Math.imul(al4, bl2)) | 0;
37191 mid = (mid + Math.imul(al4, bh2)) | 0;
37192 mid = (mid + Math.imul(ah4, bl2)) | 0;
37193 hi = (hi + Math.imul(ah4, bh2)) | 0;
37194 lo = (lo + Math.imul(al3, bl3)) | 0;
37195 mid = (mid + Math.imul(al3, bh3)) | 0;
37196 mid = (mid + Math.imul(ah3, bl3)) | 0;
37197 hi = (hi + Math.imul(ah3, bh3)) | 0;
37198 lo = (lo + Math.imul(al2, bl4)) | 0;
37199 mid = (mid + Math.imul(al2, bh4)) | 0;
37200 mid = (mid + Math.imul(ah2, bl4)) | 0;
37201 hi = (hi + Math.imul(ah2, bh4)) | 0;
37202 lo = (lo + Math.imul(al1, bl5)) | 0;
37203 mid = (mid + Math.imul(al1, bh5)) | 0;
37204 mid = (mid + Math.imul(ah1, bl5)) | 0;
37205 hi = (hi + Math.imul(ah1, bh5)) | 0;
37206 lo = (lo + Math.imul(al0, bl6)) | 0;
37207 mid = (mid + Math.imul(al0, bh6)) | 0;
37208 mid = (mid + Math.imul(ah0, bl6)) | 0;
37209 hi = (hi + Math.imul(ah0, bh6)) | 0;
37210 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37211 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
37212 w6 &= 0x3ffffff;
37213 /* k = 7 */
37214 lo = Math.imul(al7, bl0);
37215 mid = Math.imul(al7, bh0);
37216 mid = (mid + Math.imul(ah7, bl0)) | 0;
37217 hi = Math.imul(ah7, bh0);
37218 lo = (lo + Math.imul(al6, bl1)) | 0;
37219 mid = (mid + Math.imul(al6, bh1)) | 0;
37220 mid = (mid + Math.imul(ah6, bl1)) | 0;
37221 hi = (hi + Math.imul(ah6, bh1)) | 0;
37222 lo = (lo + Math.imul(al5, bl2)) | 0;
37223 mid = (mid + Math.imul(al5, bh2)) | 0;
37224 mid = (mid + Math.imul(ah5, bl2)) | 0;
37225 hi = (hi + Math.imul(ah5, bh2)) | 0;
37226 lo = (lo + Math.imul(al4, bl3)) | 0;
37227 mid = (mid + Math.imul(al4, bh3)) | 0;
37228 mid = (mid + Math.imul(ah4, bl3)) | 0;
37229 hi = (hi + Math.imul(ah4, bh3)) | 0;
37230 lo = (lo + Math.imul(al3, bl4)) | 0;
37231 mid = (mid + Math.imul(al3, bh4)) | 0;
37232 mid = (mid + Math.imul(ah3, bl4)) | 0;
37233 hi = (hi + Math.imul(ah3, bh4)) | 0;
37234 lo = (lo + Math.imul(al2, bl5)) | 0;
37235 mid = (mid + Math.imul(al2, bh5)) | 0;
37236 mid = (mid + Math.imul(ah2, bl5)) | 0;
37237 hi = (hi + Math.imul(ah2, bh5)) | 0;
37238 lo = (lo + Math.imul(al1, bl6)) | 0;
37239 mid = (mid + Math.imul(al1, bh6)) | 0;
37240 mid = (mid + Math.imul(ah1, bl6)) | 0;
37241 hi = (hi + Math.imul(ah1, bh6)) | 0;
37242 lo = (lo + Math.imul(al0, bl7)) | 0;
37243 mid = (mid + Math.imul(al0, bh7)) | 0;
37244 mid = (mid + Math.imul(ah0, bl7)) | 0;
37245 hi = (hi + Math.imul(ah0, bh7)) | 0;
37246 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37247 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
37248 w7 &= 0x3ffffff;
37249 /* k = 8 */
37250 lo = Math.imul(al8, bl0);
37251 mid = Math.imul(al8, bh0);
37252 mid = (mid + Math.imul(ah8, bl0)) | 0;
37253 hi = Math.imul(ah8, bh0);
37254 lo = (lo + Math.imul(al7, bl1)) | 0;
37255 mid = (mid + Math.imul(al7, bh1)) | 0;
37256 mid = (mid + Math.imul(ah7, bl1)) | 0;
37257 hi = (hi + Math.imul(ah7, bh1)) | 0;
37258 lo = (lo + Math.imul(al6, bl2)) | 0;
37259 mid = (mid + Math.imul(al6, bh2)) | 0;
37260 mid = (mid + Math.imul(ah6, bl2)) | 0;
37261 hi = (hi + Math.imul(ah6, bh2)) | 0;
37262 lo = (lo + Math.imul(al5, bl3)) | 0;
37263 mid = (mid + Math.imul(al5, bh3)) | 0;
37264 mid = (mid + Math.imul(ah5, bl3)) | 0;
37265 hi = (hi + Math.imul(ah5, bh3)) | 0;
37266 lo = (lo + Math.imul(al4, bl4)) | 0;
37267 mid = (mid + Math.imul(al4, bh4)) | 0;
37268 mid = (mid + Math.imul(ah4, bl4)) | 0;
37269 hi = (hi + Math.imul(ah4, bh4)) | 0;
37270 lo = (lo + Math.imul(al3, bl5)) | 0;
37271 mid = (mid + Math.imul(al3, bh5)) | 0;
37272 mid = (mid + Math.imul(ah3, bl5)) | 0;
37273 hi = (hi + Math.imul(ah3, bh5)) | 0;
37274 lo = (lo + Math.imul(al2, bl6)) | 0;
37275 mid = (mid + Math.imul(al2, bh6)) | 0;
37276 mid = (mid + Math.imul(ah2, bl6)) | 0;
37277 hi = (hi + Math.imul(ah2, bh6)) | 0;
37278 lo = (lo + Math.imul(al1, bl7)) | 0;
37279 mid = (mid + Math.imul(al1, bh7)) | 0;
37280 mid = (mid + Math.imul(ah1, bl7)) | 0;
37281 hi = (hi + Math.imul(ah1, bh7)) | 0;
37282 lo = (lo + Math.imul(al0, bl8)) | 0;
37283 mid = (mid + Math.imul(al0, bh8)) | 0;
37284 mid = (mid + Math.imul(ah0, bl8)) | 0;
37285 hi = (hi + Math.imul(ah0, bh8)) | 0;
37286 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37287 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
37288 w8 &= 0x3ffffff;
37289 /* k = 9 */
37290 lo = Math.imul(al9, bl0);
37291 mid = Math.imul(al9, bh0);
37292 mid = (mid + Math.imul(ah9, bl0)) | 0;
37293 hi = Math.imul(ah9, bh0);
37294 lo = (lo + Math.imul(al8, bl1)) | 0;
37295 mid = (mid + Math.imul(al8, bh1)) | 0;
37296 mid = (mid + Math.imul(ah8, bl1)) | 0;
37297 hi = (hi + Math.imul(ah8, bh1)) | 0;
37298 lo = (lo + Math.imul(al7, bl2)) | 0;
37299 mid = (mid + Math.imul(al7, bh2)) | 0;
37300 mid = (mid + Math.imul(ah7, bl2)) | 0;
37301 hi = (hi + Math.imul(ah7, bh2)) | 0;
37302 lo = (lo + Math.imul(al6, bl3)) | 0;
37303 mid = (mid + Math.imul(al6, bh3)) | 0;
37304 mid = (mid + Math.imul(ah6, bl3)) | 0;
37305 hi = (hi + Math.imul(ah6, bh3)) | 0;
37306 lo = (lo + Math.imul(al5, bl4)) | 0;
37307 mid = (mid + Math.imul(al5, bh4)) | 0;
37308 mid = (mid + Math.imul(ah5, bl4)) | 0;
37309 hi = (hi + Math.imul(ah5, bh4)) | 0;
37310 lo = (lo + Math.imul(al4, bl5)) | 0;
37311 mid = (mid + Math.imul(al4, bh5)) | 0;
37312 mid = (mid + Math.imul(ah4, bl5)) | 0;
37313 hi = (hi + Math.imul(ah4, bh5)) | 0;
37314 lo = (lo + Math.imul(al3, bl6)) | 0;
37315 mid = (mid + Math.imul(al3, bh6)) | 0;
37316 mid = (mid + Math.imul(ah3, bl6)) | 0;
37317 hi = (hi + Math.imul(ah3, bh6)) | 0;
37318 lo = (lo + Math.imul(al2, bl7)) | 0;
37319 mid = (mid + Math.imul(al2, bh7)) | 0;
37320 mid = (mid + Math.imul(ah2, bl7)) | 0;
37321 hi = (hi + Math.imul(ah2, bh7)) | 0;
37322 lo = (lo + Math.imul(al1, bl8)) | 0;
37323 mid = (mid + Math.imul(al1, bh8)) | 0;
37324 mid = (mid + Math.imul(ah1, bl8)) | 0;
37325 hi = (hi + Math.imul(ah1, bh8)) | 0;
37326 lo = (lo + Math.imul(al0, bl9)) | 0;
37327 mid = (mid + Math.imul(al0, bh9)) | 0;
37328 mid = (mid + Math.imul(ah0, bl9)) | 0;
37329 hi = (hi + Math.imul(ah0, bh9)) | 0;
37330 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37331 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
37332 w9 &= 0x3ffffff;
37333 /* k = 10 */
37334 lo = Math.imul(al9, bl1);
37335 mid = Math.imul(al9, bh1);
37336 mid = (mid + Math.imul(ah9, bl1)) | 0;
37337 hi = Math.imul(ah9, bh1);
37338 lo = (lo + Math.imul(al8, bl2)) | 0;
37339 mid = (mid + Math.imul(al8, bh2)) | 0;
37340 mid = (mid + Math.imul(ah8, bl2)) | 0;
37341 hi = (hi + Math.imul(ah8, bh2)) | 0;
37342 lo = (lo + Math.imul(al7, bl3)) | 0;
37343 mid = (mid + Math.imul(al7, bh3)) | 0;
37344 mid = (mid + Math.imul(ah7, bl3)) | 0;
37345 hi = (hi + Math.imul(ah7, bh3)) | 0;
37346 lo = (lo + Math.imul(al6, bl4)) | 0;
37347 mid = (mid + Math.imul(al6, bh4)) | 0;
37348 mid = (mid + Math.imul(ah6, bl4)) | 0;
37349 hi = (hi + Math.imul(ah6, bh4)) | 0;
37350 lo = (lo + Math.imul(al5, bl5)) | 0;
37351 mid = (mid + Math.imul(al5, bh5)) | 0;
37352 mid = (mid + Math.imul(ah5, bl5)) | 0;
37353 hi = (hi + Math.imul(ah5, bh5)) | 0;
37354 lo = (lo + Math.imul(al4, bl6)) | 0;
37355 mid = (mid + Math.imul(al4, bh6)) | 0;
37356 mid = (mid + Math.imul(ah4, bl6)) | 0;
37357 hi = (hi + Math.imul(ah4, bh6)) | 0;
37358 lo = (lo + Math.imul(al3, bl7)) | 0;
37359 mid = (mid + Math.imul(al3, bh7)) | 0;
37360 mid = (mid + Math.imul(ah3, bl7)) | 0;
37361 hi = (hi + Math.imul(ah3, bh7)) | 0;
37362 lo = (lo + Math.imul(al2, bl8)) | 0;
37363 mid = (mid + Math.imul(al2, bh8)) | 0;
37364 mid = (mid + Math.imul(ah2, bl8)) | 0;
37365 hi = (hi + Math.imul(ah2, bh8)) | 0;
37366 lo = (lo + Math.imul(al1, bl9)) | 0;
37367 mid = (mid + Math.imul(al1, bh9)) | 0;
37368 mid = (mid + Math.imul(ah1, bl9)) | 0;
37369 hi = (hi + Math.imul(ah1, bh9)) | 0;
37370 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37371 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
37372 w10 &= 0x3ffffff;
37373 /* k = 11 */
37374 lo = Math.imul(al9, bl2);
37375 mid = Math.imul(al9, bh2);
37376 mid = (mid + Math.imul(ah9, bl2)) | 0;
37377 hi = Math.imul(ah9, bh2);
37378 lo = (lo + Math.imul(al8, bl3)) | 0;
37379 mid = (mid + Math.imul(al8, bh3)) | 0;
37380 mid = (mid + Math.imul(ah8, bl3)) | 0;
37381 hi = (hi + Math.imul(ah8, bh3)) | 0;
37382 lo = (lo + Math.imul(al7, bl4)) | 0;
37383 mid = (mid + Math.imul(al7, bh4)) | 0;
37384 mid = (mid + Math.imul(ah7, bl4)) | 0;
37385 hi = (hi + Math.imul(ah7, bh4)) | 0;
37386 lo = (lo + Math.imul(al6, bl5)) | 0;
37387 mid = (mid + Math.imul(al6, bh5)) | 0;
37388 mid = (mid + Math.imul(ah6, bl5)) | 0;
37389 hi = (hi + Math.imul(ah6, bh5)) | 0;
37390 lo = (lo + Math.imul(al5, bl6)) | 0;
37391 mid = (mid + Math.imul(al5, bh6)) | 0;
37392 mid = (mid + Math.imul(ah5, bl6)) | 0;
37393 hi = (hi + Math.imul(ah5, bh6)) | 0;
37394 lo = (lo + Math.imul(al4, bl7)) | 0;
37395 mid = (mid + Math.imul(al4, bh7)) | 0;
37396 mid = (mid + Math.imul(ah4, bl7)) | 0;
37397 hi = (hi + Math.imul(ah4, bh7)) | 0;
37398 lo = (lo + Math.imul(al3, bl8)) | 0;
37399 mid = (mid + Math.imul(al3, bh8)) | 0;
37400 mid = (mid + Math.imul(ah3, bl8)) | 0;
37401 hi = (hi + Math.imul(ah3, bh8)) | 0;
37402 lo = (lo + Math.imul(al2, bl9)) | 0;
37403 mid = (mid + Math.imul(al2, bh9)) | 0;
37404 mid = (mid + Math.imul(ah2, bl9)) | 0;
37405 hi = (hi + Math.imul(ah2, bh9)) | 0;
37406 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37407 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
37408 w11 &= 0x3ffffff;
37409 /* k = 12 */
37410 lo = Math.imul(al9, bl3);
37411 mid = Math.imul(al9, bh3);
37412 mid = (mid + Math.imul(ah9, bl3)) | 0;
37413 hi = Math.imul(ah9, bh3);
37414 lo = (lo + Math.imul(al8, bl4)) | 0;
37415 mid = (mid + Math.imul(al8, bh4)) | 0;
37416 mid = (mid + Math.imul(ah8, bl4)) | 0;
37417 hi = (hi + Math.imul(ah8, bh4)) | 0;
37418 lo = (lo + Math.imul(al7, bl5)) | 0;
37419 mid = (mid + Math.imul(al7, bh5)) | 0;
37420 mid = (mid + Math.imul(ah7, bl5)) | 0;
37421 hi = (hi + Math.imul(ah7, bh5)) | 0;
37422 lo = (lo + Math.imul(al6, bl6)) | 0;
37423 mid = (mid + Math.imul(al6, bh6)) | 0;
37424 mid = (mid + Math.imul(ah6, bl6)) | 0;
37425 hi = (hi + Math.imul(ah6, bh6)) | 0;
37426 lo = (lo + Math.imul(al5, bl7)) | 0;
37427 mid = (mid + Math.imul(al5, bh7)) | 0;
37428 mid = (mid + Math.imul(ah5, bl7)) | 0;
37429 hi = (hi + Math.imul(ah5, bh7)) | 0;
37430 lo = (lo + Math.imul(al4, bl8)) | 0;
37431 mid = (mid + Math.imul(al4, bh8)) | 0;
37432 mid = (mid + Math.imul(ah4, bl8)) | 0;
37433 hi = (hi + Math.imul(ah4, bh8)) | 0;
37434 lo = (lo + Math.imul(al3, bl9)) | 0;
37435 mid = (mid + Math.imul(al3, bh9)) | 0;
37436 mid = (mid + Math.imul(ah3, bl9)) | 0;
37437 hi = (hi + Math.imul(ah3, bh9)) | 0;
37438 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37439 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
37440 w12 &= 0x3ffffff;
37441 /* k = 13 */
37442 lo = Math.imul(al9, bl4);
37443 mid = Math.imul(al9, bh4);
37444 mid = (mid + Math.imul(ah9, bl4)) | 0;
37445 hi = Math.imul(ah9, bh4);
37446 lo = (lo + Math.imul(al8, bl5)) | 0;
37447 mid = (mid + Math.imul(al8, bh5)) | 0;
37448 mid = (mid + Math.imul(ah8, bl5)) | 0;
37449 hi = (hi + Math.imul(ah8, bh5)) | 0;
37450 lo = (lo + Math.imul(al7, bl6)) | 0;
37451 mid = (mid + Math.imul(al7, bh6)) | 0;
37452 mid = (mid + Math.imul(ah7, bl6)) | 0;
37453 hi = (hi + Math.imul(ah7, bh6)) | 0;
37454 lo = (lo + Math.imul(al6, bl7)) | 0;
37455 mid = (mid + Math.imul(al6, bh7)) | 0;
37456 mid = (mid + Math.imul(ah6, bl7)) | 0;
37457 hi = (hi + Math.imul(ah6, bh7)) | 0;
37458 lo = (lo + Math.imul(al5, bl8)) | 0;
37459 mid = (mid + Math.imul(al5, bh8)) | 0;
37460 mid = (mid + Math.imul(ah5, bl8)) | 0;
37461 hi = (hi + Math.imul(ah5, bh8)) | 0;
37462 lo = (lo + Math.imul(al4, bl9)) | 0;
37463 mid = (mid + Math.imul(al4, bh9)) | 0;
37464 mid = (mid + Math.imul(ah4, bl9)) | 0;
37465 hi = (hi + Math.imul(ah4, bh9)) | 0;
37466 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37467 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
37468 w13 &= 0x3ffffff;
37469 /* k = 14 */
37470 lo = Math.imul(al9, bl5);
37471 mid = Math.imul(al9, bh5);
37472 mid = (mid + Math.imul(ah9, bl5)) | 0;
37473 hi = Math.imul(ah9, bh5);
37474 lo = (lo + Math.imul(al8, bl6)) | 0;
37475 mid = (mid + Math.imul(al8, bh6)) | 0;
37476 mid = (mid + Math.imul(ah8, bl6)) | 0;
37477 hi = (hi + Math.imul(ah8, bh6)) | 0;
37478 lo = (lo + Math.imul(al7, bl7)) | 0;
37479 mid = (mid + Math.imul(al7, bh7)) | 0;
37480 mid = (mid + Math.imul(ah7, bl7)) | 0;
37481 hi = (hi + Math.imul(ah7, bh7)) | 0;
37482 lo = (lo + Math.imul(al6, bl8)) | 0;
37483 mid = (mid + Math.imul(al6, bh8)) | 0;
37484 mid = (mid + Math.imul(ah6, bl8)) | 0;
37485 hi = (hi + Math.imul(ah6, bh8)) | 0;
37486 lo = (lo + Math.imul(al5, bl9)) | 0;
37487 mid = (mid + Math.imul(al5, bh9)) | 0;
37488 mid = (mid + Math.imul(ah5, bl9)) | 0;
37489 hi = (hi + Math.imul(ah5, bh9)) | 0;
37490 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37491 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
37492 w14 &= 0x3ffffff;
37493 /* k = 15 */
37494 lo = Math.imul(al9, bl6);
37495 mid = Math.imul(al9, bh6);
37496 mid = (mid + Math.imul(ah9, bl6)) | 0;
37497 hi = Math.imul(ah9, bh6);
37498 lo = (lo + Math.imul(al8, bl7)) | 0;
37499 mid = (mid + Math.imul(al8, bh7)) | 0;
37500 mid = (mid + Math.imul(ah8, bl7)) | 0;
37501 hi = (hi + Math.imul(ah8, bh7)) | 0;
37502 lo = (lo + Math.imul(al7, bl8)) | 0;
37503 mid = (mid + Math.imul(al7, bh8)) | 0;
37504 mid = (mid + Math.imul(ah7, bl8)) | 0;
37505 hi = (hi + Math.imul(ah7, bh8)) | 0;
37506 lo = (lo + Math.imul(al6, bl9)) | 0;
37507 mid = (mid + Math.imul(al6, bh9)) | 0;
37508 mid = (mid + Math.imul(ah6, bl9)) | 0;
37509 hi = (hi + Math.imul(ah6, bh9)) | 0;
37510 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37511 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
37512 w15 &= 0x3ffffff;
37513 /* k = 16 */
37514 lo = Math.imul(al9, bl7);
37515 mid = Math.imul(al9, bh7);
37516 mid = (mid + Math.imul(ah9, bl7)) | 0;
37517 hi = Math.imul(ah9, bh7);
37518 lo = (lo + Math.imul(al8, bl8)) | 0;
37519 mid = (mid + Math.imul(al8, bh8)) | 0;
37520 mid = (mid + Math.imul(ah8, bl8)) | 0;
37521 hi = (hi + Math.imul(ah8, bh8)) | 0;
37522 lo = (lo + Math.imul(al7, bl9)) | 0;
37523 mid = (mid + Math.imul(al7, bh9)) | 0;
37524 mid = (mid + Math.imul(ah7, bl9)) | 0;
37525 hi = (hi + Math.imul(ah7, bh9)) | 0;
37526 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37527 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
37528 w16 &= 0x3ffffff;
37529 /* k = 17 */
37530 lo = Math.imul(al9, bl8);
37531 mid = Math.imul(al9, bh8);
37532 mid = (mid + Math.imul(ah9, bl8)) | 0;
37533 hi = Math.imul(ah9, bh8);
37534 lo = (lo + Math.imul(al8, bl9)) | 0;
37535 mid = (mid + Math.imul(al8, bh9)) | 0;
37536 mid = (mid + Math.imul(ah8, bl9)) | 0;
37537 hi = (hi + Math.imul(ah8, bh9)) | 0;
37538 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37539 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
37540 w17 &= 0x3ffffff;
37541 /* k = 18 */
37542 lo = Math.imul(al9, bl9);
37543 mid = Math.imul(al9, bh9);
37544 mid = (mid + Math.imul(ah9, bl9)) | 0;
37545 hi = Math.imul(ah9, bh9);
37546 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
37547 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
37548 w18 &= 0x3ffffff;
37549 o[0] = w0;
37550 o[1] = w1;
37551 o[2] = w2;
37552 o[3] = w3;
37553 o[4] = w4;
37554 o[5] = w5;
37555 o[6] = w6;
37556 o[7] = w7;
37557 o[8] = w8;
37558 o[9] = w9;
37559 o[10] = w10;
37560 o[11] = w11;
37561 o[12] = w12;
37562 o[13] = w13;
37563 o[14] = w14;
37564 o[15] = w15;
37565 o[16] = w16;
37566 o[17] = w17;
37567 o[18] = w18;
37568 if (c !== 0) {
37569 o[19] = c;
37570 out.length++;
37571 }
37572 return out;
37573 };
37574
37575 // Polyfill comb
37576 if (!Math.imul) {
37577 comb10MulTo = smallMulTo;
37578 }
37579
37580 function bigMulTo (self, num, out) {
37581 out.negative = num.negative ^ self.negative;
37582 out.length = self.length + num.length;
37583
37584 var carry = 0;
37585 var hncarry = 0;
37586 for (var k = 0; k < out.length - 1; k++) {
37587 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
37588 // note that ncarry could be >= 0x3ffffff
37589 var ncarry = hncarry;
37590 hncarry = 0;
37591 var rword = carry & 0x3ffffff;
37592 var maxJ = Math.min(k, num.length - 1);
37593 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
37594 var i = k - j;
37595 var a = self.words[i] | 0;
37596 var b = num.words[j] | 0;
37597 var r = a * b;
37598
37599 var lo = r & 0x3ffffff;
37600 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
37601 lo = (lo + rword) | 0;
37602 rword = lo & 0x3ffffff;
37603 ncarry = (ncarry + (lo >>> 26)) | 0;
37604
37605 hncarry += ncarry >>> 26;
37606 ncarry &= 0x3ffffff;
37607 }
37608 out.words[k] = rword;
37609 carry = ncarry;
37610 ncarry = hncarry;
37611 }
37612 if (carry !== 0) {
37613 out.words[k] = carry;
37614 } else {
37615 out.length--;
37616 }
37617
37618 return out.strip();
37619 }
37620
37621 function jumboMulTo (self, num, out) {
37622 var fftm = new FFTM();
37623 return fftm.mulp(self, num, out);
37624 }
37625
37626 BN.prototype.mulTo = function mulTo (num, out) {
37627 var res;
37628 var len = this.length + num.length;
37629 if (this.length === 10 && num.length === 10) {
37630 res = comb10MulTo(this, num, out);
37631 } else if (len < 63) {
37632 res = smallMulTo(this, num, out);
37633 } else if (len < 1024) {
37634 res = bigMulTo(this, num, out);
37635 } else {
37636 res = jumboMulTo(this, num, out);
37637 }
37638
37639 return res;
37640 };
37641
37642 // Cooley-Tukey algorithm for FFT
37643 // slightly revisited to rely on looping instead of recursion
37644
37645 function FFTM (x, y) {
37646 this.x = x;
37647 this.y = y;
37648 }
37649
37650 FFTM.prototype.makeRBT = function makeRBT (N) {
37651 var t = new Array(N);
37652 var l = BN.prototype._countBits(N) - 1;
37653 for (var i = 0; i < N; i++) {
37654 t[i] = this.revBin(i, l, N);
37655 }
37656
37657 return t;
37658 };
37659
37660 // Returns binary-reversed representation of `x`
37661 FFTM.prototype.revBin = function revBin (x, l, N) {
37662 if (x === 0 || x === N - 1) return x;
37663
37664 var rb = 0;
37665 for (var i = 0; i < l; i++) {
37666 rb |= (x & 1) << (l - i - 1);
37667 x >>= 1;
37668 }
37669
37670 return rb;
37671 };
37672
37673 // Performs "tweedling" phase, therefore 'emulating'
37674 // behaviour of the recursive algorithm
37675 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
37676 for (var i = 0; i < N; i++) {
37677 rtws[i] = rws[rbt[i]];
37678 itws[i] = iws[rbt[i]];
37679 }
37680 };
37681
37682 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
37683 this.permute(rbt, rws, iws, rtws, itws, N);
37684
37685 for (var s = 1; s < N; s <<= 1) {
37686 var l = s << 1;
37687
37688 var rtwdf = Math.cos(2 * Math.PI / l);
37689 var itwdf = Math.sin(2 * Math.PI / l);
37690
37691 for (var p = 0; p < N; p += l) {
37692 var rtwdf_ = rtwdf;
37693 var itwdf_ = itwdf;
37694
37695 for (var j = 0; j < s; j++) {
37696 var re = rtws[p + j];
37697 var ie = itws[p + j];
37698
37699 var ro = rtws[p + j + s];
37700 var io = itws[p + j + s];
37701
37702 var rx = rtwdf_ * ro - itwdf_ * io;
37703
37704 io = rtwdf_ * io + itwdf_ * ro;
37705 ro = rx;
37706
37707 rtws[p + j] = re + ro;
37708 itws[p + j] = ie + io;
37709
37710 rtws[p + j + s] = re - ro;
37711 itws[p + j + s] = ie - io;
37712
37713 /* jshint maxdepth : false */
37714 if (j !== l) {
37715 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
37716
37717 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
37718 rtwdf_ = rx;
37719 }
37720 }
37721 }
37722 }
37723 };
37724
37725 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
37726 var N = Math.max(m, n) | 1;
37727 var odd = N & 1;
37728 var i = 0;
37729 for (N = N / 2 | 0; N; N = N >>> 1) {
37730 i++;
37731 }
37732
37733 return 1 << i + 1 + odd;
37734 };
37735
37736 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
37737 if (N <= 1) return;
37738
37739 for (var i = 0; i < N / 2; i++) {
37740 var t = rws[i];
37741
37742 rws[i] = rws[N - i - 1];
37743 rws[N - i - 1] = t;
37744
37745 t = iws[i];
37746
37747 iws[i] = -iws[N - i - 1];
37748 iws[N - i - 1] = -t;
37749 }
37750 };
37751
37752 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
37753 var carry = 0;
37754 for (var i = 0; i < N / 2; i++) {
37755 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
37756 Math.round(ws[2 * i] / N) +
37757 carry;
37758
37759 ws[i] = w & 0x3ffffff;
37760
37761 if (w < 0x4000000) {
37762 carry = 0;
37763 } else {
37764 carry = w / 0x4000000 | 0;
37765 }
37766 }
37767
37768 return ws;
37769 };
37770
37771 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
37772 var carry = 0;
37773 for (var i = 0; i < len; i++) {
37774 carry = carry + (ws[i] | 0);
37775
37776 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
37777 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
37778 }
37779
37780 // Pad with zeroes
37781 for (i = 2 * len; i < N; ++i) {
37782 rws[i] = 0;
37783 }
37784
37785 assert(carry === 0);
37786 assert((carry & ~0x1fff) === 0);
37787 };
37788
37789 FFTM.prototype.stub = function stub (N) {
37790 var ph = new Array(N);
37791 for (var i = 0; i < N; i++) {
37792 ph[i] = 0;
37793 }
37794
37795 return ph;
37796 };
37797
37798 FFTM.prototype.mulp = function mulp (x, y, out) {
37799 var N = 2 * this.guessLen13b(x.length, y.length);
37800
37801 var rbt = this.makeRBT(N);
37802
37803 var _ = this.stub(N);
37804
37805 var rws = new Array(N);
37806 var rwst = new Array(N);
37807 var iwst = new Array(N);
37808
37809 var nrws = new Array(N);
37810 var nrwst = new Array(N);
37811 var niwst = new Array(N);
37812
37813 var rmws = out.words;
37814 rmws.length = N;
37815
37816 this.convert13b(x.words, x.length, rws, N);
37817 this.convert13b(y.words, y.length, nrws, N);
37818
37819 this.transform(rws, _, rwst, iwst, N, rbt);
37820 this.transform(nrws, _, nrwst, niwst, N, rbt);
37821
37822 for (var i = 0; i < N; i++) {
37823 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
37824 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
37825 rwst[i] = rx;
37826 }
37827
37828 this.conjugate(rwst, iwst, N);
37829 this.transform(rwst, iwst, rmws, _, N, rbt);
37830 this.conjugate(rmws, _, N);
37831 this.normalize13b(rmws, N);
37832
37833 out.negative = x.negative ^ y.negative;
37834 out.length = x.length + y.length;
37835 return out.strip();
37836 };
37837
37838 // Multiply `this` by `num`
37839 BN.prototype.mul = function mul (num) {
37840 var out = new BN(null);
37841 out.words = new Array(this.length + num.length);
37842 return this.mulTo(num, out);
37843 };
37844
37845 // Multiply employing FFT
37846 BN.prototype.mulf = function mulf (num) {
37847 var out = new BN(null);
37848 out.words = new Array(this.length + num.length);
37849 return jumboMulTo(this, num, out);
37850 };
37851
37852 // In-place Multiplication
37853 BN.prototype.imul = function imul (num) {
37854 return this.clone().mulTo(num, this);
37855 };
37856
37857 BN.prototype.imuln = function imuln (num) {
37858 assert(typeof num === 'number');
37859 assert(num < 0x4000000);
37860
37861 // Carry
37862 var carry = 0;
37863 for (var i = 0; i < this.length; i++) {
37864 var w = (this.words[i] | 0) * num;
37865 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
37866 carry >>= 26;
37867 carry += (w / 0x4000000) | 0;
37868 // NOTE: lo is 27bit maximum
37869 carry += lo >>> 26;
37870 this.words[i] = lo & 0x3ffffff;
37871 }
37872
37873 if (carry !== 0) {
37874 this.words[i] = carry;
37875 this.length++;
37876 }
37877
37878 return this;
37879 };
37880
37881 BN.prototype.muln = function muln (num) {
37882 return this.clone().imuln(num);
37883 };
37884
37885 // `this` * `this`
37886 BN.prototype.sqr = function sqr () {
37887 return this.mul(this);
37888 };
37889
37890 // `this` * `this` in-place
37891 BN.prototype.isqr = function isqr () {
37892 return this.imul(this.clone());
37893 };
37894
37895 // Math.pow(`this`, `num`)
37896 BN.prototype.pow = function pow (num) {
37897 var w = toBitArray(num);
37898 if (w.length === 0) return new BN(1);
37899
37900 // Skip leading zeroes
37901 var res = this;
37902 for (var i = 0; i < w.length; i++, res = res.sqr()) {
37903 if (w[i] !== 0) break;
37904 }
37905
37906 if (++i < w.length) {
37907 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
37908 if (w[i] === 0) continue;
37909
37910 res = res.mul(q);
37911 }
37912 }
37913
37914 return res;
37915 };
37916
37917 // Shift-left in-place
37918 BN.prototype.iushln = function iushln (bits) {
37919 assert(typeof bits === 'number' && bits >= 0);
37920 var r = bits % 26;
37921 var s = (bits - r) / 26;
37922 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
37923 var i;
37924
37925 if (r !== 0) {
37926 var carry = 0;
37927
37928 for (i = 0; i < this.length; i++) {
37929 var newCarry = this.words[i] & carryMask;
37930 var c = ((this.words[i] | 0) - newCarry) << r;
37931 this.words[i] = c | carry;
37932 carry = newCarry >>> (26 - r);
37933 }
37934
37935 if (carry) {
37936 this.words[i] = carry;
37937 this.length++;
37938 }
37939 }
37940
37941 if (s !== 0) {
37942 for (i = this.length - 1; i >= 0; i--) {
37943 this.words[i + s] = this.words[i];
37944 }
37945
37946 for (i = 0; i < s; i++) {
37947 this.words[i] = 0;
37948 }
37949
37950 this.length += s;
37951 }
37952
37953 return this.strip();
37954 };
37955
37956 BN.prototype.ishln = function ishln (bits) {
37957 // TODO(indutny): implement me
37958 assert(this.negative === 0);
37959 return this.iushln(bits);
37960 };
37961
37962 // Shift-right in-place
37963 // NOTE: `hint` is a lowest bit before trailing zeroes
37964 // NOTE: if `extended` is present - it will be filled with destroyed bits
37965 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
37966 assert(typeof bits === 'number' && bits >= 0);
37967 var h;
37968 if (hint) {
37969 h = (hint - (hint % 26)) / 26;
37970 } else {
37971 h = 0;
37972 }
37973
37974 var r = bits % 26;
37975 var s = Math.min((bits - r) / 26, this.length);
37976 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
37977 var maskedWords = extended;
37978
37979 h -= s;
37980 h = Math.max(0, h);
37981
37982 // Extended mode, copy masked part
37983 if (maskedWords) {
37984 for (var i = 0; i < s; i++) {
37985 maskedWords.words[i] = this.words[i];
37986 }
37987 maskedWords.length = s;
37988 }
37989
37990 if (s === 0) ; else if (this.length > s) {
37991 this.length -= s;
37992 for (i = 0; i < this.length; i++) {
37993 this.words[i] = this.words[i + s];
37994 }
37995 } else {
37996 this.words[0] = 0;
37997 this.length = 1;
37998 }
37999
38000 var carry = 0;
38001 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
38002 var word = this.words[i] | 0;
38003 this.words[i] = (carry << (26 - r)) | (word >>> r);
38004 carry = word & mask;
38005 }
38006
38007 // Push carried bits as a mask
38008 if (maskedWords && carry !== 0) {
38009 maskedWords.words[maskedWords.length++] = carry;
38010 }
38011
38012 if (this.length === 0) {
38013 this.words[0] = 0;
38014 this.length = 1;
38015 }
38016
38017 return this.strip();
38018 };
38019
38020 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
38021 // TODO(indutny): implement me
38022 assert(this.negative === 0);
38023 return this.iushrn(bits, hint, extended);
38024 };
38025
38026 // Shift-left
38027 BN.prototype.shln = function shln (bits) {
38028 return this.clone().ishln(bits);
38029 };
38030
38031 BN.prototype.ushln = function ushln (bits) {
38032 return this.clone().iushln(bits);
38033 };
38034
38035 // Shift-right
38036 BN.prototype.shrn = function shrn (bits) {
38037 return this.clone().ishrn(bits);
38038 };
38039
38040 BN.prototype.ushrn = function ushrn (bits) {
38041 return this.clone().iushrn(bits);
38042 };
38043
38044 // Test if n bit is set
38045 BN.prototype.testn = function testn (bit) {
38046 assert(typeof bit === 'number' && bit >= 0);
38047 var r = bit % 26;
38048 var s = (bit - r) / 26;
38049 var q = 1 << r;
38050
38051 // Fast case: bit is much higher than all existing words
38052 if (this.length <= s) return false;
38053
38054 // Check bit and return
38055 var w = this.words[s];
38056
38057 return !!(w & q);
38058 };
38059
38060 // Return only lowers bits of number (in-place)
38061 BN.prototype.imaskn = function imaskn (bits) {
38062 assert(typeof bits === 'number' && bits >= 0);
38063 var r = bits % 26;
38064 var s = (bits - r) / 26;
38065
38066 assert(this.negative === 0, 'imaskn works only with positive numbers');
38067
38068 if (this.length <= s) {
38069 return this;
38070 }
38071
38072 if (r !== 0) {
38073 s++;
38074 }
38075 this.length = Math.min(s, this.length);
38076
38077 if (r !== 0) {
38078 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
38079 this.words[this.length - 1] &= mask;
38080 }
38081
38082 return this.strip();
38083 };
38084
38085 // Return only lowers bits of number
38086 BN.prototype.maskn = function maskn (bits) {
38087 return this.clone().imaskn(bits);
38088 };
38089
38090 // Add plain number `num` to `this`
38091 BN.prototype.iaddn = function iaddn (num) {
38092 assert(typeof num === 'number');
38093 assert(num < 0x4000000);
38094 if (num < 0) return this.isubn(-num);
38095
38096 // Possible sign change
38097 if (this.negative !== 0) {
38098 if (this.length === 1 && (this.words[0] | 0) < num) {
38099 this.words[0] = num - (this.words[0] | 0);
38100 this.negative = 0;
38101 return this;
38102 }
38103
38104 this.negative = 0;
38105 this.isubn(num);
38106 this.negative = 1;
38107 return this;
38108 }
38109
38110 // Add without checks
38111 return this._iaddn(num);
38112 };
38113
38114 BN.prototype._iaddn = function _iaddn (num) {
38115 this.words[0] += num;
38116
38117 // Carry
38118 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
38119 this.words[i] -= 0x4000000;
38120 if (i === this.length - 1) {
38121 this.words[i + 1] = 1;
38122 } else {
38123 this.words[i + 1]++;
38124 }
38125 }
38126 this.length = Math.max(this.length, i + 1);
38127
38128 return this;
38129 };
38130
38131 // Subtract plain number `num` from `this`
38132 BN.prototype.isubn = function isubn (num) {
38133 assert(typeof num === 'number');
38134 assert(num < 0x4000000);
38135 if (num < 0) return this.iaddn(-num);
38136
38137 if (this.negative !== 0) {
38138 this.negative = 0;
38139 this.iaddn(num);
38140 this.negative = 1;
38141 return this;
38142 }
38143
38144 this.words[0] -= num;
38145
38146 if (this.length === 1 && this.words[0] < 0) {
38147 this.words[0] = -this.words[0];
38148 this.negative = 1;
38149 } else {
38150 // Carry
38151 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
38152 this.words[i] += 0x4000000;
38153 this.words[i + 1] -= 1;
38154 }
38155 }
38156
38157 return this.strip();
38158 };
38159
38160 BN.prototype.addn = function addn (num) {
38161 return this.clone().iaddn(num);
38162 };
38163
38164 BN.prototype.subn = function subn (num) {
38165 return this.clone().isubn(num);
38166 };
38167
38168 BN.prototype.iabs = function iabs () {
38169 this.negative = 0;
38170
38171 return this;
38172 };
38173
38174 BN.prototype.abs = function abs () {
38175 return this.clone().iabs();
38176 };
38177
38178 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
38179 var len = num.length + shift;
38180 var i;
38181
38182 this._expand(len);
38183
38184 var w;
38185 var carry = 0;
38186 for (i = 0; i < num.length; i++) {
38187 w = (this.words[i + shift] | 0) + carry;
38188 var right = (num.words[i] | 0) * mul;
38189 w -= right & 0x3ffffff;
38190 carry = (w >> 26) - ((right / 0x4000000) | 0);
38191 this.words[i + shift] = w & 0x3ffffff;
38192 }
38193 for (; i < this.length - shift; i++) {
38194 w = (this.words[i + shift] | 0) + carry;
38195 carry = w >> 26;
38196 this.words[i + shift] = w & 0x3ffffff;
38197 }
38198
38199 if (carry === 0) return this.strip();
38200
38201 // Subtraction overflow
38202 assert(carry === -1);
38203 carry = 0;
38204 for (i = 0; i < this.length; i++) {
38205 w = -(this.words[i] | 0) + carry;
38206 carry = w >> 26;
38207 this.words[i] = w & 0x3ffffff;
38208 }
38209 this.negative = 1;
38210
38211 return this.strip();
38212 };
38213
38214 BN.prototype._wordDiv = function _wordDiv (num, mode) {
38215 var shift = this.length - num.length;
38216
38217 var a = this.clone();
38218 var b = num;
38219
38220 // Normalize
38221 var bhi = b.words[b.length - 1] | 0;
38222 var bhiBits = this._countBits(bhi);
38223 shift = 26 - bhiBits;
38224 if (shift !== 0) {
38225 b = b.ushln(shift);
38226 a.iushln(shift);
38227 bhi = b.words[b.length - 1] | 0;
38228 }
38229
38230 // Initialize quotient
38231 var m = a.length - b.length;
38232 var q;
38233
38234 if (mode !== 'mod') {
38235 q = new BN(null);
38236 q.length = m + 1;
38237 q.words = new Array(q.length);
38238 for (var i = 0; i < q.length; i++) {
38239 q.words[i] = 0;
38240 }
38241 }
38242
38243 var diff = a.clone()._ishlnsubmul(b, 1, m);
38244 if (diff.negative === 0) {
38245 a = diff;
38246 if (q) {
38247 q.words[m] = 1;
38248 }
38249 }
38250
38251 for (var j = m - 1; j >= 0; j--) {
38252 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
38253 (a.words[b.length + j - 1] | 0);
38254
38255 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
38256 // (0x7ffffff)
38257 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
38258
38259 a._ishlnsubmul(b, qj, j);
38260 while (a.negative !== 0) {
38261 qj--;
38262 a.negative = 0;
38263 a._ishlnsubmul(b, 1, j);
38264 if (!a.isZero()) {
38265 a.negative ^= 1;
38266 }
38267 }
38268 if (q) {
38269 q.words[j] = qj;
38270 }
38271 }
38272 if (q) {
38273 q.strip();
38274 }
38275 a.strip();
38276
38277 // Denormalize
38278 if (mode !== 'div' && shift !== 0) {
38279 a.iushrn(shift);
38280 }
38281
38282 return {
38283 div: q || null,
38284 mod: a
38285 };
38286 };
38287
38288 // NOTE: 1) `mode` can be set to `mod` to request mod only,
38289 // to `div` to request div only, or be absent to
38290 // request both div & mod
38291 // 2) `positive` is true if unsigned mod is requested
38292 BN.prototype.divmod = function divmod (num, mode, positive) {
38293 assert(!num.isZero());
38294
38295 if (this.isZero()) {
38296 return {
38297 div: new BN(0),
38298 mod: new BN(0)
38299 };
38300 }
38301
38302 var div, mod, res;
38303 if (this.negative !== 0 && num.negative === 0) {
38304 res = this.neg().divmod(num, mode);
38305
38306 if (mode !== 'mod') {
38307 div = res.div.neg();
38308 }
38309
38310 if (mode !== 'div') {
38311 mod = res.mod.neg();
38312 if (positive && mod.negative !== 0) {
38313 mod.iadd(num);
38314 }
38315 }
38316
38317 return {
38318 div: div,
38319 mod: mod
38320 };
38321 }
38322
38323 if (this.negative === 0 && num.negative !== 0) {
38324 res = this.divmod(num.neg(), mode);
38325
38326 if (mode !== 'mod') {
38327 div = res.div.neg();
38328 }
38329
38330 return {
38331 div: div,
38332 mod: res.mod
38333 };
38334 }
38335
38336 if ((this.negative & num.negative) !== 0) {
38337 res = this.neg().divmod(num.neg(), mode);
38338
38339 if (mode !== 'div') {
38340 mod = res.mod.neg();
38341 if (positive && mod.negative !== 0) {
38342 mod.isub(num);
38343 }
38344 }
38345
38346 return {
38347 div: res.div,
38348 mod: mod
38349 };
38350 }
38351
38352 // Both numbers are positive at this point
38353
38354 // Strip both numbers to approximate shift value
38355 if (num.length > this.length || this.cmp(num) < 0) {
38356 return {
38357 div: new BN(0),
38358 mod: this
38359 };
38360 }
38361
38362 // Very short reduction
38363 if (num.length === 1) {
38364 if (mode === 'div') {
38365 return {
38366 div: this.divn(num.words[0]),
38367 mod: null
38368 };
38369 }
38370
38371 if (mode === 'mod') {
38372 return {
38373 div: null,
38374 mod: new BN(this.modn(num.words[0]))
38375 };
38376 }
38377
38378 return {
38379 div: this.divn(num.words[0]),
38380 mod: new BN(this.modn(num.words[0]))
38381 };
38382 }
38383
38384 return this._wordDiv(num, mode);
38385 };
38386
38387 // Find `this` / `num`
38388 BN.prototype.div = function div (num) {
38389 return this.divmod(num, 'div', false).div;
38390 };
38391
38392 // Find `this` % `num`
38393 BN.prototype.mod = function mod (num) {
38394 return this.divmod(num, 'mod', false).mod;
38395 };
38396
38397 BN.prototype.umod = function umod (num) {
38398 return this.divmod(num, 'mod', true).mod;
38399 };
38400
38401 // Find Round(`this` / `num`)
38402 BN.prototype.divRound = function divRound (num) {
38403 var dm = this.divmod(num);
38404
38405 // Fast case - exact division
38406 if (dm.mod.isZero()) return dm.div;
38407
38408 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
38409
38410 var half = num.ushrn(1);
38411 var r2 = num.andln(1);
38412 var cmp = mod.cmp(half);
38413
38414 // Round down
38415 if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
38416
38417 // Round up
38418 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
38419 };
38420
38421 BN.prototype.modn = function modn (num) {
38422 assert(num <= 0x3ffffff);
38423 var p = (1 << 26) % num;
38424
38425 var acc = 0;
38426 for (var i = this.length - 1; i >= 0; i--) {
38427 acc = (p * acc + (this.words[i] | 0)) % num;
38428 }
38429
38430 return acc;
38431 };
38432
38433 // In-place division by number
38434 BN.prototype.idivn = function idivn (num) {
38435 assert(num <= 0x3ffffff);
38436
38437 var carry = 0;
38438 for (var i = this.length - 1; i >= 0; i--) {
38439 var w = (this.words[i] | 0) + carry * 0x4000000;
38440 this.words[i] = (w / num) | 0;
38441 carry = w % num;
38442 }
38443
38444 return this.strip();
38445 };
38446
38447 BN.prototype.divn = function divn (num) {
38448 return this.clone().idivn(num);
38449 };
38450
38451 BN.prototype.egcd = function egcd (p) {
38452 assert(p.negative === 0);
38453 assert(!p.isZero());
38454
38455 var x = this;
38456 var y = p.clone();
38457
38458 if (x.negative !== 0) {
38459 x = x.umod(p);
38460 } else {
38461 x = x.clone();
38462 }
38463
38464 // A * x + B * y = x
38465 var A = new BN(1);
38466 var B = new BN(0);
38467
38468 // C * x + D * y = y
38469 var C = new BN(0);
38470 var D = new BN(1);
38471
38472 var g = 0;
38473
38474 while (x.isEven() && y.isEven()) {
38475 x.iushrn(1);
38476 y.iushrn(1);
38477 ++g;
38478 }
38479
38480 var yp = y.clone();
38481 var xp = x.clone();
38482
38483 while (!x.isZero()) {
38484 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
38485 if (i > 0) {
38486 x.iushrn(i);
38487 while (i-- > 0) {
38488 if (A.isOdd() || B.isOdd()) {
38489 A.iadd(yp);
38490 B.isub(xp);
38491 }
38492
38493 A.iushrn(1);
38494 B.iushrn(1);
38495 }
38496 }
38497
38498 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
38499 if (j > 0) {
38500 y.iushrn(j);
38501 while (j-- > 0) {
38502 if (C.isOdd() || D.isOdd()) {
38503 C.iadd(yp);
38504 D.isub(xp);
38505 }
38506
38507 C.iushrn(1);
38508 D.iushrn(1);
38509 }
38510 }
38511
38512 if (x.cmp(y) >= 0) {
38513 x.isub(y);
38514 A.isub(C);
38515 B.isub(D);
38516 } else {
38517 y.isub(x);
38518 C.isub(A);
38519 D.isub(B);
38520 }
38521 }
38522
38523 return {
38524 a: C,
38525 b: D,
38526 gcd: y.iushln(g)
38527 };
38528 };
38529
38530 // This is reduced incarnation of the binary EEA
38531 // above, designated to invert members of the
38532 // _prime_ fields F(p) at a maximal speed
38533 BN.prototype._invmp = function _invmp (p) {
38534 assert(p.negative === 0);
38535 assert(!p.isZero());
38536
38537 var a = this;
38538 var b = p.clone();
38539
38540 if (a.negative !== 0) {
38541 a = a.umod(p);
38542 } else {
38543 a = a.clone();
38544 }
38545
38546 var x1 = new BN(1);
38547 var x2 = new BN(0);
38548
38549 var delta = b.clone();
38550
38551 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
38552 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
38553 if (i > 0) {
38554 a.iushrn(i);
38555 while (i-- > 0) {
38556 if (x1.isOdd()) {
38557 x1.iadd(delta);
38558 }
38559
38560 x1.iushrn(1);
38561 }
38562 }
38563
38564 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
38565 if (j > 0) {
38566 b.iushrn(j);
38567 while (j-- > 0) {
38568 if (x2.isOdd()) {
38569 x2.iadd(delta);
38570 }
38571
38572 x2.iushrn(1);
38573 }
38574 }
38575
38576 if (a.cmp(b) >= 0) {
38577 a.isub(b);
38578 x1.isub(x2);
38579 } else {
38580 b.isub(a);
38581 x2.isub(x1);
38582 }
38583 }
38584
38585 var res;
38586 if (a.cmpn(1) === 0) {
38587 res = x1;
38588 } else {
38589 res = x2;
38590 }
38591
38592 if (res.cmpn(0) < 0) {
38593 res.iadd(p);
38594 }
38595
38596 return res;
38597 };
38598
38599 BN.prototype.gcd = function gcd (num) {
38600 if (this.isZero()) return num.abs();
38601 if (num.isZero()) return this.abs();
38602
38603 var a = this.clone();
38604 var b = num.clone();
38605 a.negative = 0;
38606 b.negative = 0;
38607
38608 // Remove common factor of two
38609 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
38610 a.iushrn(1);
38611 b.iushrn(1);
38612 }
38613
38614 do {
38615 while (a.isEven()) {
38616 a.iushrn(1);
38617 }
38618 while (b.isEven()) {
38619 b.iushrn(1);
38620 }
38621
38622 var r = a.cmp(b);
38623 if (r < 0) {
38624 // Swap `a` and `b` to make `a` always bigger than `b`
38625 var t = a;
38626 a = b;
38627 b = t;
38628 } else if (r === 0 || b.cmpn(1) === 0) {
38629 break;
38630 }
38631
38632 a.isub(b);
38633 } while (true);
38634
38635 return b.iushln(shift);
38636 };
38637
38638 // Invert number in the field F(num)
38639 BN.prototype.invm = function invm (num) {
38640 return this.egcd(num).a.umod(num);
38641 };
38642
38643 BN.prototype.isEven = function isEven () {
38644 return (this.words[0] & 1) === 0;
38645 };
38646
38647 BN.prototype.isOdd = function isOdd () {
38648 return (this.words[0] & 1) === 1;
38649 };
38650
38651 // And first word and num
38652 BN.prototype.andln = function andln (num) {
38653 return this.words[0] & num;
38654 };
38655
38656 // Increment at the bit position in-line
38657 BN.prototype.bincn = function bincn (bit) {
38658 assert(typeof bit === 'number');
38659 var r = bit % 26;
38660 var s = (bit - r) / 26;
38661 var q = 1 << r;
38662
38663 // Fast case: bit is much higher than all existing words
38664 if (this.length <= s) {
38665 this._expand(s + 1);
38666 this.words[s] |= q;
38667 return this;
38668 }
38669
38670 // Add bit and propagate, if needed
38671 var carry = q;
38672 for (var i = s; carry !== 0 && i < this.length; i++) {
38673 var w = this.words[i] | 0;
38674 w += carry;
38675 carry = w >>> 26;
38676 w &= 0x3ffffff;
38677 this.words[i] = w;
38678 }
38679 if (carry !== 0) {
38680 this.words[i] = carry;
38681 this.length++;
38682 }
38683 return this;
38684 };
38685
38686 BN.prototype.isZero = function isZero () {
38687 return this.length === 1 && this.words[0] === 0;
38688 };
38689
38690 BN.prototype.cmpn = function cmpn (num) {
38691 var negative = num < 0;
38692
38693 if (this.negative !== 0 && !negative) return -1;
38694 if (this.negative === 0 && negative) return 1;
38695
38696 this.strip();
38697
38698 var res;
38699 if (this.length > 1) {
38700 res = 1;
38701 } else {
38702 if (negative) {
38703 num = -num;
38704 }
38705
38706 assert(num <= 0x3ffffff, 'Number is too big');
38707
38708 var w = this.words[0] | 0;
38709 res = w === num ? 0 : w < num ? -1 : 1;
38710 }
38711 if (this.negative !== 0) return -res | 0;
38712 return res;
38713 };
38714
38715 // Compare two numbers and return:
38716 // 1 - if `this` > `num`
38717 // 0 - if `this` == `num`
38718 // -1 - if `this` < `num`
38719 BN.prototype.cmp = function cmp (num) {
38720 if (this.negative !== 0 && num.negative === 0) return -1;
38721 if (this.negative === 0 && num.negative !== 0) return 1;
38722
38723 var res = this.ucmp(num);
38724 if (this.negative !== 0) return -res | 0;
38725 return res;
38726 };
38727
38728 // Unsigned comparison
38729 BN.prototype.ucmp = function ucmp (num) {
38730 // At this point both numbers have the same sign
38731 if (this.length > num.length) return 1;
38732 if (this.length < num.length) return -1;
38733
38734 var res = 0;
38735 for (var i = this.length - 1; i >= 0; i--) {
38736 var a = this.words[i] | 0;
38737 var b = num.words[i] | 0;
38738
38739 if (a === b) continue;
38740 if (a < b) {
38741 res = -1;
38742 } else if (a > b) {
38743 res = 1;
38744 }
38745 break;
38746 }
38747 return res;
38748 };
38749
38750 BN.prototype.gtn = function gtn (num) {
38751 return this.cmpn(num) === 1;
38752 };
38753
38754 BN.prototype.gt = function gt (num) {
38755 return this.cmp(num) === 1;
38756 };
38757
38758 BN.prototype.gten = function gten (num) {
38759 return this.cmpn(num) >= 0;
38760 };
38761
38762 BN.prototype.gte = function gte (num) {
38763 return this.cmp(num) >= 0;
38764 };
38765
38766 BN.prototype.ltn = function ltn (num) {
38767 return this.cmpn(num) === -1;
38768 };
38769
38770 BN.prototype.lt = function lt (num) {
38771 return this.cmp(num) === -1;
38772 };
38773
38774 BN.prototype.lten = function lten (num) {
38775 return this.cmpn(num) <= 0;
38776 };
38777
38778 BN.prototype.lte = function lte (num) {
38779 return this.cmp(num) <= 0;
38780 };
38781
38782 BN.prototype.eqn = function eqn (num) {
38783 return this.cmpn(num) === 0;
38784 };
38785
38786 BN.prototype.eq = function eq (num) {
38787 return this.cmp(num) === 0;
38788 };
38789
38790 //
38791 // A reduce context, could be using montgomery or something better, depending
38792 // on the `m` itself.
38793 //
38794 BN.red = function red (num) {
38795 return new Red(num);
38796 };
38797
38798 BN.prototype.toRed = function toRed (ctx) {
38799 assert(!this.red, 'Already a number in reduction context');
38800 assert(this.negative === 0, 'red works only with positives');
38801 return ctx.convertTo(this)._forceRed(ctx);
38802 };
38803
38804 BN.prototype.fromRed = function fromRed () {
38805 assert(this.red, 'fromRed works only with numbers in reduction context');
38806 return this.red.convertFrom(this);
38807 };
38808
38809 BN.prototype._forceRed = function _forceRed (ctx) {
38810 this.red = ctx;
38811 return this;
38812 };
38813
38814 BN.prototype.forceRed = function forceRed (ctx) {
38815 assert(!this.red, 'Already a number in reduction context');
38816 return this._forceRed(ctx);
38817 };
38818
38819 BN.prototype.redAdd = function redAdd (num) {
38820 assert(this.red, 'redAdd works only with red numbers');
38821 return this.red.add(this, num);
38822 };
38823
38824 BN.prototype.redIAdd = function redIAdd (num) {
38825 assert(this.red, 'redIAdd works only with red numbers');
38826 return this.red.iadd(this, num);
38827 };
38828
38829 BN.prototype.redSub = function redSub (num) {
38830 assert(this.red, 'redSub works only with red numbers');
38831 return this.red.sub(this, num);
38832 };
38833
38834 BN.prototype.redISub = function redISub (num) {
38835 assert(this.red, 'redISub works only with red numbers');
38836 return this.red.isub(this, num);
38837 };
38838
38839 BN.prototype.redShl = function redShl (num) {
38840 assert(this.red, 'redShl works only with red numbers');
38841 return this.red.shl(this, num);
38842 };
38843
38844 BN.prototype.redMul = function redMul (num) {
38845 assert(this.red, 'redMul works only with red numbers');
38846 this.red._verify2(this, num);
38847 return this.red.mul(this, num);
38848 };
38849
38850 BN.prototype.redIMul = function redIMul (num) {
38851 assert(this.red, 'redMul works only with red numbers');
38852 this.red._verify2(this, num);
38853 return this.red.imul(this, num);
38854 };
38855
38856 BN.prototype.redSqr = function redSqr () {
38857 assert(this.red, 'redSqr works only with red numbers');
38858 this.red._verify1(this);
38859 return this.red.sqr(this);
38860 };
38861
38862 BN.prototype.redISqr = function redISqr () {
38863 assert(this.red, 'redISqr works only with red numbers');
38864 this.red._verify1(this);
38865 return this.red.isqr(this);
38866 };
38867
38868 // Square root over p
38869 BN.prototype.redSqrt = function redSqrt () {
38870 assert(this.red, 'redSqrt works only with red numbers');
38871 this.red._verify1(this);
38872 return this.red.sqrt(this);
38873 };
38874
38875 BN.prototype.redInvm = function redInvm () {
38876 assert(this.red, 'redInvm works only with red numbers');
38877 this.red._verify1(this);
38878 return this.red.invm(this);
38879 };
38880
38881 // Return negative clone of `this` % `red modulo`
38882 BN.prototype.redNeg = function redNeg () {
38883 assert(this.red, 'redNeg works only with red numbers');
38884 this.red._verify1(this);
38885 return this.red.neg(this);
38886 };
38887
38888 BN.prototype.redPow = function redPow (num) {
38889 assert(this.red && !num.red, 'redPow(normalNum)');
38890 this.red._verify1(this);
38891 return this.red.pow(this, num);
38892 };
38893
38894 // Prime numbers with efficient reduction
38895 var primes = {
38896 k256: null,
38897 p224: null,
38898 p192: null,
38899 p25519: null
38900 };
38901
38902 // Pseudo-Mersenne prime
38903 function MPrime (name, p) {
38904 // P = 2 ^ N - K
38905 this.name = name;
38906 this.p = new BN(p, 16);
38907 this.n = this.p.bitLength();
38908 this.k = new BN(1).iushln(this.n).isub(this.p);
38909
38910 this.tmp = this._tmp();
38911 }
38912
38913 MPrime.prototype._tmp = function _tmp () {
38914 var tmp = new BN(null);
38915 tmp.words = new Array(Math.ceil(this.n / 13));
38916 return tmp;
38917 };
38918
38919 MPrime.prototype.ireduce = function ireduce (num) {
38920 // Assumes that `num` is less than `P^2`
38921 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
38922 var r = num;
38923 var rlen;
38924
38925 do {
38926 this.split(r, this.tmp);
38927 r = this.imulK(r);
38928 r = r.iadd(this.tmp);
38929 rlen = r.bitLength();
38930 } while (rlen > this.n);
38931
38932 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
38933 if (cmp === 0) {
38934 r.words[0] = 0;
38935 r.length = 1;
38936 } else if (cmp > 0) {
38937 r.isub(this.p);
38938 } else {
38939 r.strip();
38940 }
38941
38942 return r;
38943 };
38944
38945 MPrime.prototype.split = function split (input, out) {
38946 input.iushrn(this.n, 0, out);
38947 };
38948
38949 MPrime.prototype.imulK = function imulK (num) {
38950 return num.imul(this.k);
38951 };
38952
38953 function K256 () {
38954 MPrime.call(
38955 this,
38956 'k256',
38957 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
38958 }
38959 inherits(K256, MPrime);
38960
38961 K256.prototype.split = function split (input, output) {
38962 // 256 = 9 * 26 + 22
38963 var mask = 0x3fffff;
38964
38965 var outLen = Math.min(input.length, 9);
38966 for (var i = 0; i < outLen; i++) {
38967 output.words[i] = input.words[i];
38968 }
38969 output.length = outLen;
38970
38971 if (input.length <= 9) {
38972 input.words[0] = 0;
38973 input.length = 1;
38974 return;
38975 }
38976
38977 // Shift by 9 limbs
38978 var prev = input.words[9];
38979 output.words[output.length++] = prev & mask;
38980
38981 for (i = 10; i < input.length; i++) {
38982 var next = input.words[i] | 0;
38983 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
38984 prev = next;
38985 }
38986 prev >>>= 22;
38987 input.words[i - 10] = prev;
38988 if (prev === 0 && input.length > 10) {
38989 input.length -= 10;
38990 } else {
38991 input.length -= 9;
38992 }
38993 };
38994
38995 K256.prototype.imulK = function imulK (num) {
38996 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
38997 num.words[num.length] = 0;
38998 num.words[num.length + 1] = 0;
38999 num.length += 2;
39000
39001 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
39002 var lo = 0;
39003 for (var i = 0; i < num.length; i++) {
39004 var w = num.words[i] | 0;
39005 lo += w * 0x3d1;
39006 num.words[i] = lo & 0x3ffffff;
39007 lo = w * 0x40 + ((lo / 0x4000000) | 0);
39008 }
39009
39010 // Fast length reduction
39011 if (num.words[num.length - 1] === 0) {
39012 num.length--;
39013 if (num.words[num.length - 1] === 0) {
39014 num.length--;
39015 }
39016 }
39017 return num;
39018 };
39019
39020 function P224 () {
39021 MPrime.call(
39022 this,
39023 'p224',
39024 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
39025 }
39026 inherits(P224, MPrime);
39027
39028 function P192 () {
39029 MPrime.call(
39030 this,
39031 'p192',
39032 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
39033 }
39034 inherits(P192, MPrime);
39035
39036 function P25519 () {
39037 // 2 ^ 255 - 19
39038 MPrime.call(
39039 this,
39040 '25519',
39041 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
39042 }
39043 inherits(P25519, MPrime);
39044
39045 P25519.prototype.imulK = function imulK (num) {
39046 // K = 0x13
39047 var carry = 0;
39048 for (var i = 0; i < num.length; i++) {
39049 var hi = (num.words[i] | 0) * 0x13 + carry;
39050 var lo = hi & 0x3ffffff;
39051 hi >>>= 26;
39052
39053 num.words[i] = lo;
39054 carry = hi;
39055 }
39056 if (carry !== 0) {
39057 num.words[num.length++] = carry;
39058 }
39059 return num;
39060 };
39061
39062 // Exported mostly for testing purposes, use plain name instead
39063 BN._prime = function prime (name) {
39064 // Cached version of prime
39065 if (primes[name]) return primes[name];
39066
39067 var prime;
39068 if (name === 'k256') {
39069 prime = new K256();
39070 } else if (name === 'p224') {
39071 prime = new P224();
39072 } else if (name === 'p192') {
39073 prime = new P192();
39074 } else if (name === 'p25519') {
39075 prime = new P25519();
39076 } else {
39077 throw new Error('Unknown prime ' + name);
39078 }
39079 primes[name] = prime;
39080
39081 return prime;
39082 };
39083
39084 //
39085 // Base reduction engine
39086 //
39087 function Red (m) {
39088 if (typeof m === 'string') {
39089 var prime = BN._prime(m);
39090 this.m = prime.p;
39091 this.prime = prime;
39092 } else {
39093 assert(m.gtn(1), 'modulus must be greater than 1');
39094 this.m = m;
39095 this.prime = null;
39096 }
39097 }
39098
39099 Red.prototype._verify1 = function _verify1 (a) {
39100 assert(a.negative === 0, 'red works only with positives');
39101 assert(a.red, 'red works only with red numbers');
39102 };
39103
39104 Red.prototype._verify2 = function _verify2 (a, b) {
39105 assert((a.negative | b.negative) === 0, 'red works only with positives');
39106 assert(a.red && a.red === b.red,
39107 'red works only with red numbers');
39108 };
39109
39110 Red.prototype.imod = function imod (a) {
39111 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
39112 return a.umod(this.m)._forceRed(this);
39113 };
39114
39115 Red.prototype.neg = function neg (a) {
39116 if (a.isZero()) {
39117 return a.clone();
39118 }
39119
39120 return this.m.sub(a)._forceRed(this);
39121 };
39122
39123 Red.prototype.add = function add (a, b) {
39124 this._verify2(a, b);
39125
39126 var res = a.add(b);
39127 if (res.cmp(this.m) >= 0) {
39128 res.isub(this.m);
39129 }
39130 return res._forceRed(this);
39131 };
39132
39133 Red.prototype.iadd = function iadd (a, b) {
39134 this._verify2(a, b);
39135
39136 var res = a.iadd(b);
39137 if (res.cmp(this.m) >= 0) {
39138 res.isub(this.m);
39139 }
39140 return res;
39141 };
39142
39143 Red.prototype.sub = function sub (a, b) {
39144 this._verify2(a, b);
39145
39146 var res = a.sub(b);
39147 if (res.cmpn(0) < 0) {
39148 res.iadd(this.m);
39149 }
39150 return res._forceRed(this);
39151 };
39152
39153 Red.prototype.isub = function isub (a, b) {
39154 this._verify2(a, b);
39155
39156 var res = a.isub(b);
39157 if (res.cmpn(0) < 0) {
39158 res.iadd(this.m);
39159 }
39160 return res;
39161 };
39162
39163 Red.prototype.shl = function shl (a, num) {
39164 this._verify1(a);
39165 return this.imod(a.ushln(num));
39166 };
39167
39168 Red.prototype.imul = function imul (a, b) {
39169 this._verify2(a, b);
39170 return this.imod(a.imul(b));
39171 };
39172
39173 Red.prototype.mul = function mul (a, b) {
39174 this._verify2(a, b);
39175 return this.imod(a.mul(b));
39176 };
39177
39178 Red.prototype.isqr = function isqr (a) {
39179 return this.imul(a, a.clone());
39180 };
39181
39182 Red.prototype.sqr = function sqr (a) {
39183 return this.mul(a, a);
39184 };
39185
39186 Red.prototype.sqrt = function sqrt (a) {
39187 if (a.isZero()) return a.clone();
39188
39189 var mod3 = this.m.andln(3);
39190 assert(mod3 % 2 === 1);
39191
39192 // Fast case
39193 if (mod3 === 3) {
39194 var pow = this.m.add(new BN(1)).iushrn(2);
39195 return this.pow(a, pow);
39196 }
39197
39198 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
39199 //
39200 // Find Q and S, that Q * 2 ^ S = (P - 1)
39201 var q = this.m.subn(1);
39202 var s = 0;
39203 while (!q.isZero() && q.andln(1) === 0) {
39204 s++;
39205 q.iushrn(1);
39206 }
39207 assert(!q.isZero());
39208
39209 var one = new BN(1).toRed(this);
39210 var nOne = one.redNeg();
39211
39212 // Find quadratic non-residue
39213 // NOTE: Max is such because of generalized Riemann hypothesis.
39214 var lpow = this.m.subn(1).iushrn(1);
39215 var z = this.m.bitLength();
39216 z = new BN(2 * z * z).toRed(this);
39217
39218 while (this.pow(z, lpow).cmp(nOne) !== 0) {
39219 z.redIAdd(nOne);
39220 }
39221
39222 var c = this.pow(z, q);
39223 var r = this.pow(a, q.addn(1).iushrn(1));
39224 var t = this.pow(a, q);
39225 var m = s;
39226 while (t.cmp(one) !== 0) {
39227 var tmp = t;
39228 for (var i = 0; tmp.cmp(one) !== 0; i++) {
39229 tmp = tmp.redSqr();
39230 }
39231 assert(i < m);
39232 var b = this.pow(c, new BN(1).iushln(m - i - 1));
39233
39234 r = r.redMul(b);
39235 c = b.redSqr();
39236 t = t.redMul(c);
39237 m = i;
39238 }
39239
39240 return r;
39241 };
39242
39243 Red.prototype.invm = function invm (a) {
39244 var inv = a._invmp(this.m);
39245 if (inv.negative !== 0) {
39246 inv.negative = 0;
39247 return this.imod(inv).redNeg();
39248 } else {
39249 return this.imod(inv);
39250 }
39251 };
39252
39253 Red.prototype.pow = function pow (a, num) {
39254 if (num.isZero()) return new BN(1).toRed(this);
39255 if (num.cmpn(1) === 0) return a.clone();
39256
39257 var windowSize = 4;
39258 var wnd = new Array(1 << windowSize);
39259 wnd[0] = new BN(1).toRed(this);
39260 wnd[1] = a;
39261 for (var i = 2; i < wnd.length; i++) {
39262 wnd[i] = this.mul(wnd[i - 1], a);
39263 }
39264
39265 var res = wnd[0];
39266 var current = 0;
39267 var currentLen = 0;
39268 var start = num.bitLength() % 26;
39269 if (start === 0) {
39270 start = 26;
39271 }
39272
39273 for (i = num.length - 1; i >= 0; i--) {
39274 var word = num.words[i];
39275 for (var j = start - 1; j >= 0; j--) {
39276 var bit = (word >> j) & 1;
39277 if (res !== wnd[0]) {
39278 res = this.sqr(res);
39279 }
39280
39281 if (bit === 0 && current === 0) {
39282 currentLen = 0;
39283 continue;
39284 }
39285
39286 current <<= 1;
39287 current |= bit;
39288 currentLen++;
39289 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
39290
39291 res = this.mul(res, wnd[current]);
39292 currentLen = 0;
39293 current = 0;
39294 }
39295 start = 26;
39296 }
39297
39298 return res;
39299 };
39300
39301 Red.prototype.convertTo = function convertTo (num) {
39302 var r = num.umod(this.m);
39303
39304 return r === num ? r.clone() : r;
39305 };
39306
39307 Red.prototype.convertFrom = function convertFrom (num) {
39308 var res = num.clone();
39309 res.red = null;
39310 return res;
39311 };
39312
39313 //
39314 // Montgomery method engine
39315 //
39316
39317 BN.mont = function mont (num) {
39318 return new Mont(num);
39319 };
39320
39321 function Mont (m) {
39322 Red.call(this, m);
39323
39324 this.shift = this.m.bitLength();
39325 if (this.shift % 26 !== 0) {
39326 this.shift += 26 - (this.shift % 26);
39327 }
39328
39329 this.r = new BN(1).iushln(this.shift);
39330 this.r2 = this.imod(this.r.sqr());
39331 this.rinv = this.r._invmp(this.m);
39332
39333 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
39334 this.minv = this.minv.umod(this.r);
39335 this.minv = this.r.sub(this.minv);
39336 }
39337 inherits(Mont, Red);
39338
39339 Mont.prototype.convertTo = function convertTo (num) {
39340 return this.imod(num.ushln(this.shift));
39341 };
39342
39343 Mont.prototype.convertFrom = function convertFrom (num) {
39344 var r = this.imod(num.mul(this.rinv));
39345 r.red = null;
39346 return r;
39347 };
39348
39349 Mont.prototype.imul = function imul (a, b) {
39350 if (a.isZero() || b.isZero()) {
39351 a.words[0] = 0;
39352 a.length = 1;
39353 return a;
39354 }
39355
39356 var t = a.imul(b);
39357 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
39358 var u = t.isub(c).iushrn(this.shift);
39359 var res = u;
39360
39361 if (u.cmp(this.m) >= 0) {
39362 res = u.isub(this.m);
39363 } else if (u.cmpn(0) < 0) {
39364 res = u.iadd(this.m);
39365 }
39366
39367 return res._forceRed(this);
39368 };
39369
39370 Mont.prototype.mul = function mul (a, b) {
39371 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
39372
39373 var t = a.mul(b);
39374 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
39375 var u = t.isub(c).iushrn(this.shift);
39376 var res = u;
39377 if (u.cmp(this.m) >= 0) {
39378 res = u.isub(this.m);
39379 } else if (u.cmpn(0) < 0) {
39380 res = u.iadd(this.m);
39381 }
39382
39383 return res._forceRed(this);
39384 };
39385
39386 Mont.prototype.invm = function invm (a) {
39387 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
39388 var res = this.imod(a._invmp(this.m).mul(this.r2));
39389 return res._forceRed(this);
39390 };
39391})(module, commonjsGlobal);
39392});
39393
39394var bn$1 = /*#__PURE__*/Object.freeze({
39395 __proto__: null,
39396 'default': bn,
39397 __moduleExports: bn
39398});
39399
39400/**
39401 * @fileoverview
39402 * BigInteger implementation of basic operations
39403 * Wrapper of bn.js library (wwww.github.com/indutny/bn.js)
39404 * @module biginteger/bn
39405 * @private
39406 */
39407
39408/**
39409 * @private
39410 */
39411class BigInteger$1 {
39412 /**
39413 * Get a BigInteger (input must be big endian for strings and arrays)
39414 * @param {Number|String|Uint8Array} n - Value to convert
39415 * @throws {Error} on undefined input
39416 */
39417 constructor(n) {
39418 if (n === undefined) {
39419 throw new Error('Invalid BigInteger input');
39420 }
39421
39422 this.value = new bn(n);
39423 }
39424
39425 clone() {
39426 const clone = new BigInteger$1(null);
39427 this.value.copy(clone.value);
39428 return clone;
39429 }
39430
39431 /**
39432 * BigInteger increment in place
39433 */
39434 iinc() {
39435 this.value.iadd(new bn(1));
39436 return this;
39437 }
39438
39439 /**
39440 * BigInteger increment
39441 * @returns {BigInteger} this + 1.
39442 */
39443 inc() {
39444 return this.clone().iinc();
39445 }
39446
39447 /**
39448 * BigInteger decrement in place
39449 */
39450 idec() {
39451 this.value.isub(new bn(1));
39452 return this;
39453 }
39454
39455 /**
39456 * BigInteger decrement
39457 * @returns {BigInteger} this - 1.
39458 */
39459 dec() {
39460 return this.clone().idec();
39461 }
39462
39463
39464 /**
39465 * BigInteger addition in place
39466 * @param {BigInteger} x - Value to add
39467 */
39468 iadd(x) {
39469 this.value.iadd(x.value);
39470 return this;
39471 }
39472
39473 /**
39474 * BigInteger addition
39475 * @param {BigInteger} x - Value to add
39476 * @returns {BigInteger} this + x.
39477 */
39478 add(x) {
39479 return this.clone().iadd(x);
39480 }
39481
39482 /**
39483 * BigInteger subtraction in place
39484 * @param {BigInteger} x - Value to subtract
39485 */
39486 isub(x) {
39487 this.value.isub(x.value);
39488 return this;
39489 }
39490
39491 /**
39492 * BigInteger subtraction
39493 * @param {BigInteger} x - Value to subtract
39494 * @returns {BigInteger} this - x.
39495 */
39496 sub(x) {
39497 return this.clone().isub(x);
39498 }
39499
39500 /**
39501 * BigInteger multiplication in place
39502 * @param {BigInteger} x - Value to multiply
39503 */
39504 imul(x) {
39505 this.value.imul(x.value);
39506 return this;
39507 }
39508
39509 /**
39510 * BigInteger multiplication
39511 * @param {BigInteger} x - Value to multiply
39512 * @returns {BigInteger} this * x.
39513 */
39514 mul(x) {
39515 return this.clone().imul(x);
39516 }
39517
39518 /**
39519 * Compute value modulo m, in place
39520 * @param {BigInteger} m - Modulo
39521 */
39522 imod(m) {
39523 this.value = this.value.umod(m.value);
39524 return this;
39525 }
39526
39527 /**
39528 * Compute value modulo m
39529 * @param {BigInteger} m - Modulo
39530 * @returns {BigInteger} this mod m.
39531 */
39532 mod(m) {
39533 return this.clone().imod(m);
39534 }
39535
39536 /**
39537 * Compute modular exponentiation
39538 * Much faster than this.exp(e).mod(n)
39539 * @param {BigInteger} e - Exponent
39540 * @param {BigInteger} n - Modulo
39541 * @returns {BigInteger} this ** e mod n.
39542 */
39543 modExp(e, n) {
39544 // We use either Montgomery or normal reduction context
39545 // Montgomery requires coprime n and R (montogmery multiplier)
39546 // bn.js picks R as power of 2, so n must be odd
39547 const nred = n.isEven() ? bn.red(n.value) : bn.mont(n.value);
39548 const x = this.clone();
39549 x.value = x.value.toRed(nred).redPow(e.value).fromRed();
39550 return x;
39551 }
39552
39553 /**
39554 * Compute the inverse of this value modulo n
39555 * Note: this and and n must be relatively prime
39556 * @param {BigInteger} n - Modulo
39557 * @returns {BigInteger} x such that this*x = 1 mod n
39558 * @throws {Error} if the inverse does not exist
39559 */
39560 modInv(n) {
39561 // invm returns a wrong result if the inverse does not exist
39562 if (!this.gcd(n).isOne()) {
39563 throw new Error('Inverse does not exist');
39564 }
39565 return new BigInteger$1(this.value.invm(n.value));
39566 }
39567
39568 /**
39569 * Compute greatest common divisor between this and n
39570 * @param {BigInteger} n - Operand
39571 * @returns {BigInteger} gcd
39572 */
39573 gcd(n) {
39574 return new BigInteger$1(this.value.gcd(n.value));
39575 }
39576
39577 /**
39578 * Shift this to the left by x, in place
39579 * @param {BigInteger} x - Shift value
39580 */
39581 ileftShift(x) {
39582 this.value.ishln(x.value.toNumber());
39583 return this;
39584 }
39585
39586 /**
39587 * Shift this to the left by x
39588 * @param {BigInteger} x - Shift value
39589 * @returns {BigInteger} this << x.
39590 */
39591 leftShift(x) {
39592 return this.clone().ileftShift(x);
39593 }
39594
39595 /**
39596 * Shift this to the right by x, in place
39597 * @param {BigInteger} x - Shift value
39598 */
39599 irightShift(x) {
39600 this.value.ishrn(x.value.toNumber());
39601 return this;
39602 }
39603
39604 /**
39605 * Shift this to the right by x
39606 * @param {BigInteger} x - Shift value
39607 * @returns {BigInteger} this >> x.
39608 */
39609 rightShift(x) {
39610 return this.clone().irightShift(x);
39611 }
39612
39613 /**
39614 * Whether this value is equal to x
39615 * @param {BigInteger} x
39616 * @returns {Boolean}
39617 */
39618 equal(x) {
39619 return this.value.eq(x.value);
39620 }
39621
39622 /**
39623 * Whether this value is less than x
39624 * @param {BigInteger} x
39625 * @returns {Boolean}
39626 */
39627 lt(x) {
39628 return this.value.lt(x.value);
39629 }
39630
39631 /**
39632 * Whether this value is less than or equal to x
39633 * @param {BigInteger} x
39634 * @returns {Boolean}
39635 */
39636 lte(x) {
39637 return this.value.lte(x.value);
39638 }
39639
39640 /**
39641 * Whether this value is greater than x
39642 * @param {BigInteger} x
39643 * @returns {Boolean}
39644 */
39645 gt(x) {
39646 return this.value.gt(x.value);
39647 }
39648
39649 /**
39650 * Whether this value is greater than or equal to x
39651 * @param {BigInteger} x
39652 * @returns {Boolean}
39653 */
39654 gte(x) {
39655 return this.value.gte(x.value);
39656 }
39657
39658 isZero() {
39659 return this.value.isZero();
39660 }
39661
39662 isOne() {
39663 return this.value.eq(new bn(1));
39664 }
39665
39666 isNegative() {
39667 return this.value.isNeg();
39668 }
39669
39670 isEven() {
39671 return this.value.isEven();
39672 }
39673
39674 abs() {
39675 const res = this.clone();
39676 res.value = res.value.abs();
39677 return res;
39678 }
39679
39680 /**
39681 * Get this value as a string
39682 * @returns {String} this value.
39683 */
39684 toString() {
39685 return this.value.toString();
39686 }
39687
39688 /**
39689 * Get this value as an exact Number (max 53 bits)
39690 * Fails if this value is too large
39691 * @returns {Number}
39692 */
39693 toNumber() {
39694 return this.value.toNumber();
39695 }
39696
39697 /**
39698 * Get value of i-th bit
39699 * @param {Number} i - Bit index
39700 * @returns {Number} Bit value.
39701 */
39702 getBit(i) {
39703 return this.value.testn(i) ? 1 : 0;
39704 }
39705
39706 /**
39707 * Compute bit length
39708 * @returns {Number} Bit length.
39709 */
39710 bitLength() {
39711 return this.value.bitLength();
39712 }
39713
39714 /**
39715 * Compute byte length
39716 * @returns {Number} Byte length.
39717 */
39718 byteLength() {
39719 return this.value.byteLength();
39720 }
39721
39722 /**
39723 * Get Uint8Array representation of this number
39724 * @param {String} endian - Endianess of output array (defaults to 'be')
39725 * @param {Number} length - Of output array
39726 * @returns {Uint8Array}
39727 */
39728 toUint8Array(endian = 'be', length) {
39729 return this.value.toArrayLike(Uint8Array, endian, length);
39730 }
39731}
39732
39733var bn_interface = /*#__PURE__*/Object.freeze({
39734 __proto__: null,
39735 'default': BigInteger$1
39736});
39737
39738var utils_1 = createCommonjsModule(function (module, exports) {
39739
39740var utils = exports;
39741
39742function toArray(msg, enc) {
39743 if (Array.isArray(msg))
39744 return msg.slice();
39745 if (!msg)
39746 return [];
39747 var res = [];
39748 if (typeof msg !== 'string') {
39749 for (var i = 0; i < msg.length; i++)
39750 res[i] = msg[i] | 0;
39751 return res;
39752 }
39753 if (enc === 'hex') {
39754 msg = msg.replace(/[^a-z0-9]+/ig, '');
39755 if (msg.length % 2 !== 0)
39756 msg = '0' + msg;
39757 for (var i = 0; i < msg.length; i += 2)
39758 res.push(parseInt(msg[i] + msg[i + 1], 16));
39759 } else {
39760 for (var i = 0; i < msg.length; i++) {
39761 var c = msg.charCodeAt(i);
39762 var hi = c >> 8;
39763 var lo = c & 0xff;
39764 if (hi)
39765 res.push(hi, lo);
39766 else
39767 res.push(lo);
39768 }
39769 }
39770 return res;
39771}
39772utils.toArray = toArray;
39773
39774function zero2(word) {
39775 if (word.length === 1)
39776 return '0' + word;
39777 else
39778 return word;
39779}
39780utils.zero2 = zero2;
39781
39782function toHex(msg) {
39783 var res = '';
39784 for (var i = 0; i < msg.length; i++)
39785 res += zero2(msg[i].toString(16));
39786 return res;
39787}
39788utils.toHex = toHex;
39789
39790utils.encode = function encode(arr, enc) {
39791 if (enc === 'hex')
39792 return toHex(arr);
39793 else
39794 return arr;
39795};
39796});
39797
39798var utils_1$1 = createCommonjsModule(function (module, exports) {
39799
39800var utils = exports;
39801
39802
39803
39804
39805utils.assert = minimalisticAssert;
39806utils.toArray = utils_1.toArray;
39807utils.zero2 = utils_1.zero2;
39808utils.toHex = utils_1.toHex;
39809utils.encode = utils_1.encode;
39810
39811// Represent num in a w-NAF form
39812function getNAF(num, w) {
39813 var naf = [];
39814 var ws = 1 << (w + 1);
39815 var k = num.clone();
39816 while (k.cmpn(1) >= 0) {
39817 var z;
39818 if (k.isOdd()) {
39819 var mod = k.andln(ws - 1);
39820 if (mod > (ws >> 1) - 1)
39821 z = (ws >> 1) - mod;
39822 else
39823 z = mod;
39824 k.isubn(z);
39825 } else {
39826 z = 0;
39827 }
39828 naf.push(z);
39829
39830 // Optimization, shift by word if possible
39831 var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
39832 for (var i = 1; i < shift; i++)
39833 naf.push(0);
39834 k.iushrn(shift);
39835 }
39836
39837 return naf;
39838}
39839utils.getNAF = getNAF;
39840
39841// Represent k1, k2 in a Joint Sparse Form
39842function getJSF(k1, k2) {
39843 var jsf = [
39844 [],
39845 []
39846 ];
39847
39848 k1 = k1.clone();
39849 k2 = k2.clone();
39850 var d1 = 0;
39851 var d2 = 0;
39852 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
39853
39854 // First phase
39855 var m14 = (k1.andln(3) + d1) & 3;
39856 var m24 = (k2.andln(3) + d2) & 3;
39857 if (m14 === 3)
39858 m14 = -1;
39859 if (m24 === 3)
39860 m24 = -1;
39861 var u1;
39862 if ((m14 & 1) === 0) {
39863 u1 = 0;
39864 } else {
39865 var m8 = (k1.andln(7) + d1) & 7;
39866 if ((m8 === 3 || m8 === 5) && m24 === 2)
39867 u1 = -m14;
39868 else
39869 u1 = m14;
39870 }
39871 jsf[0].push(u1);
39872
39873 var u2;
39874 if ((m24 & 1) === 0) {
39875 u2 = 0;
39876 } else {
39877 var m8 = (k2.andln(7) + d2) & 7;
39878 if ((m8 === 3 || m8 === 5) && m14 === 2)
39879 u2 = -m24;
39880 else
39881 u2 = m24;
39882 }
39883 jsf[1].push(u2);
39884
39885 // Second phase
39886 if (2 * d1 === u1 + 1)
39887 d1 = 1 - d1;
39888 if (2 * d2 === u2 + 1)
39889 d2 = 1 - d2;
39890 k1.iushrn(1);
39891 k2.iushrn(1);
39892 }
39893
39894 return jsf;
39895}
39896utils.getJSF = getJSF;
39897
39898function cachedProperty(obj, name, computer) {
39899 var key = '_' + name;
39900 obj.prototype[name] = function cachedProperty() {
39901 return this[key] !== undefined ? this[key] :
39902 this[key] = computer.call(this);
39903 };
39904}
39905utils.cachedProperty = cachedProperty;
39906
39907function parseBytes(bytes) {
39908 return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
39909 bytes;
39910}
39911utils.parseBytes = parseBytes;
39912
39913function intFromLE(bytes) {
39914 return new bn(bytes, 'hex', 'le');
39915}
39916utils.intFromLE = intFromLE;
39917});
39918
39919var r$1;
39920
39921var brorand = function rand(len) {
39922 if (!r$1)
39923 r$1 = new Rand(null);
39924
39925 return r$1.generate(len);
39926};
39927
39928function Rand(rand) {
39929 this.rand = rand;
39930}
39931var Rand_1 = Rand;
39932
39933Rand.prototype.generate = function generate(len) {
39934 return this._rand(len);
39935};
39936
39937// Emulate crypto API using randy
39938Rand.prototype._rand = function _rand(n) {
39939 if (this.rand.getBytes)
39940 return this.rand.getBytes(n);
39941
39942 var res = new Uint8Array(n);
39943 for (var i = 0; i < res.length; i++)
39944 res[i] = this.rand.getByte();
39945 return res;
39946};
39947
39948if (typeof self === 'object') {
39949 if (self.crypto && self.crypto.getRandomValues) {
39950 // Modern browsers
39951 Rand.prototype._rand = function _rand(n) {
39952 var arr = new Uint8Array(n);
39953 self.crypto.getRandomValues(arr);
39954 return arr;
39955 };
39956 } else if (self.msCrypto && self.msCrypto.getRandomValues) {
39957 // IE
39958 Rand.prototype._rand = function _rand(n) {
39959 var arr = new Uint8Array(n);
39960 self.msCrypto.getRandomValues(arr);
39961 return arr;
39962 };
39963
39964 // Safari's WebWorkers do not have `crypto`
39965 } else if (typeof window === 'object') {
39966 // Old junk
39967 Rand.prototype._rand = function() {
39968 throw new Error('Not implemented yet');
39969 };
39970 }
39971} else {
39972 // Node.js or Web worker with no crypto support
39973 try {
39974 var crypto$2 = void('crypto');
39975 if (typeof crypto$2.randomBytes !== 'function')
39976 throw new Error('Not supported');
39977
39978 Rand.prototype._rand = function _rand(n) {
39979 return crypto$2.randomBytes(n);
39980 };
39981 } catch (e) {
39982 }
39983}
39984brorand.Rand = Rand_1;
39985
39986var getNAF = utils_1$1.getNAF;
39987var getJSF = utils_1$1.getJSF;
39988var assert$2 = utils_1$1.assert;
39989
39990function BaseCurve(type, conf) {
39991 this.type = type;
39992 this.p = new bn(conf.p, 16);
39993
39994 // Use Montgomery, when there is no fast reduction for the prime
39995 this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p);
39996
39997 // Useful for many curves
39998 this.zero = new bn(0).toRed(this.red);
39999 this.one = new bn(1).toRed(this.red);
40000 this.two = new bn(2).toRed(this.red);
40001
40002 // Curve configuration, optional
40003 this.n = conf.n && new bn(conf.n, 16);
40004 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
40005
40006 // Temporary arrays
40007 this._wnafT1 = new Array(4);
40008 this._wnafT2 = new Array(4);
40009 this._wnafT3 = new Array(4);
40010 this._wnafT4 = new Array(4);
40011
40012 // Generalized Greg Maxwell's trick
40013 var adjustCount = this.n && this.p.div(this.n);
40014 if (!adjustCount || adjustCount.cmpn(100) > 0) {
40015 this.redN = null;
40016 } else {
40017 this._maxwellTrick = true;
40018 this.redN = this.n.toRed(this.red);
40019 }
40020}
40021var base = BaseCurve;
40022
40023BaseCurve.prototype.point = function point() {
40024 throw new Error('Not implemented');
40025};
40026
40027BaseCurve.prototype.validate = function validate() {
40028 throw new Error('Not implemented');
40029};
40030
40031BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
40032 assert$2(p.precomputed);
40033 var doubles = p._getDoubles();
40034
40035 var naf = getNAF(k, 1);
40036 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
40037 I /= 3;
40038
40039 // Translate into more windowed form
40040 var repr = [];
40041 for (var j = 0; j < naf.length; j += doubles.step) {
40042 var nafW = 0;
40043 for (var k = j + doubles.step - 1; k >= j; k--)
40044 nafW = (nafW << 1) + naf[k];
40045 repr.push(nafW);
40046 }
40047
40048 var a = this.jpoint(null, null, null);
40049 var b = this.jpoint(null, null, null);
40050 for (var i = I; i > 0; i--) {
40051 for (var j = 0; j < repr.length; j++) {
40052 var nafW = repr[j];
40053 if (nafW === i)
40054 b = b.mixedAdd(doubles.points[j]);
40055 else if (nafW === -i)
40056 b = b.mixedAdd(doubles.points[j].neg());
40057 }
40058 a = a.add(b);
40059 }
40060 return a.toP();
40061};
40062
40063BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
40064 var w = 4;
40065
40066 // Precompute window
40067 var nafPoints = p._getNAFPoints(w);
40068 w = nafPoints.wnd;
40069 var wnd = nafPoints.points;
40070
40071 // Get NAF form
40072 var naf = getNAF(k, w);
40073
40074 // Add `this`*(N+1) for every w-NAF index
40075 var acc = this.jpoint(null, null, null);
40076 for (var i = naf.length - 1; i >= 0; i--) {
40077 // Count zeroes
40078 for (var k = 0; i >= 0 && naf[i] === 0; i--)
40079 k++;
40080 if (i >= 0)
40081 k++;
40082 acc = acc.dblp(k);
40083
40084 if (i < 0)
40085 break;
40086 var z = naf[i];
40087 assert$2(z !== 0);
40088 if (p.type === 'affine') {
40089 // J +- P
40090 if (z > 0)
40091 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
40092 else
40093 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
40094 } else {
40095 // J +- J
40096 if (z > 0)
40097 acc = acc.add(wnd[(z - 1) >> 1]);
40098 else
40099 acc = acc.add(wnd[(-z - 1) >> 1].neg());
40100 }
40101 }
40102 return p.type === 'affine' ? acc.toP() : acc;
40103};
40104
40105BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
40106 points,
40107 coeffs,
40108 len,
40109 jacobianResult) {
40110 var wndWidth = this._wnafT1;
40111 var wnd = this._wnafT2;
40112 var naf = this._wnafT3;
40113
40114 // Fill all arrays
40115 var max = 0;
40116 for (var i = 0; i < len; i++) {
40117 var p = points[i];
40118 var nafPoints = p._getNAFPoints(defW);
40119 wndWidth[i] = nafPoints.wnd;
40120 wnd[i] = nafPoints.points;
40121 }
40122
40123 // Comb small window NAFs
40124 for (var i = len - 1; i >= 1; i -= 2) {
40125 var a = i - 1;
40126 var b = i;
40127 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
40128 naf[a] = getNAF(coeffs[a], wndWidth[a]);
40129 naf[b] = getNAF(coeffs[b], wndWidth[b]);
40130 max = Math.max(naf[a].length, max);
40131 max = Math.max(naf[b].length, max);
40132 continue;
40133 }
40134
40135 var comb = [
40136 points[a], /* 1 */
40137 null, /* 3 */
40138 null, /* 5 */
40139 points[b] /* 7 */
40140 ];
40141
40142 // Try to avoid Projective points, if possible
40143 if (points[a].y.cmp(points[b].y) === 0) {
40144 comb[1] = points[a].add(points[b]);
40145 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
40146 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
40147 comb[1] = points[a].toJ().mixedAdd(points[b]);
40148 comb[2] = points[a].add(points[b].neg());
40149 } else {
40150 comb[1] = points[a].toJ().mixedAdd(points[b]);
40151 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
40152 }
40153
40154 var index = [
40155 -3, /* -1 -1 */
40156 -1, /* -1 0 */
40157 -5, /* -1 1 */
40158 -7, /* 0 -1 */
40159 0, /* 0 0 */
40160 7, /* 0 1 */
40161 5, /* 1 -1 */
40162 1, /* 1 0 */
40163 3 /* 1 1 */
40164 ];
40165
40166 var jsf = getJSF(coeffs[a], coeffs[b]);
40167 max = Math.max(jsf[0].length, max);
40168 naf[a] = new Array(max);
40169 naf[b] = new Array(max);
40170 for (var j = 0; j < max; j++) {
40171 var ja = jsf[0][j] | 0;
40172 var jb = jsf[1][j] | 0;
40173
40174 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
40175 naf[b][j] = 0;
40176 wnd[a] = comb;
40177 }
40178 }
40179
40180 var acc = this.jpoint(null, null, null);
40181 var tmp = this._wnafT4;
40182 for (var i = max; i >= 0; i--) {
40183 var k = 0;
40184
40185 while (i >= 0) {
40186 var zero = true;
40187 for (var j = 0; j < len; j++) {
40188 tmp[j] = naf[j][i] | 0;
40189 if (tmp[j] !== 0)
40190 zero = false;
40191 }
40192 if (!zero)
40193 break;
40194 k++;
40195 i--;
40196 }
40197 if (i >= 0)
40198 k++;
40199 acc = acc.dblp(k);
40200 if (i < 0)
40201 break;
40202
40203 for (var j = 0; j < len; j++) {
40204 var z = tmp[j];
40205 var p;
40206 if (z === 0)
40207 continue;
40208 else if (z > 0)
40209 p = wnd[j][(z - 1) >> 1];
40210 else if (z < 0)
40211 p = wnd[j][(-z - 1) >> 1].neg();
40212
40213 if (p.type === 'affine')
40214 acc = acc.mixedAdd(p);
40215 else
40216 acc = acc.add(p);
40217 }
40218 }
40219 // Zeroify references
40220 for (var i = 0; i < len; i++)
40221 wnd[i] = null;
40222
40223 if (jacobianResult)
40224 return acc;
40225 else
40226 return acc.toP();
40227};
40228
40229function BasePoint(curve, type) {
40230 this.curve = curve;
40231 this.type = type;
40232 this.precomputed = null;
40233}
40234BaseCurve.BasePoint = BasePoint;
40235
40236BasePoint.prototype.eq = function eq(/*other*/) {
40237 throw new Error('Not implemented');
40238};
40239
40240BasePoint.prototype.validate = function validate() {
40241 return this.curve.validate(this);
40242};
40243
40244BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
40245 bytes = utils_1$1.toArray(bytes, enc);
40246
40247 var len = this.p.byteLength();
40248
40249 // uncompressed, hybrid-odd, hybrid-even
40250 if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
40251 bytes.length - 1 === 2 * len) {
40252 if (bytes[0] === 0x06)
40253 assert$2(bytes[bytes.length - 1] % 2 === 0);
40254 else if (bytes[0] === 0x07)
40255 assert$2(bytes[bytes.length - 1] % 2 === 1);
40256
40257 var res = this.point(bytes.slice(1, 1 + len),
40258 bytes.slice(1 + len, 1 + 2 * len));
40259
40260 return res;
40261 } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
40262 bytes.length - 1 === len) {
40263 return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
40264 }
40265 throw new Error('Unknown point format');
40266};
40267
40268BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
40269 return this.encode(enc, true);
40270};
40271
40272BasePoint.prototype._encode = function _encode(compact) {
40273 var len = this.curve.p.byteLength();
40274 var x = this.getX().toArray('be', len);
40275
40276 if (compact)
40277 return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
40278
40279 return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
40280};
40281
40282BasePoint.prototype.encode = function encode(enc, compact) {
40283 return utils_1$1.encode(this._encode(compact), enc);
40284};
40285
40286BasePoint.prototype.precompute = function precompute(power) {
40287 if (this.precomputed)
40288 return this;
40289
40290 var precomputed = {
40291 doubles: null,
40292 naf: null,
40293 beta: null
40294 };
40295 precomputed.naf = this._getNAFPoints(8);
40296 precomputed.doubles = this._getDoubles(4, power);
40297 precomputed.beta = this._getBeta();
40298 this.precomputed = precomputed;
40299
40300 return this;
40301};
40302
40303BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
40304 if (!this.precomputed)
40305 return false;
40306
40307 var doubles = this.precomputed.doubles;
40308 if (!doubles)
40309 return false;
40310
40311 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
40312};
40313
40314BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
40315 if (this.precomputed && this.precomputed.doubles)
40316 return this.precomputed.doubles;
40317
40318 var doubles = [ this ];
40319 var acc = this;
40320 for (var i = 0; i < power; i += step) {
40321 for (var j = 0; j < step; j++)
40322 acc = acc.dbl();
40323 doubles.push(acc);
40324 }
40325 return {
40326 step: step,
40327 points: doubles
40328 };
40329};
40330
40331BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
40332 if (this.precomputed && this.precomputed.naf)
40333 return this.precomputed.naf;
40334
40335 var res = [ this ];
40336 var max = (1 << wnd) - 1;
40337 var dbl = max === 1 ? null : this.dbl();
40338 for (var i = 1; i < max; i++)
40339 res[i] = res[i - 1].add(dbl);
40340 return {
40341 wnd: wnd,
40342 points: res
40343 };
40344};
40345
40346BasePoint.prototype._getBeta = function _getBeta() {
40347 return null;
40348};
40349
40350BasePoint.prototype.dblp = function dblp(k) {
40351 var r = this;
40352 for (var i = 0; i < k; i++)
40353 r = r.dbl();
40354 return r;
40355};
40356
40357var assert$3 = utils_1$1.assert;
40358
40359function ShortCurve(conf) {
40360 base.call(this, 'short', conf);
40361
40362 this.a = new bn(conf.a, 16).toRed(this.red);
40363 this.b = new bn(conf.b, 16).toRed(this.red);
40364 this.tinv = this.two.redInvm();
40365
40366 this.zeroA = this.a.fromRed().cmpn(0) === 0;
40367 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
40368
40369 // If the curve is endomorphic, precalculate beta and lambda
40370 this.endo = this._getEndomorphism(conf);
40371 this._endoWnafT1 = new Array(4);
40372 this._endoWnafT2 = new Array(4);
40373}
40374inherits_browser(ShortCurve, base);
40375var short_1 = ShortCurve;
40376
40377ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
40378 // No efficient endomorphism
40379 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
40380 return;
40381
40382 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
40383 var beta;
40384 var lambda;
40385 if (conf.beta) {
40386 beta = new bn(conf.beta, 16).toRed(this.red);
40387 } else {
40388 var betas = this._getEndoRoots(this.p);
40389 // Choose the smallest beta
40390 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
40391 beta = beta.toRed(this.red);
40392 }
40393 if (conf.lambda) {
40394 lambda = new bn(conf.lambda, 16);
40395 } else {
40396 // Choose the lambda that is matching selected beta
40397 var lambdas = this._getEndoRoots(this.n);
40398 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
40399 lambda = lambdas[0];
40400 } else {
40401 lambda = lambdas[1];
40402 assert$3(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
40403 }
40404 }
40405
40406 // Get basis vectors, used for balanced length-two representation
40407 var basis;
40408 if (conf.basis) {
40409 basis = conf.basis.map(function(vec) {
40410 return {
40411 a: new bn(vec.a, 16),
40412 b: new bn(vec.b, 16)
40413 };
40414 });
40415 } else {
40416 basis = this._getEndoBasis(lambda);
40417 }
40418
40419 return {
40420 beta: beta,
40421 lambda: lambda,
40422 basis: basis
40423 };
40424};
40425
40426ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
40427 // Find roots of for x^2 + x + 1 in F
40428 // Root = (-1 +- Sqrt(-3)) / 2
40429 //
40430 var red = num === this.p ? this.red : bn.mont(num);
40431 var tinv = new bn(2).toRed(red).redInvm();
40432 var ntinv = tinv.redNeg();
40433
40434 var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv);
40435
40436 var l1 = ntinv.redAdd(s).fromRed();
40437 var l2 = ntinv.redSub(s).fromRed();
40438 return [ l1, l2 ];
40439};
40440
40441ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
40442 // aprxSqrt >= sqrt(this.n)
40443 var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
40444
40445 // 3.74
40446 // Run EGCD, until r(L + 1) < aprxSqrt
40447 var u = lambda;
40448 var v = this.n.clone();
40449 var x1 = new bn(1);
40450 var y1 = new bn(0);
40451 var x2 = new bn(0);
40452 var y2 = new bn(1);
40453
40454 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
40455 var a0;
40456 var b0;
40457 // First vector
40458 var a1;
40459 var b1;
40460 // Second vector
40461 var a2;
40462 var b2;
40463
40464 var prevR;
40465 var i = 0;
40466 var r;
40467 var x;
40468 while (u.cmpn(0) !== 0) {
40469 var q = v.div(u);
40470 r = v.sub(q.mul(u));
40471 x = x2.sub(q.mul(x1));
40472 var y = y2.sub(q.mul(y1));
40473
40474 if (!a1 && r.cmp(aprxSqrt) < 0) {
40475 a0 = prevR.neg();
40476 b0 = x1;
40477 a1 = r.neg();
40478 b1 = x;
40479 } else if (a1 && ++i === 2) {
40480 break;
40481 }
40482 prevR = r;
40483
40484 v = u;
40485 u = r;
40486 x2 = x1;
40487 x1 = x;
40488 y2 = y1;
40489 y1 = y;
40490 }
40491 a2 = r.neg();
40492 b2 = x;
40493
40494 var len1 = a1.sqr().add(b1.sqr());
40495 var len2 = a2.sqr().add(b2.sqr());
40496 if (len2.cmp(len1) >= 0) {
40497 a2 = a0;
40498 b2 = b0;
40499 }
40500
40501 // Normalize signs
40502 if (a1.negative) {
40503 a1 = a1.neg();
40504 b1 = b1.neg();
40505 }
40506 if (a2.negative) {
40507 a2 = a2.neg();
40508 b2 = b2.neg();
40509 }
40510
40511 return [
40512 { a: a1, b: b1 },
40513 { a: a2, b: b2 }
40514 ];
40515};
40516
40517ShortCurve.prototype._endoSplit = function _endoSplit(k) {
40518 var basis = this.endo.basis;
40519 var v1 = basis[0];
40520 var v2 = basis[1];
40521
40522 var c1 = v2.b.mul(k).divRound(this.n);
40523 var c2 = v1.b.neg().mul(k).divRound(this.n);
40524
40525 var p1 = c1.mul(v1.a);
40526 var p2 = c2.mul(v2.a);
40527 var q1 = c1.mul(v1.b);
40528 var q2 = c2.mul(v2.b);
40529
40530 // Calculate answer
40531 var k1 = k.sub(p1).sub(p2);
40532 var k2 = q1.add(q2).neg();
40533 return { k1: k1, k2: k2 };
40534};
40535
40536ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
40537 x = new bn(x, 16);
40538 if (!x.red)
40539 x = x.toRed(this.red);
40540
40541 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
40542 var y = y2.redSqrt();
40543 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
40544 throw new Error('invalid point');
40545
40546 // XXX Is there any way to tell if the number is odd without converting it
40547 // to non-red form?
40548 var isOdd = y.fromRed().isOdd();
40549 if (odd && !isOdd || !odd && isOdd)
40550 y = y.redNeg();
40551
40552 return this.point(x, y);
40553};
40554
40555ShortCurve.prototype.validate = function validate(point) {
40556 if (point.inf)
40557 return true;
40558
40559 var x = point.x;
40560 var y = point.y;
40561
40562 var ax = this.a.redMul(x);
40563 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
40564 return y.redSqr().redISub(rhs).cmpn(0) === 0;
40565};
40566
40567ShortCurve.prototype._endoWnafMulAdd =
40568 function _endoWnafMulAdd(points, coeffs, jacobianResult) {
40569 var npoints = this._endoWnafT1;
40570 var ncoeffs = this._endoWnafT2;
40571 for (var i = 0; i < points.length; i++) {
40572 var split = this._endoSplit(coeffs[i]);
40573 var p = points[i];
40574 var beta = p._getBeta();
40575
40576 if (split.k1.negative) {
40577 split.k1.ineg();
40578 p = p.neg(true);
40579 }
40580 if (split.k2.negative) {
40581 split.k2.ineg();
40582 beta = beta.neg(true);
40583 }
40584
40585 npoints[i * 2] = p;
40586 npoints[i * 2 + 1] = beta;
40587 ncoeffs[i * 2] = split.k1;
40588 ncoeffs[i * 2 + 1] = split.k2;
40589 }
40590 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
40591
40592 // Clean-up references to points and coefficients
40593 for (var j = 0; j < i * 2; j++) {
40594 npoints[j] = null;
40595 ncoeffs[j] = null;
40596 }
40597 return res;
40598};
40599
40600function Point(curve, x, y, isRed) {
40601 base.BasePoint.call(this, curve, 'affine');
40602 if (x === null && y === null) {
40603 this.x = null;
40604 this.y = null;
40605 this.inf = true;
40606 } else {
40607 this.x = new bn(x, 16);
40608 this.y = new bn(y, 16);
40609 // Force redgomery representation when loading from JSON
40610 if (isRed) {
40611 this.x.forceRed(this.curve.red);
40612 this.y.forceRed(this.curve.red);
40613 }
40614 if (!this.x.red)
40615 this.x = this.x.toRed(this.curve.red);
40616 if (!this.y.red)
40617 this.y = this.y.toRed(this.curve.red);
40618 this.inf = false;
40619 }
40620}
40621inherits_browser(Point, base.BasePoint);
40622
40623ShortCurve.prototype.point = function point(x, y, isRed) {
40624 return new Point(this, x, y, isRed);
40625};
40626
40627ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
40628 return Point.fromJSON(this, obj, red);
40629};
40630
40631Point.prototype._getBeta = function _getBeta() {
40632 if (!this.curve.endo)
40633 return;
40634
40635 var pre = this.precomputed;
40636 if (pre && pre.beta)
40637 return pre.beta;
40638
40639 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
40640 if (pre) {
40641 var curve = this.curve;
40642 var endoMul = function(p) {
40643 return curve.point(p.x.redMul(curve.endo.beta), p.y);
40644 };
40645 pre.beta = beta;
40646 beta.precomputed = {
40647 beta: null,
40648 naf: pre.naf && {
40649 wnd: pre.naf.wnd,
40650 points: pre.naf.points.map(endoMul)
40651 },
40652 doubles: pre.doubles && {
40653 step: pre.doubles.step,
40654 points: pre.doubles.points.map(endoMul)
40655 }
40656 };
40657 }
40658 return beta;
40659};
40660
40661Point.prototype.toJSON = function toJSON() {
40662 if (!this.precomputed)
40663 return [ this.x, this.y ];
40664
40665 return [ this.x, this.y, this.precomputed && {
40666 doubles: this.precomputed.doubles && {
40667 step: this.precomputed.doubles.step,
40668 points: this.precomputed.doubles.points.slice(1)
40669 },
40670 naf: this.precomputed.naf && {
40671 wnd: this.precomputed.naf.wnd,
40672 points: this.precomputed.naf.points.slice(1)
40673 }
40674 } ];
40675};
40676
40677Point.fromJSON = function fromJSON(curve, obj, red) {
40678 if (typeof obj === 'string')
40679 obj = JSON.parse(obj);
40680 var res = curve.point(obj[0], obj[1], red);
40681 if (!obj[2])
40682 return res;
40683
40684 function obj2point(obj) {
40685 return curve.point(obj[0], obj[1], red);
40686 }
40687
40688 var pre = obj[2];
40689 res.precomputed = {
40690 beta: null,
40691 doubles: pre.doubles && {
40692 step: pre.doubles.step,
40693 points: [ res ].concat(pre.doubles.points.map(obj2point))
40694 },
40695 naf: pre.naf && {
40696 wnd: pre.naf.wnd,
40697 points: [ res ].concat(pre.naf.points.map(obj2point))
40698 }
40699 };
40700 return res;
40701};
40702
40703Point.prototype.inspect = function inspect() {
40704 if (this.isInfinity())
40705 return '<EC Point Infinity>';
40706 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
40707 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
40708};
40709
40710Point.prototype.isInfinity = function isInfinity() {
40711 return this.inf;
40712};
40713
40714Point.prototype.add = function add(p) {
40715 // O + P = P
40716 if (this.inf)
40717 return p;
40718
40719 // P + O = P
40720 if (p.inf)
40721 return this;
40722
40723 // P + P = 2P
40724 if (this.eq(p))
40725 return this.dbl();
40726
40727 // P + (-P) = O
40728 if (this.neg().eq(p))
40729 return this.curve.point(null, null);
40730
40731 // P + Q = O
40732 if (this.x.cmp(p.x) === 0)
40733 return this.curve.point(null, null);
40734
40735 var c = this.y.redSub(p.y);
40736 if (c.cmpn(0) !== 0)
40737 c = c.redMul(this.x.redSub(p.x).redInvm());
40738 var nx = c.redSqr().redISub(this.x).redISub(p.x);
40739 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
40740 return this.curve.point(nx, ny);
40741};
40742
40743Point.prototype.dbl = function dbl() {
40744 if (this.inf)
40745 return this;
40746
40747 // 2P = O
40748 var ys1 = this.y.redAdd(this.y);
40749 if (ys1.cmpn(0) === 0)
40750 return this.curve.point(null, null);
40751
40752 var a = this.curve.a;
40753
40754 var x2 = this.x.redSqr();
40755 var dyinv = ys1.redInvm();
40756 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
40757
40758 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
40759 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
40760 return this.curve.point(nx, ny);
40761};
40762
40763Point.prototype.getX = function getX() {
40764 return this.x.fromRed();
40765};
40766
40767Point.prototype.getY = function getY() {
40768 return this.y.fromRed();
40769};
40770
40771Point.prototype.mul = function mul(k) {
40772 k = new bn(k, 16);
40773 if (this.isInfinity())
40774 return this;
40775 else if (this._hasDoubles(k))
40776 return this.curve._fixedNafMul(this, k);
40777 else if (this.curve.endo)
40778 return this.curve._endoWnafMulAdd([ this ], [ k ]);
40779 else
40780 return this.curve._wnafMul(this, k);
40781};
40782
40783Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
40784 var points = [ this, p2 ];
40785 var coeffs = [ k1, k2 ];
40786 if (this.curve.endo)
40787 return this.curve._endoWnafMulAdd(points, coeffs);
40788 else
40789 return this.curve._wnafMulAdd(1, points, coeffs, 2);
40790};
40791
40792Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
40793 var points = [ this, p2 ];
40794 var coeffs = [ k1, k2 ];
40795 if (this.curve.endo)
40796 return this.curve._endoWnafMulAdd(points, coeffs, true);
40797 else
40798 return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
40799};
40800
40801Point.prototype.eq = function eq(p) {
40802 return this === p ||
40803 this.inf === p.inf &&
40804 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
40805};
40806
40807Point.prototype.neg = function neg(_precompute) {
40808 if (this.inf)
40809 return this;
40810
40811 var res = this.curve.point(this.x, this.y.redNeg());
40812 if (_precompute && this.precomputed) {
40813 var pre = this.precomputed;
40814 var negate = function(p) {
40815 return p.neg();
40816 };
40817 res.precomputed = {
40818 naf: pre.naf && {
40819 wnd: pre.naf.wnd,
40820 points: pre.naf.points.map(negate)
40821 },
40822 doubles: pre.doubles && {
40823 step: pre.doubles.step,
40824 points: pre.doubles.points.map(negate)
40825 }
40826 };
40827 }
40828 return res;
40829};
40830
40831Point.prototype.toJ = function toJ() {
40832 if (this.inf)
40833 return this.curve.jpoint(null, null, null);
40834
40835 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
40836 return res;
40837};
40838
40839function JPoint(curve, x, y, z) {
40840 base.BasePoint.call(this, curve, 'jacobian');
40841 if (x === null && y === null && z === null) {
40842 this.x = this.curve.one;
40843 this.y = this.curve.one;
40844 this.z = new bn(0);
40845 } else {
40846 this.x = new bn(x, 16);
40847 this.y = new bn(y, 16);
40848 this.z = new bn(z, 16);
40849 }
40850 if (!this.x.red)
40851 this.x = this.x.toRed(this.curve.red);
40852 if (!this.y.red)
40853 this.y = this.y.toRed(this.curve.red);
40854 if (!this.z.red)
40855 this.z = this.z.toRed(this.curve.red);
40856
40857 this.zOne = this.z === this.curve.one;
40858}
40859inherits_browser(JPoint, base.BasePoint);
40860
40861ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
40862 return new JPoint(this, x, y, z);
40863};
40864
40865JPoint.prototype.toP = function toP() {
40866 if (this.isInfinity())
40867 return this.curve.point(null, null);
40868
40869 var zinv = this.z.redInvm();
40870 var zinv2 = zinv.redSqr();
40871 var ax = this.x.redMul(zinv2);
40872 var ay = this.y.redMul(zinv2).redMul(zinv);
40873
40874 return this.curve.point(ax, ay);
40875};
40876
40877JPoint.prototype.neg = function neg() {
40878 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
40879};
40880
40881JPoint.prototype.add = function add(p) {
40882 // O + P = P
40883 if (this.isInfinity())
40884 return p;
40885
40886 // P + O = P
40887 if (p.isInfinity())
40888 return this;
40889
40890 // 12M + 4S + 7A
40891 var pz2 = p.z.redSqr();
40892 var z2 = this.z.redSqr();
40893 var u1 = this.x.redMul(pz2);
40894 var u2 = p.x.redMul(z2);
40895 var s1 = this.y.redMul(pz2.redMul(p.z));
40896 var s2 = p.y.redMul(z2.redMul(this.z));
40897
40898 var h = u1.redSub(u2);
40899 var r = s1.redSub(s2);
40900 if (h.cmpn(0) === 0) {
40901 if (r.cmpn(0) !== 0)
40902 return this.curve.jpoint(null, null, null);
40903 else
40904 return this.dbl();
40905 }
40906
40907 var h2 = h.redSqr();
40908 var h3 = h2.redMul(h);
40909 var v = u1.redMul(h2);
40910
40911 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
40912 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
40913 var nz = this.z.redMul(p.z).redMul(h);
40914
40915 return this.curve.jpoint(nx, ny, nz);
40916};
40917
40918JPoint.prototype.mixedAdd = function mixedAdd(p) {
40919 // O + P = P
40920 if (this.isInfinity())
40921 return p.toJ();
40922
40923 // P + O = P
40924 if (p.isInfinity())
40925 return this;
40926
40927 // 8M + 3S + 7A
40928 var z2 = this.z.redSqr();
40929 var u1 = this.x;
40930 var u2 = p.x.redMul(z2);
40931 var s1 = this.y;
40932 var s2 = p.y.redMul(z2).redMul(this.z);
40933
40934 var h = u1.redSub(u2);
40935 var r = s1.redSub(s2);
40936 if (h.cmpn(0) === 0) {
40937 if (r.cmpn(0) !== 0)
40938 return this.curve.jpoint(null, null, null);
40939 else
40940 return this.dbl();
40941 }
40942
40943 var h2 = h.redSqr();
40944 var h3 = h2.redMul(h);
40945 var v = u1.redMul(h2);
40946
40947 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
40948 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
40949 var nz = this.z.redMul(h);
40950
40951 return this.curve.jpoint(nx, ny, nz);
40952};
40953
40954JPoint.prototype.dblp = function dblp(pow) {
40955 if (pow === 0)
40956 return this;
40957 if (this.isInfinity())
40958 return this;
40959 if (!pow)
40960 return this.dbl();
40961
40962 if (this.curve.zeroA || this.curve.threeA) {
40963 var r = this;
40964 for (var i = 0; i < pow; i++)
40965 r = r.dbl();
40966 return r;
40967 }
40968
40969 // 1M + 2S + 1A + N * (4S + 5M + 8A)
40970 // N = 1 => 6M + 6S + 9A
40971 var a = this.curve.a;
40972 var tinv = this.curve.tinv;
40973
40974 var jx = this.x;
40975 var jy = this.y;
40976 var jz = this.z;
40977 var jz4 = jz.redSqr().redSqr();
40978
40979 // Reuse results
40980 var jyd = jy.redAdd(jy);
40981 for (var i = 0; i < pow; i++) {
40982 var jx2 = jx.redSqr();
40983 var jyd2 = jyd.redSqr();
40984 var jyd4 = jyd2.redSqr();
40985 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
40986
40987 var t1 = jx.redMul(jyd2);
40988 var nx = c.redSqr().redISub(t1.redAdd(t1));
40989 var t2 = t1.redISub(nx);
40990 var dny = c.redMul(t2);
40991 dny = dny.redIAdd(dny).redISub(jyd4);
40992 var nz = jyd.redMul(jz);
40993 if (i + 1 < pow)
40994 jz4 = jz4.redMul(jyd4);
40995
40996 jx = nx;
40997 jz = nz;
40998 jyd = dny;
40999 }
41000
41001 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
41002};
41003
41004JPoint.prototype.dbl = function dbl() {
41005 if (this.isInfinity())
41006 return this;
41007
41008 if (this.curve.zeroA)
41009 return this._zeroDbl();
41010 else if (this.curve.threeA)
41011 return this._threeDbl();
41012 else
41013 return this._dbl();
41014};
41015
41016JPoint.prototype._zeroDbl = function _zeroDbl() {
41017 var nx;
41018 var ny;
41019 var nz;
41020 // Z = 1
41021 if (this.zOne) {
41022 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
41023 // #doubling-mdbl-2007-bl
41024 // 1M + 5S + 14A
41025
41026 // XX = X1^2
41027 var xx = this.x.redSqr();
41028 // YY = Y1^2
41029 var yy = this.y.redSqr();
41030 // YYYY = YY^2
41031 var yyyy = yy.redSqr();
41032 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
41033 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
41034 s = s.redIAdd(s);
41035 // M = 3 * XX + a; a = 0
41036 var m = xx.redAdd(xx).redIAdd(xx);
41037 // T = M ^ 2 - 2*S
41038 var t = m.redSqr().redISub(s).redISub(s);
41039
41040 // 8 * YYYY
41041 var yyyy8 = yyyy.redIAdd(yyyy);
41042 yyyy8 = yyyy8.redIAdd(yyyy8);
41043 yyyy8 = yyyy8.redIAdd(yyyy8);
41044
41045 // X3 = T
41046 nx = t;
41047 // Y3 = M * (S - T) - 8 * YYYY
41048 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
41049 // Z3 = 2*Y1
41050 nz = this.y.redAdd(this.y);
41051 } else {
41052 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
41053 // #doubling-dbl-2009-l
41054 // 2M + 5S + 13A
41055
41056 // A = X1^2
41057 var a = this.x.redSqr();
41058 // B = Y1^2
41059 var b = this.y.redSqr();
41060 // C = B^2
41061 var c = b.redSqr();
41062 // D = 2 * ((X1 + B)^2 - A - C)
41063 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
41064 d = d.redIAdd(d);
41065 // E = 3 * A
41066 var e = a.redAdd(a).redIAdd(a);
41067 // F = E^2
41068 var f = e.redSqr();
41069
41070 // 8 * C
41071 var c8 = c.redIAdd(c);
41072 c8 = c8.redIAdd(c8);
41073 c8 = c8.redIAdd(c8);
41074
41075 // X3 = F - 2 * D
41076 nx = f.redISub(d).redISub(d);
41077 // Y3 = E * (D - X3) - 8 * C
41078 ny = e.redMul(d.redISub(nx)).redISub(c8);
41079 // Z3 = 2 * Y1 * Z1
41080 nz = this.y.redMul(this.z);
41081 nz = nz.redIAdd(nz);
41082 }
41083
41084 return this.curve.jpoint(nx, ny, nz);
41085};
41086
41087JPoint.prototype._threeDbl = function _threeDbl() {
41088 var nx;
41089 var ny;
41090 var nz;
41091 // Z = 1
41092 if (this.zOne) {
41093 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
41094 // #doubling-mdbl-2007-bl
41095 // 1M + 5S + 15A
41096
41097 // XX = X1^2
41098 var xx = this.x.redSqr();
41099 // YY = Y1^2
41100 var yy = this.y.redSqr();
41101 // YYYY = YY^2
41102 var yyyy = yy.redSqr();
41103 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
41104 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
41105 s = s.redIAdd(s);
41106 // M = 3 * XX + a
41107 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
41108 // T = M^2 - 2 * S
41109 var t = m.redSqr().redISub(s).redISub(s);
41110 // X3 = T
41111 nx = t;
41112 // Y3 = M * (S - T) - 8 * YYYY
41113 var yyyy8 = yyyy.redIAdd(yyyy);
41114 yyyy8 = yyyy8.redIAdd(yyyy8);
41115 yyyy8 = yyyy8.redIAdd(yyyy8);
41116 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
41117 // Z3 = 2 * Y1
41118 nz = this.y.redAdd(this.y);
41119 } else {
41120 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
41121 // 3M + 5S
41122
41123 // delta = Z1^2
41124 var delta = this.z.redSqr();
41125 // gamma = Y1^2
41126 var gamma = this.y.redSqr();
41127 // beta = X1 * gamma
41128 var beta = this.x.redMul(gamma);
41129 // alpha = 3 * (X1 - delta) * (X1 + delta)
41130 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
41131 alpha = alpha.redAdd(alpha).redIAdd(alpha);
41132 // X3 = alpha^2 - 8 * beta
41133 var beta4 = beta.redIAdd(beta);
41134 beta4 = beta4.redIAdd(beta4);
41135 var beta8 = beta4.redAdd(beta4);
41136 nx = alpha.redSqr().redISub(beta8);
41137 // Z3 = (Y1 + Z1)^2 - gamma - delta
41138 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
41139 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
41140 var ggamma8 = gamma.redSqr();
41141 ggamma8 = ggamma8.redIAdd(ggamma8);
41142 ggamma8 = ggamma8.redIAdd(ggamma8);
41143 ggamma8 = ggamma8.redIAdd(ggamma8);
41144 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
41145 }
41146
41147 return this.curve.jpoint(nx, ny, nz);
41148};
41149
41150JPoint.prototype._dbl = function _dbl() {
41151 var a = this.curve.a;
41152
41153 // 4M + 6S + 10A
41154 var jx = this.x;
41155 var jy = this.y;
41156 var jz = this.z;
41157 var jz4 = jz.redSqr().redSqr();
41158
41159 var jx2 = jx.redSqr();
41160 var jy2 = jy.redSqr();
41161
41162 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
41163
41164 var jxd4 = jx.redAdd(jx);
41165 jxd4 = jxd4.redIAdd(jxd4);
41166 var t1 = jxd4.redMul(jy2);
41167 var nx = c.redSqr().redISub(t1.redAdd(t1));
41168 var t2 = t1.redISub(nx);
41169
41170 var jyd8 = jy2.redSqr();
41171 jyd8 = jyd8.redIAdd(jyd8);
41172 jyd8 = jyd8.redIAdd(jyd8);
41173 jyd8 = jyd8.redIAdd(jyd8);
41174 var ny = c.redMul(t2).redISub(jyd8);
41175 var nz = jy.redAdd(jy).redMul(jz);
41176
41177 return this.curve.jpoint(nx, ny, nz);
41178};
41179
41180JPoint.prototype.trpl = function trpl() {
41181 if (!this.curve.zeroA)
41182 return this.dbl().add(this);
41183
41184 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
41185 // 5M + 10S + ...
41186
41187 // XX = X1^2
41188 var xx = this.x.redSqr();
41189 // YY = Y1^2
41190 var yy = this.y.redSqr();
41191 // ZZ = Z1^2
41192 var zz = this.z.redSqr();
41193 // YYYY = YY^2
41194 var yyyy = yy.redSqr();
41195 // M = 3 * XX + a * ZZ2; a = 0
41196 var m = xx.redAdd(xx).redIAdd(xx);
41197 // MM = M^2
41198 var mm = m.redSqr();
41199 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
41200 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
41201 e = e.redIAdd(e);
41202 e = e.redAdd(e).redIAdd(e);
41203 e = e.redISub(mm);
41204 // EE = E^2
41205 var ee = e.redSqr();
41206 // T = 16*YYYY
41207 var t = yyyy.redIAdd(yyyy);
41208 t = t.redIAdd(t);
41209 t = t.redIAdd(t);
41210 t = t.redIAdd(t);
41211 // U = (M + E)^2 - MM - EE - T
41212 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
41213 // X3 = 4 * (X1 * EE - 4 * YY * U)
41214 var yyu4 = yy.redMul(u);
41215 yyu4 = yyu4.redIAdd(yyu4);
41216 yyu4 = yyu4.redIAdd(yyu4);
41217 var nx = this.x.redMul(ee).redISub(yyu4);
41218 nx = nx.redIAdd(nx);
41219 nx = nx.redIAdd(nx);
41220 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
41221 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
41222 ny = ny.redIAdd(ny);
41223 ny = ny.redIAdd(ny);
41224 ny = ny.redIAdd(ny);
41225 // Z3 = (Z1 + E)^2 - ZZ - EE
41226 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
41227
41228 return this.curve.jpoint(nx, ny, nz);
41229};
41230
41231JPoint.prototype.mul = function mul(k, kbase) {
41232 k = new bn(k, kbase);
41233
41234 return this.curve._wnafMul(this, k);
41235};
41236
41237JPoint.prototype.eq = function eq(p) {
41238 if (p.type === 'affine')
41239 return this.eq(p.toJ());
41240
41241 if (this === p)
41242 return true;
41243
41244 // x1 * z2^2 == x2 * z1^2
41245 var z2 = this.z.redSqr();
41246 var pz2 = p.z.redSqr();
41247 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
41248 return false;
41249
41250 // y1 * z2^3 == y2 * z1^3
41251 var z3 = z2.redMul(this.z);
41252 var pz3 = pz2.redMul(p.z);
41253 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
41254};
41255
41256JPoint.prototype.eqXToP = function eqXToP(x) {
41257 var zs = this.z.redSqr();
41258 var rx = x.toRed(this.curve.red).redMul(zs);
41259 if (this.x.cmp(rx) === 0)
41260 return true;
41261
41262 var xc = x.clone();
41263 var t = this.curve.redN.redMul(zs);
41264 for (;;) {
41265 xc.iadd(this.curve.n);
41266 if (xc.cmp(this.curve.p) >= 0)
41267 return false;
41268
41269 rx.redIAdd(t);
41270 if (this.x.cmp(rx) === 0)
41271 return true;
41272 }
41273};
41274
41275JPoint.prototype.inspect = function inspect() {
41276 if (this.isInfinity())
41277 return '<EC JPoint Infinity>';
41278 return '<EC JPoint x: ' + this.x.toString(16, 2) +
41279 ' y: ' + this.y.toString(16, 2) +
41280 ' z: ' + this.z.toString(16, 2) + '>';
41281};
41282
41283JPoint.prototype.isInfinity = function isInfinity() {
41284 // XXX This code assumes that zero is always zero in red
41285 return this.z.cmpn(0) === 0;
41286};
41287
41288function MontCurve(conf) {
41289 base.call(this, 'mont', conf);
41290
41291 this.a = new bn(conf.a, 16).toRed(this.red);
41292 this.b = new bn(conf.b, 16).toRed(this.red);
41293 this.i4 = new bn(4).toRed(this.red).redInvm();
41294 this.two = new bn(2).toRed(this.red);
41295 // Note: this implementation is according to the original paper
41296 // by P. Montgomery, NOT the one by D. J. Bernstein.
41297 this.a24 = this.i4.redMul(this.a.redAdd(this.two));
41298}
41299inherits_browser(MontCurve, base);
41300var mont = MontCurve;
41301
41302MontCurve.prototype.validate = function validate(point) {
41303 var x = point.normalize().x;
41304 var x2 = x.redSqr();
41305 var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
41306 var y = rhs.redSqrt();
41307
41308 return y.redSqr().cmp(rhs) === 0;
41309};
41310
41311function Point$1(curve, x, z) {
41312 base.BasePoint.call(this, curve, 'projective');
41313 if (x === null && z === null) {
41314 this.x = this.curve.one;
41315 this.z = this.curve.zero;
41316 } else {
41317 this.x = new bn(x, 16);
41318 this.z = new bn(z, 16);
41319 if (!this.x.red)
41320 this.x = this.x.toRed(this.curve.red);
41321 if (!this.z.red)
41322 this.z = this.z.toRed(this.curve.red);
41323 }
41324}
41325inherits_browser(Point$1, base.BasePoint);
41326
41327MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
41328 var bytes = utils_1$1.toArray(bytes, enc);
41329
41330 // TODO Curve448
41331 // Montgomery curve points must be represented in the compressed format
41332 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
41333 if (bytes.length === 33 && bytes[0] === 0x40)
41334 bytes = bytes.slice(1, 33).reverse(); // point must be little-endian
41335 if (bytes.length !== 32)
41336 throw new Error('Unknown point compression format');
41337 return this.point(bytes, 1);
41338};
41339
41340MontCurve.prototype.point = function point(x, z) {
41341 return new Point$1(this, x, z);
41342};
41343
41344MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
41345 return Point$1.fromJSON(this, obj);
41346};
41347
41348Point$1.prototype.precompute = function precompute() {
41349 // No-op
41350};
41351
41352Point$1.prototype._encode = function _encode(compact) {
41353 var len = this.curve.p.byteLength();
41354
41355 // Note: the output should always be little-endian
41356 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
41357 if (compact) {
41358 return [ 0x40 ].concat(this.getX().toArray('le', len));
41359 } else {
41360 return this.getX().toArray('be', len);
41361 }
41362};
41363
41364Point$1.fromJSON = function fromJSON(curve, obj) {
41365 return new Point$1(curve, obj[0], obj[1] || curve.one);
41366};
41367
41368Point$1.prototype.inspect = function inspect() {
41369 if (this.isInfinity())
41370 return '<EC Point Infinity>';
41371 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
41372 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
41373};
41374
41375Point$1.prototype.isInfinity = function isInfinity() {
41376 // XXX This code assumes that zero is always zero in red
41377 return this.z.cmpn(0) === 0;
41378};
41379
41380Point$1.prototype.dbl = function dbl() {
41381 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
41382 // 2M + 2S + 4A
41383
41384 // A = X1 + Z1
41385 var a = this.x.redAdd(this.z);
41386 // AA = A^2
41387 var aa = a.redSqr();
41388 // B = X1 - Z1
41389 var b = this.x.redSub(this.z);
41390 // BB = B^2
41391 var bb = b.redSqr();
41392 // C = AA - BB
41393 var c = aa.redSub(bb);
41394 // X3 = AA * BB
41395 var nx = aa.redMul(bb);
41396 // Z3 = C * (BB + A24 * C)
41397 var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
41398 return this.curve.point(nx, nz);
41399};
41400
41401Point$1.prototype.add = function add() {
41402 throw new Error('Not supported on Montgomery curve');
41403};
41404
41405Point$1.prototype.diffAdd = function diffAdd(p, diff) {
41406 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
41407 // 4M + 2S + 6A
41408
41409 // A = X2 + Z2
41410 var a = this.x.redAdd(this.z);
41411 // B = X2 - Z2
41412 var b = this.x.redSub(this.z);
41413 // C = X3 + Z3
41414 var c = p.x.redAdd(p.z);
41415 // D = X3 - Z3
41416 var d = p.x.redSub(p.z);
41417 // DA = D * A
41418 var da = d.redMul(a);
41419 // CB = C * B
41420 var cb = c.redMul(b);
41421 // X5 = Z1 * (DA + CB)^2
41422 var nx = diff.z.redMul(da.redAdd(cb).redSqr());
41423 // Z5 = X1 * (DA - CB)^2
41424 var nz = diff.x.redMul(da.redISub(cb).redSqr());
41425 return this.curve.point(nx, nz);
41426};
41427
41428Point$1.prototype.mul = function mul(k) {
41429 k = new bn(k, 16);
41430
41431 var t = k.clone();
41432 var a = this; // (N / 2) * Q + Q
41433 var b = this.curve.point(null, null); // (N / 2) * Q
41434 var c = this; // Q
41435
41436 for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
41437 bits.push(t.andln(1));
41438
41439 for (var i = bits.length - 1; i >= 0; i--) {
41440 if (bits[i] === 0) {
41441 // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
41442 a = a.diffAdd(b, c);
41443 // N * Q = 2 * ((N / 2) * Q + Q))
41444 b = b.dbl();
41445 } else {
41446 // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
41447 b = a.diffAdd(b, c);
41448 // N * Q + Q = 2 * ((N / 2) * Q + Q)
41449 a = a.dbl();
41450 }
41451 }
41452 return b;
41453};
41454
41455Point$1.prototype.mulAdd = function mulAdd() {
41456 throw new Error('Not supported on Montgomery curve');
41457};
41458
41459Point$1.prototype.jumlAdd = function jumlAdd() {
41460 throw new Error('Not supported on Montgomery curve');
41461};
41462
41463Point$1.prototype.eq = function eq(other) {
41464 return this.getX().cmp(other.getX()) === 0;
41465};
41466
41467Point$1.prototype.normalize = function normalize() {
41468 this.x = this.x.redMul(this.z.redInvm());
41469 this.z = this.curve.one;
41470 return this;
41471};
41472
41473Point$1.prototype.getX = function getX() {
41474 // Normalize coordinates
41475 this.normalize();
41476
41477 return this.x.fromRed();
41478};
41479
41480var assert$4 = utils_1$1.assert;
41481
41482function EdwardsCurve(conf) {
41483 // NOTE: Important as we are creating point in Base.call()
41484 this.twisted = (conf.a | 0) !== 1;
41485 this.mOneA = this.twisted && (conf.a | 0) === -1;
41486 this.extended = this.mOneA;
41487
41488 base.call(this, 'edwards', conf);
41489
41490 this.a = new bn(conf.a, 16).umod(this.red.m);
41491 this.a = this.a.toRed(this.red);
41492 this.c = new bn(conf.c, 16).toRed(this.red);
41493 this.c2 = this.c.redSqr();
41494 this.d = new bn(conf.d, 16).toRed(this.red);
41495 this.dd = this.d.redAdd(this.d);
41496
41497 assert$4(!this.twisted || this.c.fromRed().cmpn(1) === 0);
41498 this.oneC = (conf.c | 0) === 1;
41499}
41500inherits_browser(EdwardsCurve, base);
41501var edwards = EdwardsCurve;
41502
41503EdwardsCurve.prototype._mulA = function _mulA(num) {
41504 if (this.mOneA)
41505 return num.redNeg();
41506 else
41507 return this.a.redMul(num);
41508};
41509
41510EdwardsCurve.prototype._mulC = function _mulC(num) {
41511 if (this.oneC)
41512 return num;
41513 else
41514 return this.c.redMul(num);
41515};
41516
41517// Just for compatibility with Short curve
41518EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
41519 return this.point(x, y, z, t);
41520};
41521
41522EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
41523 x = new bn(x, 16);
41524 if (!x.red)
41525 x = x.toRed(this.red);
41526
41527 var x2 = x.redSqr();
41528 var rhs = this.c2.redSub(this.a.redMul(x2));
41529 var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
41530
41531 var y2 = rhs.redMul(lhs.redInvm());
41532 var y = y2.redSqrt();
41533 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
41534 throw new Error('invalid point');
41535
41536 var isOdd = y.fromRed().isOdd();
41537 if (odd && !isOdd || !odd && isOdd)
41538 y = y.redNeg();
41539
41540 return this.point(x, y);
41541};
41542
41543EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
41544 y = new bn(y, 16);
41545 if (!y.red)
41546 y = y.toRed(this.red);
41547
41548 // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
41549 var y2 = y.redSqr();
41550 var lhs = y2.redSub(this.c2);
41551 var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
41552 var x2 = lhs.redMul(rhs.redInvm());
41553
41554 if (x2.cmp(this.zero) === 0) {
41555 if (odd)
41556 throw new Error('invalid point');
41557 else
41558 return this.point(this.zero, y);
41559 }
41560
41561 var x = x2.redSqrt();
41562 if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
41563 throw new Error('invalid point');
41564
41565 if (x.fromRed().isOdd() !== odd)
41566 x = x.redNeg();
41567
41568 return this.point(x, y);
41569};
41570
41571EdwardsCurve.prototype.validate = function validate(point) {
41572 if (point.isInfinity())
41573 return true;
41574
41575 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
41576 point.normalize();
41577
41578 var x2 = point.x.redSqr();
41579 var y2 = point.y.redSqr();
41580 var lhs = x2.redMul(this.a).redAdd(y2);
41581 var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
41582
41583 return lhs.cmp(rhs) === 0;
41584};
41585
41586function Point$2(curve, x, y, z, t) {
41587 base.BasePoint.call(this, curve, 'projective');
41588 if (x === null && y === null && z === null) {
41589 this.x = this.curve.zero;
41590 this.y = this.curve.one;
41591 this.z = this.curve.one;
41592 this.t = this.curve.zero;
41593 this.zOne = true;
41594 } else {
41595 this.x = new bn(x, 16);
41596 this.y = new bn(y, 16);
41597 this.z = z ? new bn(z, 16) : this.curve.one;
41598 this.t = t && new bn(t, 16);
41599 if (!this.x.red)
41600 this.x = this.x.toRed(this.curve.red);
41601 if (!this.y.red)
41602 this.y = this.y.toRed(this.curve.red);
41603 if (!this.z.red)
41604 this.z = this.z.toRed(this.curve.red);
41605 if (this.t && !this.t.red)
41606 this.t = this.t.toRed(this.curve.red);
41607 this.zOne = this.z === this.curve.one;
41608
41609 // Use extended coordinates
41610 if (this.curve.extended && !this.t) {
41611 this.t = this.x.redMul(this.y);
41612 if (!this.zOne)
41613 this.t = this.t.redMul(this.z.redInvm());
41614 }
41615 }
41616}
41617inherits_browser(Point$2, base.BasePoint);
41618
41619EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
41620 return Point$2.fromJSON(this, obj);
41621};
41622
41623EdwardsCurve.prototype.point = function point(x, y, z, t) {
41624 return new Point$2(this, x, y, z, t);
41625};
41626
41627Point$2.fromJSON = function fromJSON(curve, obj) {
41628 return new Point$2(curve, obj[0], obj[1], obj[2]);
41629};
41630
41631Point$2.prototype.inspect = function inspect() {
41632 if (this.isInfinity())
41633 return '<EC Point Infinity>';
41634 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
41635 ' y: ' + this.y.fromRed().toString(16, 2) +
41636 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
41637};
41638
41639Point$2.prototype.isInfinity = function isInfinity() {
41640 // XXX This code assumes that zero is always zero in red
41641 return this.x.cmpn(0) === 0 &&
41642 (this.y.cmp(this.z) === 0 ||
41643 (this.zOne && this.y.cmp(this.curve.c) === 0));
41644};
41645
41646Point$2.prototype._extDbl = function _extDbl() {
41647 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
41648 // #doubling-dbl-2008-hwcd
41649 // 4M + 4S
41650
41651 // A = X1^2
41652 var a = this.x.redSqr();
41653 // B = Y1^2
41654 var b = this.y.redSqr();
41655 // C = 2 * Z1^2
41656 var c = this.z.redSqr();
41657 c = c.redIAdd(c);
41658 // D = a * A
41659 var d = this.curve._mulA(a);
41660 // E = (X1 + Y1)^2 - A - B
41661 var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
41662 // G = D + B
41663 var g = d.redAdd(b);
41664 // F = G - C
41665 var f = g.redSub(c);
41666 // H = D - B
41667 var h = d.redSub(b);
41668 // X3 = E * F
41669 var nx = e.redMul(f);
41670 // Y3 = G * H
41671 var ny = g.redMul(h);
41672 // T3 = E * H
41673 var nt = e.redMul(h);
41674 // Z3 = F * G
41675 var nz = f.redMul(g);
41676 return this.curve.point(nx, ny, nz, nt);
41677};
41678
41679Point$2.prototype._projDbl = function _projDbl() {
41680 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
41681 // #doubling-dbl-2008-bbjlp
41682 // #doubling-dbl-2007-bl
41683 // and others
41684 // Generally 3M + 4S or 2M + 4S
41685
41686 // B = (X1 + Y1)^2
41687 var b = this.x.redAdd(this.y).redSqr();
41688 // C = X1^2
41689 var c = this.x.redSqr();
41690 // D = Y1^2
41691 var d = this.y.redSqr();
41692
41693 var nx;
41694 var ny;
41695 var nz;
41696 if (this.curve.twisted) {
41697 // E = a * C
41698 var e = this.curve._mulA(c);
41699 // F = E + D
41700 var f = e.redAdd(d);
41701 if (this.zOne) {
41702 // X3 = (B - C - D) * (F - 2)
41703 nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
41704 // Y3 = F * (E - D)
41705 ny = f.redMul(e.redSub(d));
41706 // Z3 = F^2 - 2 * F
41707 nz = f.redSqr().redSub(f).redSub(f);
41708 } else {
41709 // H = Z1^2
41710 var h = this.z.redSqr();
41711 // J = F - 2 * H
41712 var j = f.redSub(h).redISub(h);
41713 // X3 = (B-C-D)*J
41714 nx = b.redSub(c).redISub(d).redMul(j);
41715 // Y3 = F * (E - D)
41716 ny = f.redMul(e.redSub(d));
41717 // Z3 = F * J
41718 nz = f.redMul(j);
41719 }
41720 } else {
41721 // E = C + D
41722 var e = c.redAdd(d);
41723 // H = (c * Z1)^2
41724 var h = this.curve._mulC(this.z).redSqr();
41725 // J = E - 2 * H
41726 var j = e.redSub(h).redSub(h);
41727 // X3 = c * (B - E) * J
41728 nx = this.curve._mulC(b.redISub(e)).redMul(j);
41729 // Y3 = c * E * (C - D)
41730 ny = this.curve._mulC(e).redMul(c.redISub(d));
41731 // Z3 = E * J
41732 nz = e.redMul(j);
41733 }
41734 return this.curve.point(nx, ny, nz);
41735};
41736
41737Point$2.prototype.dbl = function dbl() {
41738 if (this.isInfinity())
41739 return this;
41740
41741 // Double in extended coordinates
41742 if (this.curve.extended)
41743 return this._extDbl();
41744 else
41745 return this._projDbl();
41746};
41747
41748Point$2.prototype._extAdd = function _extAdd(p) {
41749 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
41750 // #addition-add-2008-hwcd-3
41751 // 8M
41752
41753 // A = (Y1 - X1) * (Y2 - X2)
41754 var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
41755 // B = (Y1 + X1) * (Y2 + X2)
41756 var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
41757 // C = T1 * k * T2
41758 var c = this.t.redMul(this.curve.dd).redMul(p.t);
41759 // D = Z1 * 2 * Z2
41760 var d = this.z.redMul(p.z.redAdd(p.z));
41761 // E = B - A
41762 var e = b.redSub(a);
41763 // F = D - C
41764 var f = d.redSub(c);
41765 // G = D + C
41766 var g = d.redAdd(c);
41767 // H = B + A
41768 var h = b.redAdd(a);
41769 // X3 = E * F
41770 var nx = e.redMul(f);
41771 // Y3 = G * H
41772 var ny = g.redMul(h);
41773 // T3 = E * H
41774 var nt = e.redMul(h);
41775 // Z3 = F * G
41776 var nz = f.redMul(g);
41777 return this.curve.point(nx, ny, nz, nt);
41778};
41779
41780Point$2.prototype._projAdd = function _projAdd(p) {
41781 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
41782 // #addition-add-2008-bbjlp
41783 // #addition-add-2007-bl
41784 // 10M + 1S
41785
41786 // A = Z1 * Z2
41787 var a = this.z.redMul(p.z);
41788 // B = A^2
41789 var b = a.redSqr();
41790 // C = X1 * X2
41791 var c = this.x.redMul(p.x);
41792 // D = Y1 * Y2
41793 var d = this.y.redMul(p.y);
41794 // E = d * C * D
41795 var e = this.curve.d.redMul(c).redMul(d);
41796 // F = B - E
41797 var f = b.redSub(e);
41798 // G = B + E
41799 var g = b.redAdd(e);
41800 // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
41801 var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
41802 var nx = a.redMul(f).redMul(tmp);
41803 var ny;
41804 var nz;
41805 if (this.curve.twisted) {
41806 // Y3 = A * G * (D - a * C)
41807 ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
41808 // Z3 = F * G
41809 nz = f.redMul(g);
41810 } else {
41811 // Y3 = A * G * (D - C)
41812 ny = a.redMul(g).redMul(d.redSub(c));
41813 // Z3 = c * F * G
41814 nz = this.curve._mulC(f).redMul(g);
41815 }
41816 return this.curve.point(nx, ny, nz);
41817};
41818
41819Point$2.prototype.add = function add(p) {
41820 if (this.isInfinity())
41821 return p;
41822 if (p.isInfinity())
41823 return this;
41824
41825 if (this.curve.extended)
41826 return this._extAdd(p);
41827 else
41828 return this._projAdd(p);
41829};
41830
41831Point$2.prototype.mul = function mul(k) {
41832 if (this._hasDoubles(k))
41833 return this.curve._fixedNafMul(this, k);
41834 else
41835 return this.curve._wnafMul(this, k);
41836};
41837
41838Point$2.prototype.mulAdd = function mulAdd(k1, p, k2) {
41839 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
41840};
41841
41842Point$2.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
41843 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
41844};
41845
41846Point$2.prototype.normalize = function normalize() {
41847 if (this.zOne)
41848 return this;
41849
41850 // Normalize coordinates
41851 var zi = this.z.redInvm();
41852 this.x = this.x.redMul(zi);
41853 this.y = this.y.redMul(zi);
41854 if (this.t)
41855 this.t = this.t.redMul(zi);
41856 this.z = this.curve.one;
41857 this.zOne = true;
41858 return this;
41859};
41860
41861Point$2.prototype.neg = function neg() {
41862 return this.curve.point(this.x.redNeg(),
41863 this.y,
41864 this.z,
41865 this.t && this.t.redNeg());
41866};
41867
41868Point$2.prototype.getX = function getX() {
41869 this.normalize();
41870 return this.x.fromRed();
41871};
41872
41873Point$2.prototype.getY = function getY() {
41874 this.normalize();
41875 return this.y.fromRed();
41876};
41877
41878Point$2.prototype.eq = function eq(other) {
41879 return this === other ||
41880 this.getX().cmp(other.getX()) === 0 &&
41881 this.getY().cmp(other.getY()) === 0;
41882};
41883
41884Point$2.prototype.eqXToP = function eqXToP(x) {
41885 var rx = x.toRed(this.curve.red).redMul(this.z);
41886 if (this.x.cmp(rx) === 0)
41887 return true;
41888
41889 var xc = x.clone();
41890 var t = this.curve.redN.redMul(this.z);
41891 for (;;) {
41892 xc.iadd(this.curve.n);
41893 if (xc.cmp(this.curve.p) >= 0)
41894 return false;
41895
41896 rx.redIAdd(t);
41897 if (this.x.cmp(rx) === 0)
41898 return true;
41899 }
41900};
41901
41902// Compatibility with BaseCurve
41903Point$2.prototype.toP = Point$2.prototype.normalize;
41904Point$2.prototype.mixedAdd = Point$2.prototype.add;
41905
41906var curve_1 = createCommonjsModule(function (module, exports) {
41907
41908var curve = exports;
41909
41910curve.base = base;
41911curve.short = short_1;
41912curve.mont = mont;
41913curve.edwards = edwards;
41914});
41915
41916var rotl32$2 = utils.rotl32;
41917var sum32$3 = utils.sum32;
41918var sum32_5$2 = utils.sum32_5;
41919var ft_1$1 = common$1.ft_1;
41920var BlockHash$4 = common.BlockHash;
41921
41922var sha1_K = [
41923 0x5A827999, 0x6ED9EBA1,
41924 0x8F1BBCDC, 0xCA62C1D6
41925];
41926
41927function SHA1() {
41928 if (!(this instanceof SHA1))
41929 return new SHA1();
41930
41931 BlockHash$4.call(this);
41932 this.h = [
41933 0x67452301, 0xefcdab89, 0x98badcfe,
41934 0x10325476, 0xc3d2e1f0 ];
41935 this.W = new Array(80);
41936}
41937
41938utils.inherits(SHA1, BlockHash$4);
41939var _1 = SHA1;
41940
41941SHA1.blockSize = 512;
41942SHA1.outSize = 160;
41943SHA1.hmacStrength = 80;
41944SHA1.padLength = 64;
41945
41946SHA1.prototype._update = function _update(msg, start) {
41947 var W = this.W;
41948
41949 for (var i = 0; i < 16; i++)
41950 W[i] = msg[start + i];
41951
41952 for(; i < W.length; i++)
41953 W[i] = rotl32$2(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
41954
41955 var a = this.h[0];
41956 var b = this.h[1];
41957 var c = this.h[2];
41958 var d = this.h[3];
41959 var e = this.h[4];
41960
41961 for (i = 0; i < W.length; i++) {
41962 var s = ~~(i / 20);
41963 var t = sum32_5$2(rotl32$2(a, 5), ft_1$1(s, b, c, d), e, W[i], sha1_K[s]);
41964 e = d;
41965 d = c;
41966 c = rotl32$2(b, 30);
41967 b = a;
41968 a = t;
41969 }
41970
41971 this.h[0] = sum32$3(this.h[0], a);
41972 this.h[1] = sum32$3(this.h[1], b);
41973 this.h[2] = sum32$3(this.h[2], c);
41974 this.h[3] = sum32$3(this.h[3], d);
41975 this.h[4] = sum32$3(this.h[4], e);
41976};
41977
41978SHA1.prototype._digest = function digest(enc) {
41979 if (enc === 'hex')
41980 return utils.toHex32(this.h, 'big');
41981 else
41982 return utils.split32(this.h, 'big');
41983};
41984
41985var sha1 = _1;
41986var sha224 = _224;
41987var sha256 = _256;
41988var sha384 = _384;
41989var sha512 = _512;
41990
41991var sha = {
41992 sha1: sha1,
41993 sha224: sha224,
41994 sha256: sha256,
41995 sha384: sha384,
41996 sha512: sha512
41997};
41998
41999function Hmac(hash, key, enc) {
42000 if (!(this instanceof Hmac))
42001 return new Hmac(hash, key, enc);
42002 this.Hash = hash;
42003 this.blockSize = hash.blockSize / 8;
42004 this.outSize = hash.outSize / 8;
42005 this.inner = null;
42006 this.outer = null;
42007
42008 this._init(utils.toArray(key, enc));
42009}
42010var hmac = Hmac;
42011
42012Hmac.prototype._init = function init(key) {
42013 // Shorten key, if needed
42014 if (key.length > this.blockSize)
42015 key = new this.Hash().update(key).digest();
42016 minimalisticAssert(key.length <= this.blockSize);
42017
42018 // Add padding to key
42019 for (var i = key.length; i < this.blockSize; i++)
42020 key.push(0);
42021
42022 for (i = 0; i < key.length; i++)
42023 key[i] ^= 0x36;
42024 this.inner = new this.Hash().update(key);
42025
42026 // 0x36 ^ 0x5c = 0x6a
42027 for (i = 0; i < key.length; i++)
42028 key[i] ^= 0x6a;
42029 this.outer = new this.Hash().update(key);
42030};
42031
42032Hmac.prototype.update = function update(msg, enc) {
42033 this.inner.update(msg, enc);
42034 return this;
42035};
42036
42037Hmac.prototype.digest = function digest(enc) {
42038 this.outer.update(this.inner.digest());
42039 return this.outer.digest(enc);
42040};
42041
42042var hash_1 = createCommonjsModule(function (module, exports) {
42043var hash = exports;
42044
42045hash.utils = utils;
42046hash.common = common;
42047hash.sha = sha;
42048hash.ripemd = ripemd;
42049hash.hmac = hmac;
42050
42051// Proxy hash functions to the main object
42052hash.sha1 = hash.sha.sha1;
42053hash.sha256 = hash.sha.sha256;
42054hash.sha224 = hash.sha.sha224;
42055hash.sha384 = hash.sha.sha384;
42056hash.sha512 = hash.sha.sha512;
42057hash.ripemd160 = hash.ripemd.ripemd160;
42058});
42059
42060var secp256k1 = {
42061 doubles: {
42062 step: 4,
42063 points: [
42064 [
42065 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
42066 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
42067 ],
42068 [
42069 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
42070 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
42071 ],
42072 [
42073 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
42074 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
42075 ],
42076 [
42077 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
42078 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
42079 ],
42080 [
42081 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
42082 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
42083 ],
42084 [
42085 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
42086 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
42087 ],
42088 [
42089 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
42090 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
42091 ],
42092 [
42093 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
42094 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
42095 ],
42096 [
42097 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
42098 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
42099 ],
42100 [
42101 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
42102 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
42103 ],
42104 [
42105 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
42106 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
42107 ],
42108 [
42109 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
42110 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
42111 ],
42112 [
42113 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
42114 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
42115 ],
42116 [
42117 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
42118 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
42119 ],
42120 [
42121 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
42122 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
42123 ],
42124 [
42125 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
42126 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
42127 ],
42128 [
42129 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
42130 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
42131 ],
42132 [
42133 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
42134 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
42135 ],
42136 [
42137 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
42138 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
42139 ],
42140 [
42141 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
42142 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
42143 ],
42144 [
42145 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
42146 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
42147 ],
42148 [
42149 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
42150 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
42151 ],
42152 [
42153 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
42154 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
42155 ],
42156 [
42157 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
42158 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
42159 ],
42160 [
42161 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
42162 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
42163 ],
42164 [
42165 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
42166 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
42167 ],
42168 [
42169 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
42170 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
42171 ],
42172 [
42173 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
42174 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
42175 ],
42176 [
42177 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
42178 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
42179 ],
42180 [
42181 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
42182 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
42183 ],
42184 [
42185 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
42186 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
42187 ],
42188 [
42189 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
42190 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
42191 ],
42192 [
42193 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
42194 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
42195 ],
42196 [
42197 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
42198 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
42199 ],
42200 [
42201 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
42202 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
42203 ],
42204 [
42205 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
42206 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
42207 ],
42208 [
42209 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
42210 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
42211 ],
42212 [
42213 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
42214 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
42215 ],
42216 [
42217 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
42218 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
42219 ],
42220 [
42221 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
42222 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
42223 ],
42224 [
42225 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
42226 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
42227 ],
42228 [
42229 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
42230 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
42231 ],
42232 [
42233 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
42234 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
42235 ],
42236 [
42237 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
42238 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
42239 ],
42240 [
42241 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
42242 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
42243 ],
42244 [
42245 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
42246 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
42247 ],
42248 [
42249 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
42250 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
42251 ],
42252 [
42253 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
42254 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
42255 ],
42256 [
42257 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
42258 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
42259 ],
42260 [
42261 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
42262 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
42263 ],
42264 [
42265 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
42266 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
42267 ],
42268 [
42269 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
42270 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
42271 ],
42272 [
42273 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
42274 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
42275 ],
42276 [
42277 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
42278 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
42279 ],
42280 [
42281 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
42282 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
42283 ],
42284 [
42285 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
42286 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
42287 ],
42288 [
42289 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
42290 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
42291 ],
42292 [
42293 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
42294 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
42295 ],
42296 [
42297 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
42298 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
42299 ],
42300 [
42301 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
42302 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
42303 ],
42304 [
42305 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
42306 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
42307 ],
42308 [
42309 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
42310 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
42311 ],
42312 [
42313 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
42314 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
42315 ],
42316 [
42317 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
42318 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
42319 ],
42320 [
42321 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
42322 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
42323 ]
42324 ]
42325 },
42326 naf: {
42327 wnd: 7,
42328 points: [
42329 [
42330 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
42331 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
42332 ],
42333 [
42334 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
42335 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
42336 ],
42337 [
42338 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
42339 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
42340 ],
42341 [
42342 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
42343 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
42344 ],
42345 [
42346 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
42347 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
42348 ],
42349 [
42350 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
42351 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
42352 ],
42353 [
42354 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
42355 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
42356 ],
42357 [
42358 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
42359 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
42360 ],
42361 [
42362 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
42363 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
42364 ],
42365 [
42366 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
42367 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
42368 ],
42369 [
42370 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
42371 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
42372 ],
42373 [
42374 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
42375 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
42376 ],
42377 [
42378 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
42379 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
42380 ],
42381 [
42382 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
42383 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
42384 ],
42385 [
42386 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
42387 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
42388 ],
42389 [
42390 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
42391 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
42392 ],
42393 [
42394 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
42395 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
42396 ],
42397 [
42398 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
42399 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
42400 ],
42401 [
42402 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
42403 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
42404 ],
42405 [
42406 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
42407 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
42408 ],
42409 [
42410 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
42411 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
42412 ],
42413 [
42414 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
42415 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
42416 ],
42417 [
42418 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
42419 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
42420 ],
42421 [
42422 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
42423 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
42424 ],
42425 [
42426 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
42427 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
42428 ],
42429 [
42430 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
42431 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
42432 ],
42433 [
42434 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
42435 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
42436 ],
42437 [
42438 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
42439 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
42440 ],
42441 [
42442 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
42443 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
42444 ],
42445 [
42446 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
42447 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
42448 ],
42449 [
42450 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
42451 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
42452 ],
42453 [
42454 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
42455 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
42456 ],
42457 [
42458 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
42459 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
42460 ],
42461 [
42462 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
42463 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
42464 ],
42465 [
42466 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
42467 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
42468 ],
42469 [
42470 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
42471 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
42472 ],
42473 [
42474 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
42475 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
42476 ],
42477 [
42478 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
42479 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
42480 ],
42481 [
42482 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
42483 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
42484 ],
42485 [
42486 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
42487 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
42488 ],
42489 [
42490 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
42491 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
42492 ],
42493 [
42494 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
42495 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
42496 ],
42497 [
42498 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
42499 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
42500 ],
42501 [
42502 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
42503 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
42504 ],
42505 [
42506 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
42507 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
42508 ],
42509 [
42510 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
42511 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
42512 ],
42513 [
42514 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
42515 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
42516 ],
42517 [
42518 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
42519 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
42520 ],
42521 [
42522 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
42523 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
42524 ],
42525 [
42526 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
42527 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
42528 ],
42529 [
42530 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
42531 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
42532 ],
42533 [
42534 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
42535 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
42536 ],
42537 [
42538 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
42539 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
42540 ],
42541 [
42542 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
42543 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
42544 ],
42545 [
42546 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
42547 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
42548 ],
42549 [
42550 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
42551 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
42552 ],
42553 [
42554 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
42555 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
42556 ],
42557 [
42558 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
42559 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
42560 ],
42561 [
42562 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
42563 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
42564 ],
42565 [
42566 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
42567 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
42568 ],
42569 [
42570 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
42571 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
42572 ],
42573 [
42574 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
42575 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
42576 ],
42577 [
42578 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
42579 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
42580 ],
42581 [
42582 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
42583 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
42584 ],
42585 [
42586 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
42587 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
42588 ],
42589 [
42590 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
42591 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
42592 ],
42593 [
42594 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
42595 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
42596 ],
42597 [
42598 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
42599 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
42600 ],
42601 [
42602 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
42603 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
42604 ],
42605 [
42606 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
42607 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
42608 ],
42609 [
42610 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
42611 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
42612 ],
42613 [
42614 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
42615 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
42616 ],
42617 [
42618 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
42619 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
42620 ],
42621 [
42622 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
42623 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
42624 ],
42625 [
42626 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
42627 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
42628 ],
42629 [
42630 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
42631 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
42632 ],
42633 [
42634 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
42635 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
42636 ],
42637 [
42638 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
42639 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
42640 ],
42641 [
42642 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
42643 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
42644 ],
42645 [
42646 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
42647 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
42648 ],
42649 [
42650 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
42651 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
42652 ],
42653 [
42654 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
42655 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
42656 ],
42657 [
42658 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
42659 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
42660 ],
42661 [
42662 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
42663 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
42664 ],
42665 [
42666 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
42667 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
42668 ],
42669 [
42670 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
42671 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
42672 ],
42673 [
42674 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
42675 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
42676 ],
42677 [
42678 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
42679 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
42680 ],
42681 [
42682 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
42683 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
42684 ],
42685 [
42686 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
42687 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
42688 ],
42689 [
42690 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
42691 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
42692 ],
42693 [
42694 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
42695 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
42696 ],
42697 [
42698 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
42699 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
42700 ],
42701 [
42702 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
42703 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
42704 ],
42705 [
42706 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
42707 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
42708 ],
42709 [
42710 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
42711 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
42712 ],
42713 [
42714 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
42715 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
42716 ],
42717 [
42718 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
42719 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
42720 ],
42721 [
42722 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
42723 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
42724 ],
42725 [
42726 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
42727 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
42728 ],
42729 [
42730 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
42731 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
42732 ],
42733 [
42734 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
42735 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
42736 ],
42737 [
42738 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
42739 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
42740 ],
42741 [
42742 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
42743 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
42744 ],
42745 [
42746 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
42747 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
42748 ],
42749 [
42750 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
42751 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
42752 ],
42753 [
42754 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
42755 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
42756 ],
42757 [
42758 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
42759 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
42760 ],
42761 [
42762 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
42763 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
42764 ],
42765 [
42766 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
42767 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
42768 ],
42769 [
42770 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
42771 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
42772 ],
42773 [
42774 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
42775 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
42776 ],
42777 [
42778 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
42779 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
42780 ],
42781 [
42782 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
42783 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
42784 ],
42785 [
42786 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
42787 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
42788 ],
42789 [
42790 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
42791 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
42792 ],
42793 [
42794 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
42795 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
42796 ],
42797 [
42798 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
42799 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
42800 ],
42801 [
42802 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
42803 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
42804 ],
42805 [
42806 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
42807 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
42808 ],
42809 [
42810 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
42811 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
42812 ],
42813 [
42814 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
42815 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
42816 ],
42817 [
42818 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
42819 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
42820 ],
42821 [
42822 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
42823 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
42824 ],
42825 [
42826 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
42827 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
42828 ],
42829 [
42830 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
42831 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
42832 ],
42833 [
42834 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
42835 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
42836 ]
42837 ]
42838 }
42839};
42840
42841var curves_1 = createCommonjsModule(function (module, exports) {
42842
42843var curves = exports;
42844
42845
42846
42847
42848
42849var assert = utils_1$1.assert;
42850
42851function PresetCurve(options) {
42852 if (options.type === 'short')
42853 this.curve = new curve_1.short(options);
42854 else if (options.type === 'edwards')
42855 this.curve = new curve_1.edwards(options);
42856 else if (options.type === 'mont')
42857 this.curve = new curve_1.mont(options);
42858 else throw new Error('Unknown curve type.');
42859 this.g = this.curve.g;
42860 this.n = this.curve.n;
42861 this.hash = options.hash;
42862
42863 assert(this.g.validate(), 'Invalid curve');
42864 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O');
42865}
42866curves.PresetCurve = PresetCurve;
42867
42868function defineCurve(name, options) {
42869 Object.defineProperty(curves, name, {
42870 configurable: true,
42871 enumerable: true,
42872 get: function() {
42873 var curve = new PresetCurve(options);
42874 Object.defineProperty(curves, name, {
42875 configurable: true,
42876 enumerable: true,
42877 value: curve
42878 });
42879 return curve;
42880 }
42881 });
42882}
42883
42884defineCurve('p192', {
42885 type: 'short',
42886 prime: 'p192',
42887 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
42888 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
42889 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
42890 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
42891 hash: hash_1.sha256,
42892 gRed: false,
42893 g: [
42894 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
42895 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
42896 ]
42897});
42898
42899defineCurve('p224', {
42900 type: 'short',
42901 prime: 'p224',
42902 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
42903 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
42904 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
42905 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
42906 hash: hash_1.sha256,
42907 gRed: false,
42908 g: [
42909 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
42910 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
42911 ]
42912});
42913
42914defineCurve('p256', {
42915 type: 'short',
42916 prime: null,
42917 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
42918 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
42919 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
42920 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
42921 hash: hash_1.sha256,
42922 gRed: false,
42923 g: [
42924 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
42925 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
42926 ]
42927});
42928
42929defineCurve('p384', {
42930 type: 'short',
42931 prime: null,
42932 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42933 'fffffffe ffffffff 00000000 00000000 ffffffff',
42934 a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42935 'fffffffe ffffffff 00000000 00000000 fffffffc',
42936 b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
42937 '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
42938 n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
42939 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
42940 hash: hash_1.sha384,
42941 gRed: false,
42942 g: [
42943 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
42944 '5502f25d bf55296c 3a545e38 72760ab7',
42945 '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
42946 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
42947 ]
42948});
42949
42950defineCurve('p521', {
42951 type: 'short',
42952 prime: null,
42953 p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42954 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42955 'ffffffff ffffffff ffffffff ffffffff ffffffff',
42956 a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42957 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42958 'ffffffff ffffffff ffffffff ffffffff fffffffc',
42959 b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
42960 '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
42961 '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
42962 n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42963 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
42964 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
42965 hash: hash_1.sha512,
42966 gRed: false,
42967 g: [
42968 '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
42969 '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
42970 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
42971 '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
42972 '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
42973 '3fad0761 353c7086 a272c240 88be9476 9fd16650'
42974 ]
42975});
42976
42977// https://tools.ietf.org/html/rfc7748#section-4.1
42978defineCurve('curve25519', {
42979 type: 'mont',
42980 prime: 'p25519',
42981 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
42982 a: '76d06',
42983 b: '1',
42984 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
42985 cofactor: '8',
42986 hash: hash_1.sha256,
42987 gRed: false,
42988 g: [
42989 '9'
42990 ]
42991});
42992
42993defineCurve('ed25519', {
42994 type: 'edwards',
42995 prime: 'p25519',
42996 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
42997 a: '-1',
42998 c: '1',
42999 // -121665 * (121666^(-1)) (mod P)
43000 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
43001 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
43002 cofactor: '8',
43003 hash: hash_1.sha256,
43004 gRed: false,
43005 g: [
43006 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
43007 // 4/5
43008 '6666666666666666666666666666666666666666666666666666666666666658'
43009 ]
43010});
43011
43012// https://tools.ietf.org/html/rfc5639#section-3.4
43013defineCurve('brainpoolP256r1', {
43014 type: 'short',
43015 prime: null,
43016 p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377',
43017 a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9',
43018 b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6',
43019 n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7',
43020 hash: hash_1.sha256, // or 384, or 512
43021 gRed: false,
43022 g: [
43023 '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262',
43024 '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997'
43025 ]
43026});
43027
43028// https://tools.ietf.org/html/rfc5639#section-3.6
43029defineCurve('brainpoolP384r1', {
43030 type: 'short',
43031 prime: null,
43032 p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' +
43033 'ACD3A729 901D1A71 87470013 3107EC53',
43034 a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' +
43035 '8AA5814A 503AD4EB 04A8C7DD 22CE2826',
43036 b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' +
43037 '7CB43902 95DBC994 3AB78696 FA504C11',
43038 n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' +
43039 'CF3AB6AF 6B7FC310 3B883202 E9046565',
43040 hash: hash_1.sha384, // or 512
43041 gRed: false,
43042 g: [
43043 '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' +
43044 'E8E826E03436D646AAEF87B2E247D4AF1E',
43045 '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' +
43046 '280E4646217791811142820341263C5315'
43047 ]
43048});
43049
43050// https://tools.ietf.org/html/rfc5639#section-3.7
43051defineCurve('brainpoolP512r1', {
43052 type: 'short',
43053 prime: null,
43054 p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' +
43055 '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3',
43056 a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' +
43057 '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA',
43058 b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' +
43059 '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723',
43060 n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' +
43061 '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069',
43062 hash: hash_1.sha512,
43063 gRed: false,
43064 g: [
43065 '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' +
43066 '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822',
43067 '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' +
43068 '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892'
43069 ]
43070});
43071
43072// https://en.bitcoin.it/wiki/Secp256k1
43073var pre;
43074try {
43075 pre = secp256k1;
43076} catch (e) {
43077 pre = undefined;
43078}
43079
43080defineCurve('secp256k1', {
43081 type: 'short',
43082 prime: 'k256',
43083 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
43084 a: '0',
43085 b: '7',
43086 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
43087 h: '1',
43088 hash: hash_1.sha256,
43089
43090 // Precomputed endomorphism
43091 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
43092 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
43093 basis: [
43094 {
43095 a: '3086d221a7d46bcde86c90e49284eb15',
43096 b: '-e4437ed6010e88286f547fa90abfe4c3'
43097 },
43098 {
43099 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
43100 b: '3086d221a7d46bcde86c90e49284eb15'
43101 }
43102 ],
43103
43104 gRed: false,
43105 g: [
43106 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
43107 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
43108 pre
43109 ]
43110});
43111});
43112
43113function HmacDRBG(options) {
43114 if (!(this instanceof HmacDRBG))
43115 return new HmacDRBG(options);
43116 this.hash = options.hash;
43117 this.predResist = !!options.predResist;
43118
43119 this.outLen = this.hash.outSize;
43120 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
43121
43122 this._reseed = null;
43123 this.reseedInterval = null;
43124 this.K = null;
43125 this.V = null;
43126
43127 var entropy = utils_1.toArray(options.entropy, options.entropyEnc || 'hex');
43128 var nonce = utils_1.toArray(options.nonce, options.nonceEnc || 'hex');
43129 var pers = utils_1.toArray(options.pers, options.persEnc || 'hex');
43130 minimalisticAssert(entropy.length >= (this.minEntropy / 8),
43131 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
43132 this._init(entropy, nonce, pers);
43133}
43134var hmacDrbg = HmacDRBG;
43135
43136HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
43137 var seed = entropy.concat(nonce).concat(pers);
43138
43139 this.K = new Array(this.outLen / 8);
43140 this.V = new Array(this.outLen / 8);
43141 for (var i = 0; i < this.V.length; i++) {
43142 this.K[i] = 0x00;
43143 this.V[i] = 0x01;
43144 }
43145
43146 this._update(seed);
43147 this._reseed = 1;
43148 this.reseedInterval = 0x1000000000000; // 2^48
43149};
43150
43151HmacDRBG.prototype._hmac = function hmac() {
43152 return new hash_1.hmac(this.hash, this.K);
43153};
43154
43155HmacDRBG.prototype._update = function update(seed) {
43156 var kmac = this._hmac()
43157 .update(this.V)
43158 .update([ 0x00 ]);
43159 if (seed)
43160 kmac = kmac.update(seed);
43161 this.K = kmac.digest();
43162 this.V = this._hmac().update(this.V).digest();
43163 if (!seed)
43164 return;
43165
43166 this.K = this._hmac()
43167 .update(this.V)
43168 .update([ 0x01 ])
43169 .update(seed)
43170 .digest();
43171 this.V = this._hmac().update(this.V).digest();
43172};
43173
43174HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
43175 // Optional entropy enc
43176 if (typeof entropyEnc !== 'string') {
43177 addEnc = add;
43178 add = entropyEnc;
43179 entropyEnc = null;
43180 }
43181
43182 entropy = utils_1.toArray(entropy, entropyEnc);
43183 add = utils_1.toArray(add, addEnc);
43184
43185 minimalisticAssert(entropy.length >= (this.minEntropy / 8),
43186 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
43187
43188 this._update(entropy.concat(add || []));
43189 this._reseed = 1;
43190};
43191
43192HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
43193 if (this._reseed > this.reseedInterval)
43194 throw new Error('Reseed is required');
43195
43196 // Optional encoding
43197 if (typeof enc !== 'string') {
43198 addEnc = add;
43199 add = enc;
43200 enc = null;
43201 }
43202
43203 // Optional additional data
43204 if (add) {
43205 add = utils_1.toArray(add, addEnc || 'hex');
43206 this._update(add);
43207 }
43208
43209 var temp = [];
43210 while (temp.length < len) {
43211 this.V = this._hmac().update(this.V).digest();
43212 temp = temp.concat(this.V);
43213 }
43214
43215 var res = temp.slice(0, len);
43216 this._update(add);
43217 this._reseed++;
43218 return utils_1.encode(res, enc);
43219};
43220
43221var assert$5 = utils_1$1.assert;
43222
43223function KeyPair(ec, options) {
43224 this.ec = ec;
43225 this.priv = null;
43226 this.pub = null;
43227
43228 // KeyPair(ec, { priv: ..., pub: ... })
43229 if (options.priv)
43230 this._importPrivate(options.priv, options.privEnc);
43231 if (options.pub)
43232 this._importPublic(options.pub, options.pubEnc);
43233}
43234var key = KeyPair;
43235
43236KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
43237 if (pub instanceof KeyPair)
43238 return pub;
43239
43240 return new KeyPair(ec, {
43241 pub: pub,
43242 pubEnc: enc
43243 });
43244};
43245
43246KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
43247 if (priv instanceof KeyPair)
43248 return priv;
43249
43250 return new KeyPair(ec, {
43251 priv: priv,
43252 privEnc: enc
43253 });
43254};
43255
43256// TODO: should not validate for X25519
43257KeyPair.prototype.validate = function validate() {
43258 var pub = this.getPublic();
43259
43260 if (pub.isInfinity())
43261 return { result: false, reason: 'Invalid public key' };
43262 if (!pub.validate())
43263 return { result: false, reason: 'Public key is not a point' };
43264 if (!pub.mul(this.ec.curve.n).isInfinity())
43265 return { result: false, reason: 'Public key * N != O' };
43266
43267 return { result: true, reason: null };
43268};
43269
43270KeyPair.prototype.getPublic = function getPublic(enc, compact) {
43271 if (!this.pub)
43272 this.pub = this.ec.g.mul(this.priv);
43273
43274 if (!enc)
43275 return this.pub;
43276
43277 return this.pub.encode(enc, compact);
43278};
43279
43280KeyPair.prototype.getPrivate = function getPrivate(enc) {
43281 if (enc === 'hex')
43282 return this.priv.toString(16, 2);
43283 else
43284 return this.priv;
43285};
43286
43287KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
43288 this.priv = new bn(key, enc || 16);
43289
43290 // For Curve25519/Curve448 we have a specific procedure.
43291 // TODO Curve448
43292 if (this.ec.curve.type === 'mont') {
43293 var one = this.ec.curve.one;
43294 var mask = one.ushln(255 - 3).sub(one).ushln(3);
43295 this.priv = this.priv.or(one.ushln(255 - 1));
43296 this.priv = this.priv.and(mask);
43297 } else
43298 // Ensure that the priv won't be bigger than n, otherwise we may fail
43299 // in fixed multiplication method
43300 this.priv = this.priv.umod(this.ec.curve.n);
43301};
43302
43303KeyPair.prototype._importPublic = function _importPublic(key, enc) {
43304 if (key.x || key.y) {
43305 // Montgomery points only have an `x` coordinate.
43306 // Weierstrass/Edwards points on the other hand have both `x` and
43307 // `y` coordinates.
43308 if (this.ec.curve.type === 'mont') {
43309 assert$5(key.x, 'Need x coordinate');
43310 } else if (this.ec.curve.type === 'short' ||
43311 this.ec.curve.type === 'edwards') {
43312 assert$5(key.x && key.y, 'Need both x and y coordinate');
43313 }
43314 this.pub = this.ec.curve.point(key.x, key.y);
43315 return;
43316 }
43317 this.pub = this.ec.curve.decodePoint(key, enc);
43318};
43319
43320// ECDH
43321KeyPair.prototype.derive = function derive(pub) {
43322 return pub.mul(this.priv).getX();
43323};
43324
43325// ECDSA
43326KeyPair.prototype.sign = function sign(msg, enc, options) {
43327 return this.ec.sign(msg, this, enc, options);
43328};
43329
43330KeyPair.prototype.verify = function verify(msg, signature) {
43331 return this.ec.verify(msg, signature, this);
43332};
43333
43334KeyPair.prototype.inspect = function inspect() {
43335 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
43336 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
43337};
43338
43339var assert$6 = utils_1$1.assert;
43340
43341function Signature$1(options, enc) {
43342 if (options instanceof Signature$1)
43343 return options;
43344
43345 if (this._importDER(options, enc))
43346 return;
43347
43348 assert$6(options.r && options.s, 'Signature without r or s');
43349 this.r = new bn(options.r, 16);
43350 this.s = new bn(options.s, 16);
43351 if (options.recoveryParam === undefined)
43352 this.recoveryParam = null;
43353 else
43354 this.recoveryParam = options.recoveryParam;
43355}
43356var signature$1 = Signature$1;
43357
43358function Position() {
43359 this.place = 0;
43360}
43361
43362function getLength(buf, p) {
43363 var initial = buf[p.place++];
43364 if (!(initial & 0x80)) {
43365 return initial;
43366 }
43367 var octetLen = initial & 0xf;
43368 var val = 0;
43369 for (var i = 0, off = p.place; i < octetLen; i++, off++) {
43370 val <<= 8;
43371 val |= buf[off];
43372 }
43373 p.place = off;
43374 return val;
43375}
43376
43377function rmPadding(buf) {
43378 var i = 0;
43379 var len = buf.length - 1;
43380 while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
43381 i++;
43382 }
43383 if (i === 0) {
43384 return buf;
43385 }
43386 return buf.slice(i);
43387}
43388
43389Signature$1.prototype._importDER = function _importDER(data, enc) {
43390 data = utils_1$1.toArray(data, enc);
43391 var p = new Position();
43392 if (data[p.place++] !== 0x30) {
43393 return false;
43394 }
43395 var len = getLength(data, p);
43396 if ((len + p.place) !== data.length) {
43397 return false;
43398 }
43399 if (data[p.place++] !== 0x02) {
43400 return false;
43401 }
43402 var rlen = getLength(data, p);
43403 var r = data.slice(p.place, rlen + p.place);
43404 p.place += rlen;
43405 if (data[p.place++] !== 0x02) {
43406 return false;
43407 }
43408 var slen = getLength(data, p);
43409 if (data.length !== slen + p.place) {
43410 return false;
43411 }
43412 var s = data.slice(p.place, slen + p.place);
43413 if (r[0] === 0 && (r[1] & 0x80)) {
43414 r = r.slice(1);
43415 }
43416 if (s[0] === 0 && (s[1] & 0x80)) {
43417 s = s.slice(1);
43418 }
43419
43420 this.r = new bn(r);
43421 this.s = new bn(s);
43422 this.recoveryParam = null;
43423
43424 return true;
43425};
43426
43427function constructLength(arr, len) {
43428 if (len < 0x80) {
43429 arr.push(len);
43430 return;
43431 }
43432 var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
43433 arr.push(octets | 0x80);
43434 while (--octets) {
43435 arr.push((len >>> (octets << 3)) & 0xff);
43436 }
43437 arr.push(len);
43438}
43439
43440Signature$1.prototype.toDER = function toDER(enc) {
43441 var r = this.r.toArray();
43442 var s = this.s.toArray();
43443
43444 // Pad values
43445 if (r[0] & 0x80)
43446 r = [ 0 ].concat(r);
43447 // Pad values
43448 if (s[0] & 0x80)
43449 s = [ 0 ].concat(s);
43450
43451 r = rmPadding(r);
43452 s = rmPadding(s);
43453
43454 while (!s[0] && !(s[1] & 0x80)) {
43455 s = s.slice(1);
43456 }
43457 var arr = [ 0x02 ];
43458 constructLength(arr, r.length);
43459 arr = arr.concat(r);
43460 arr.push(0x02);
43461 constructLength(arr, s.length);
43462 var backHalf = arr.concat(s);
43463 var res = [ 0x30 ];
43464 constructLength(res, backHalf.length);
43465 res = res.concat(backHalf);
43466 return utils_1$1.encode(res, enc);
43467};
43468
43469var assert$7 = utils_1$1.assert;
43470
43471
43472
43473
43474function EC(options) {
43475 if (!(this instanceof EC))
43476 return new EC(options);
43477
43478 // Shortcut `elliptic.ec(curve-name)`
43479 if (typeof options === 'string') {
43480 assert$7(curves_1.hasOwnProperty(options), 'Unknown curve ' + options);
43481
43482 options = curves_1[options];
43483 }
43484
43485 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
43486 if (options instanceof curves_1.PresetCurve)
43487 options = { curve: options };
43488
43489 this.curve = options.curve.curve;
43490 this.n = this.curve.n;
43491 this.nh = this.n.ushrn(1);
43492 this.g = this.curve.g;
43493
43494 // Point on curve
43495 this.g = options.curve.g;
43496 this.g.precompute(options.curve.n.bitLength() + 1);
43497
43498 // Hash function for DRBG
43499 this.hash = options.hash || options.curve.hash;
43500}
43501var ec = EC;
43502
43503EC.prototype.keyPair = function keyPair(options) {
43504 return new key(this, options);
43505};
43506
43507EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
43508 return key.fromPrivate(this, priv, enc);
43509};
43510
43511EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
43512 return key.fromPublic(this, pub, enc);
43513};
43514
43515EC.prototype.genKeyPair = function genKeyPair(options) {
43516 if (!options)
43517 options = {};
43518
43519 // Instantiate Hmac_DRBG
43520 var drbg = new hmacDrbg({
43521 hash: this.hash,
43522 pers: options.pers,
43523 persEnc: options.persEnc || 'utf8',
43524 entropy: options.entropy || brorand(this.hash.hmacStrength),
43525 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
43526 nonce: this.n.toArray()
43527 });
43528
43529 // Key generation for curve25519 is simpler
43530 if (this.curve.type === 'mont') {
43531 var priv = new bn(drbg.generate(32));
43532 return this.keyFromPrivate(priv);
43533 }
43534
43535 var bytes = this.n.byteLength();
43536 var ns2 = this.n.sub(new bn(2));
43537 do {
43538 var priv = new bn(drbg.generate(bytes));
43539 if (priv.cmp(ns2) > 0)
43540 continue;
43541
43542 priv.iaddn(1);
43543 return this.keyFromPrivate(priv);
43544 } while (true);
43545};
43546
43547EC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) {
43548 bitSize = bitSize || msg.byteLength() * 8;
43549 var delta = bitSize - this.n.bitLength();
43550 if (delta > 0)
43551 msg = msg.ushrn(delta);
43552 if (!truncOnly && msg.cmp(this.n) >= 0)
43553 return msg.sub(this.n);
43554 else
43555 return msg;
43556};
43557
43558EC.prototype.truncateMsg = function truncateMSG(msg) {
43559 // Bit size is only determined correctly for Uint8Arrays and hex strings
43560 var bitSize;
43561 if (msg instanceof Uint8Array) {
43562 bitSize = msg.byteLength * 8;
43563 msg = this._truncateToN(new bn(msg, 16), false, bitSize);
43564 } else if (typeof msg === 'string') {
43565 bitSize = msg.length * 4;
43566 msg = this._truncateToN(new bn(msg, 16), false, bitSize);
43567 } else {
43568 msg = this._truncateToN(new bn(msg, 16));
43569 }
43570 return msg;
43571};
43572
43573EC.prototype.sign = function sign(msg, key, enc, options) {
43574 if (typeof enc === 'object') {
43575 options = enc;
43576 enc = null;
43577 }
43578 if (!options)
43579 options = {};
43580
43581 key = this.keyFromPrivate(key, enc);
43582 msg = this.truncateMsg(msg);
43583
43584 // Zero-extend key to provide enough entropy
43585 var bytes = this.n.byteLength();
43586 var bkey = key.getPrivate().toArray('be', bytes);
43587
43588 // Zero-extend nonce to have the same byte size as N
43589 var nonce = msg.toArray('be', bytes);
43590
43591 // Instantiate Hmac_DRBG
43592 var drbg = new hmacDrbg({
43593 hash: this.hash,
43594 entropy: bkey,
43595 nonce: nonce,
43596 pers: options.pers,
43597 persEnc: options.persEnc || 'utf8'
43598 });
43599
43600 // Number of bytes to generate
43601 var ns1 = this.n.sub(new bn(1));
43602
43603 for (var iter = 0; true; iter++) {
43604 var k = options.k ?
43605 options.k(iter) :
43606 new bn(drbg.generate(this.n.byteLength()));
43607 k = this._truncateToN(k, true);
43608 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
43609 continue;
43610
43611 var kp = this.g.mul(k);
43612 if (kp.isInfinity())
43613 continue;
43614
43615 var kpX = kp.getX();
43616 var r = kpX.umod(this.n);
43617 if (r.cmpn(0) === 0)
43618 continue;
43619
43620 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
43621 s = s.umod(this.n);
43622 if (s.cmpn(0) === 0)
43623 continue;
43624
43625 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
43626 (kpX.cmp(r) !== 0 ? 2 : 0);
43627
43628 // Use complement of `s`, if it is > `n / 2`
43629 if (options.canonical && s.cmp(this.nh) > 0) {
43630 s = this.n.sub(s);
43631 recoveryParam ^= 1;
43632 }
43633
43634 return new signature$1({ r: r, s: s, recoveryParam: recoveryParam });
43635 }
43636};
43637
43638EC.prototype.verify = function verify(msg, signature, key, enc) {
43639 key = this.keyFromPublic(key, enc);
43640 signature = new signature$1(signature, 'hex');
43641 // Fallback to the old code
43642 var ret = this._verify(this.truncateMsg(msg), signature, key) ||
43643 this._verify(this._truncateToN(new bn(msg, 16)), signature, key);
43644 return ret;
43645};
43646
43647EC.prototype._verify = function _verify(msg, signature, key) {
43648 // Perform primitive values validation
43649 var r = signature.r;
43650 var s = signature.s;
43651 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
43652 return false;
43653 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
43654 return false;
43655
43656 // Validate signature
43657 var sinv = s.invm(this.n);
43658 var u1 = sinv.mul(msg).umod(this.n);
43659 var u2 = sinv.mul(r).umod(this.n);
43660
43661 if (!this.curve._maxwellTrick) {
43662 var p = this.g.mulAdd(u1, key.getPublic(), u2);
43663 if (p.isInfinity())
43664 return false;
43665
43666 return p.getX().umod(this.n).cmp(r) === 0;
43667 }
43668
43669 // NOTE: Greg Maxwell's trick, inspired by:
43670 // https://git.io/vad3K
43671
43672 var p = this.g.jmulAdd(u1, key.getPublic(), u2);
43673 if (p.isInfinity())
43674 return false;
43675
43676 // Compare `p.x` of Jacobian point with `r`,
43677 // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
43678 // inverse of `p.z^2`
43679 return p.eqXToP(r);
43680};
43681
43682EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
43683 assert$7((3 & j) === j, 'The recovery param is more than two bits');
43684 signature = new signature$1(signature, enc);
43685
43686 var n = this.n;
43687 var e = new bn(msg);
43688 var r = signature.r;
43689 var s = signature.s;
43690
43691 // A set LSB signifies that the y-coordinate is odd
43692 var isYOdd = j & 1;
43693 var isSecondKey = j >> 1;
43694 if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
43695 throw new Error('Unable to find sencond key candinate');
43696
43697 // 1.1. Let x = r + jn.
43698 if (isSecondKey)
43699 r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
43700 else
43701 r = this.curve.pointFromX(r, isYOdd);
43702
43703 var rInv = signature.r.invm(n);
43704 var s1 = n.sub(e).mul(rInv).umod(n);
43705 var s2 = s.mul(rInv).umod(n);
43706
43707 // 1.6.1 Compute Q = r^-1 (sR - eG)
43708 // Q = r^-1 (sR + -eG)
43709 return this.g.mulAdd(s1, r, s2);
43710};
43711
43712EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
43713 signature = new signature$1(signature, enc);
43714 if (signature.recoveryParam !== null)
43715 return signature.recoveryParam;
43716
43717 for (var i = 0; i < 4; i++) {
43718 var Qprime;
43719 try {
43720 Qprime = this.recoverPubKey(e, signature, i);
43721 } catch (e) {
43722 continue;
43723 }
43724
43725 if (Qprime.eq(Q))
43726 return i;
43727 }
43728 throw new Error('Unable to find valid recovery factor');
43729};
43730
43731var assert$8 = utils_1$1.assert;
43732var parseBytes = utils_1$1.parseBytes;
43733var cachedProperty = utils_1$1.cachedProperty;
43734
43735/**
43736* @param {EDDSA} eddsa - instance
43737* @param {Object} params - public/private key parameters
43738*
43739* @param {Array<Byte>} [params.secret] - secret seed bytes
43740* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
43741* @param {Array<Byte>} [params.pub] - public key point encoded as bytes
43742*
43743*/
43744function KeyPair$1(eddsa, params) {
43745 this.eddsa = eddsa;
43746 if (params.hasOwnProperty('secret'))
43747 this._secret = parseBytes(params.secret);
43748 if (eddsa.isPoint(params.pub))
43749 this._pub = params.pub;
43750 else {
43751 this._pubBytes = parseBytes(params.pub);
43752 if (this._pubBytes && this._pubBytes.length === 33 &&
43753 this._pubBytes[0] === 0x40)
43754 this._pubBytes = this._pubBytes.slice(1, 33);
43755 if (this._pubBytes && this._pubBytes.length !== 32)
43756 throw new Error('Unknown point compression format');
43757 }
43758}
43759
43760KeyPair$1.fromPublic = function fromPublic(eddsa, pub) {
43761 if (pub instanceof KeyPair$1)
43762 return pub;
43763 return new KeyPair$1(eddsa, { pub: pub });
43764};
43765
43766KeyPair$1.fromSecret = function fromSecret(eddsa, secret) {
43767 if (secret instanceof KeyPair$1)
43768 return secret;
43769 return new KeyPair$1(eddsa, { secret: secret });
43770};
43771
43772KeyPair$1.prototype.secret = function secret() {
43773 return this._secret;
43774};
43775
43776cachedProperty(KeyPair$1, 'pubBytes', function pubBytes() {
43777 return this.eddsa.encodePoint(this.pub());
43778});
43779
43780cachedProperty(KeyPair$1, 'pub', function pub() {
43781 if (this._pubBytes)
43782 return this.eddsa.decodePoint(this._pubBytes);
43783 return this.eddsa.g.mul(this.priv());
43784});
43785
43786cachedProperty(KeyPair$1, 'privBytes', function privBytes() {
43787 var eddsa = this.eddsa;
43788 var hash = this.hash();
43789 var lastIx = eddsa.encodingLength - 1;
43790
43791 // https://tools.ietf.org/html/rfc8032#section-5.1.5
43792 var a = hash.slice(0, eddsa.encodingLength);
43793 a[0] &= 248;
43794 a[lastIx] &= 127;
43795 a[lastIx] |= 64;
43796
43797 return a;
43798});
43799
43800cachedProperty(KeyPair$1, 'priv', function priv() {
43801 return this.eddsa.decodeInt(this.privBytes());
43802});
43803
43804cachedProperty(KeyPair$1, 'hash', function hash() {
43805 return this.eddsa.hash().update(this.secret()).digest();
43806});
43807
43808cachedProperty(KeyPair$1, 'messagePrefix', function messagePrefix() {
43809 return this.hash().slice(this.eddsa.encodingLength);
43810});
43811
43812KeyPair$1.prototype.sign = function sign(message) {
43813 assert$8(this._secret, 'KeyPair can only verify');
43814 return this.eddsa.sign(message, this);
43815};
43816
43817KeyPair$1.prototype.verify = function verify(message, sig) {
43818 return this.eddsa.verify(message, sig, this);
43819};
43820
43821KeyPair$1.prototype.getSecret = function getSecret(enc) {
43822 assert$8(this._secret, 'KeyPair is public only');
43823 return utils_1$1.encode(this.secret(), enc);
43824};
43825
43826KeyPair$1.prototype.getPublic = function getPublic(enc, compact) {
43827 return utils_1$1.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc);
43828};
43829
43830var key$1 = KeyPair$1;
43831
43832var assert$9 = utils_1$1.assert;
43833var cachedProperty$1 = utils_1$1.cachedProperty;
43834var parseBytes$1 = utils_1$1.parseBytes;
43835
43836/**
43837* @param {EDDSA} eddsa - eddsa instance
43838* @param {Array<Bytes>|Object} sig -
43839* @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
43840* @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
43841* @param {Array<Bytes>} [sig.Rencoded] - R point encoded
43842* @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
43843*/
43844function Signature$2(eddsa, sig) {
43845 this.eddsa = eddsa;
43846
43847 if (typeof sig !== 'object')
43848 sig = parseBytes$1(sig);
43849
43850 if (Array.isArray(sig)) {
43851 sig = {
43852 R: sig.slice(0, eddsa.encodingLength),
43853 S: sig.slice(eddsa.encodingLength)
43854 };
43855 }
43856
43857 assert$9(sig.R && sig.S, 'Signature without R or S');
43858
43859 if (eddsa.isPoint(sig.R))
43860 this._R = sig.R;
43861 if (sig.S instanceof bn)
43862 this._S = sig.S;
43863
43864 this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
43865 this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
43866}
43867
43868cachedProperty$1(Signature$2, 'S', function S() {
43869 return this.eddsa.decodeInt(this.Sencoded());
43870});
43871
43872cachedProperty$1(Signature$2, 'R', function R() {
43873 return this.eddsa.decodePoint(this.Rencoded());
43874});
43875
43876cachedProperty$1(Signature$2, 'Rencoded', function Rencoded() {
43877 return this.eddsa.encodePoint(this.R());
43878});
43879
43880cachedProperty$1(Signature$2, 'Sencoded', function Sencoded() {
43881 return this.eddsa.encodeInt(this.S());
43882});
43883
43884Signature$2.prototype.toBytes = function toBytes() {
43885 return this.Rencoded().concat(this.Sencoded());
43886};
43887
43888Signature$2.prototype.toHex = function toHex() {
43889 return utils_1$1.encode(this.toBytes(), 'hex').toUpperCase();
43890};
43891
43892var signature$2 = Signature$2;
43893
43894var assert$a = utils_1$1.assert;
43895var parseBytes$2 = utils_1$1.parseBytes;
43896
43897
43898
43899function EDDSA(curve) {
43900 assert$a(curve === 'ed25519', 'only tested with ed25519 so far');
43901
43902 if (!(this instanceof EDDSA))
43903 return new EDDSA(curve);
43904
43905 var curve = curves_1[curve].curve;
43906 this.curve = curve;
43907 this.g = curve.g;
43908 this.g.precompute(curve.n.bitLength() + 1);
43909
43910 this.pointClass = curve.point().constructor;
43911 this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
43912 this.hash = hash_1.sha512;
43913}
43914
43915var eddsa$1 = EDDSA;
43916
43917/**
43918* @param {Array|String} message - message bytes
43919* @param {Array|String|KeyPair} secret - secret bytes or a keypair
43920* @returns {Signature} - signature
43921*/
43922EDDSA.prototype.sign = function sign(message, secret) {
43923 message = parseBytes$2(message);
43924 var key = this.keyFromSecret(secret);
43925 var r = this.hashInt(key.messagePrefix(), message);
43926 var R = this.g.mul(r);
43927 var Rencoded = this.encodePoint(R);
43928 var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
43929 .mul(key.priv());
43930 var S = r.add(s_).umod(this.curve.n);
43931 return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
43932};
43933
43934/**
43935* @param {Array} message - message bytes
43936* @param {Array|String|Signature} sig - sig bytes
43937* @param {Array|String|Point|KeyPair} pub - public key
43938* @returns {Boolean} - true if public key matches sig of message
43939*/
43940EDDSA.prototype.verify = function verify(message, sig, pub) {
43941 message = parseBytes$2(message);
43942 sig = this.makeSignature(sig);
43943 var key = this.keyFromPublic(pub);
43944 var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
43945 var SG = this.g.mul(sig.S());
43946 var RplusAh = sig.R().add(key.pub().mul(h));
43947 return RplusAh.eq(SG);
43948};
43949
43950EDDSA.prototype.hashInt = function hashInt() {
43951 var hash = this.hash();
43952 for (var i = 0; i < arguments.length; i++)
43953 hash.update(arguments[i]);
43954 return utils_1$1.intFromLE(hash.digest()).umod(this.curve.n);
43955};
43956
43957EDDSA.prototype.keyPair = function keyPair(options) {
43958 return new key$1(this, options);
43959};
43960
43961EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
43962 return key$1.fromPublic(this, pub);
43963};
43964
43965EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
43966 return key$1.fromSecret(this, secret);
43967};
43968
43969EDDSA.prototype.genKeyPair = function genKeyPair(options) {
43970 if (!options)
43971 options = {};
43972
43973 // Instantiate Hmac_DRBG
43974 var drbg = new hmacDrbg({
43975 hash: this.hash,
43976 pers: options.pers,
43977 persEnc: options.persEnc || 'utf8',
43978 entropy: options.entropy || brorand(this.hash.hmacStrength),
43979 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
43980 nonce: this.curve.n.toArray()
43981 });
43982
43983 return this.keyFromSecret(drbg.generate(32));
43984};
43985
43986EDDSA.prototype.makeSignature = function makeSignature(sig) {
43987 if (sig instanceof signature$2)
43988 return sig;
43989 return new signature$2(this, sig);
43990};
43991
43992/**
43993* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
43994*
43995* EDDSA defines methods for encoding and decoding points and integers. These are
43996* helper convenience methods, that pass along to utility functions implied
43997* parameters.
43998*
43999*/
44000EDDSA.prototype.encodePoint = function encodePoint(point) {
44001 var enc = point.getY().toArray('le', this.encodingLength);
44002 enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
44003 return enc;
44004};
44005
44006EDDSA.prototype.decodePoint = function decodePoint(bytes) {
44007 bytes = utils_1$1.parseBytes(bytes);
44008
44009 var lastIx = bytes.length - 1;
44010 var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
44011 var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
44012
44013 var y = utils_1$1.intFromLE(normed);
44014 return this.curve.pointFromY(y, xIsOdd);
44015};
44016
44017EDDSA.prototype.encodeInt = function encodeInt(num) {
44018 return num.toArray('le', this.encodingLength);
44019};
44020
44021EDDSA.prototype.decodeInt = function decodeInt(bytes) {
44022 return utils_1$1.intFromLE(bytes);
44023};
44024
44025EDDSA.prototype.isPoint = function isPoint(val) {
44026 return val instanceof this.pointClass;
44027};
44028
44029var elliptic_1 = createCommonjsModule(function (module, exports) {
44030
44031var elliptic = exports;
44032
44033elliptic.utils = utils_1$1;
44034elliptic.rand = brorand;
44035elliptic.curve = curve_1;
44036elliptic.curves = curves_1;
44037
44038// Protocols
44039elliptic.ec = ec;
44040elliptic.eddsa = eddsa$1;
44041});
44042
44043var elliptic$1 = /*#__PURE__*/Object.freeze({
44044 __proto__: null,
44045 'default': elliptic_1,
44046 __moduleExports: elliptic_1
44047});
44048
44049export { AEADEncryptedDataPacket, CleartextMessage, CompressedDataPacket, LiteralDataPacket, MarkerPacket, Message, OnePassSignaturePacket, PacketList, PrivateKey, PublicKey, PublicKeyEncryptedSessionKeyPacket, PublicKeyPacket, PublicSubkeyPacket, SecretKeyPacket, SecretSubkeyPacket, Signature, SignaturePacket, Subkey, SymEncryptedIntegrityProtectedDataPacket, SymEncryptedSessionKeyPacket, SymmetricallyEncryptedDataPacket, TrustPacket, UnparseablePacket, UserAttributePacket, UserIDPacket, armor, config, createCleartextMessage, createMessage, decrypt$5 as decrypt, decryptKey, decryptSessionKeys, encrypt$5 as encrypt, encryptKey, encryptSessionKey, enums, generateKey, generateSessionKey$1 as generateSessionKey, readCleartextMessage, readKey, readKeys, readMessage, readPrivateKey, readPrivateKeys, readSignature, reformatKey, revokeKey, sign$6 as sign, unarmor, verify$6 as verify };