UNPKG

1.53 MBJavaScriptView Raw
1/*! OpenPGP.js v5.0.0 - 2021-09-02 - this is LGPL licensed code, see LICENSE/our website https://openpgpjs.org/ for more information. */
2var openpgp = (function (exports) {
3 'use strict';
4
5 const globalThis = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
6
7 const doneWritingPromise = Symbol('doneWritingPromise');
8 const doneWritingResolve = Symbol('doneWritingResolve');
9 const doneWritingReject = Symbol('doneWritingReject');
10
11 class ArrayStream extends Array {
12 constructor() {
13 super();
14 this[doneWritingPromise] = new Promise((resolve, reject) => {
15 this[doneWritingResolve] = resolve;
16 this[doneWritingReject] = reject;
17 });
18 this[doneWritingPromise].catch(() => {});
19 }
20 }
21
22 ArrayStream.prototype.getReader = function() {
23 return {
24 read: async () => {
25 await this[doneWritingPromise];
26 if (!this.length) {
27 return { value: undefined, done: true };
28 }
29 return { value: this.shift(), done: false };
30 }
31 };
32 };
33
34 /**
35 * Check whether data is an ArrayStream
36 * @param {Any} input data to check
37 * @returns {boolean}
38 */
39 function isArrayStream(input) {
40 return input && input.getReader && Array.isArray(input);
41 }
42
43 /**
44 * A wrapper class over the native WritableStreamDefaultWriter.
45 * It also lets you "write data to" array streams instead of streams.
46 * @class
47 */
48 function Writer(input) {
49 if (!isArrayStream(input)) {
50 const writer = input.getWriter();
51 const releaseLock = writer.releaseLock;
52 writer.releaseLock = () => {
53 writer.closed.catch(function() {});
54 releaseLock.call(writer);
55 };
56 return writer;
57 }
58 this.stream = input;
59 }
60
61 /**
62 * Write a chunk of data.
63 * @returns {Promise<undefined>}
64 * @async
65 */
66 Writer.prototype.write = async function(chunk) {
67 this.stream.push(chunk);
68 };
69
70 /**
71 * Close the stream.
72 * @returns {Promise<undefined>}
73 * @async
74 */
75 Writer.prototype.close = async function() {
76 this.stream[doneWritingResolve]();
77 };
78
79 /**
80 * Error the stream.
81 * @returns {Promise<Object>}
82 * @async
83 */
84 Writer.prototype.abort = async function(reason) {
85 this.stream[doneWritingReject](reason);
86 return reason;
87 };
88
89 /**
90 * Release the writer's lock.
91 * @returns {undefined}
92 * @async
93 */
94 Writer.prototype.releaseLock = function() {};
95
96 const isNode = typeof globalThis.process === 'object' &&
97 typeof globalThis.process.versions === 'object';
98
99 const NodeReadableStream = isNode && void('stream').Readable;
100
101 /**
102 * Check whether data is a Stream, and if so of which type
103 * @param {Any} input data to check
104 * @returns {'web'|'ponyfill'|'node'|'array'|'web-like'|false}
105 */
106 function isStream(input) {
107 if (isArrayStream(input)) {
108 return 'array';
109 }
110 if (globalThis.ReadableStream && globalThis.ReadableStream.prototype.isPrototypeOf(input)) {
111 return 'web';
112 }
113 if (ReadableStream && ReadableStream.prototype.isPrototypeOf(input)) {
114 return 'ponyfill';
115 }
116 if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) {
117 return 'node';
118 }
119 if (input && input.getReader) {
120 return 'web-like';
121 }
122 return false;
123 }
124
125 /**
126 * Check whether data is a Uint8Array
127 * @param {Any} input data to check
128 * @returns {Boolean}
129 */
130 function isUint8Array(input) {
131 return Uint8Array.prototype.isPrototypeOf(input);
132 }
133
134 /**
135 * Concat Uint8Arrays
136 * @param {Array<Uint8array>} Array of Uint8Arrays to concatenate
137 * @returns {Uint8array} Concatenated array
138 */
139 function concatUint8Array(arrays) {
140 if (arrays.length === 1) return arrays[0];
141
142 let totalLength = 0;
143 for (let i = 0; i < arrays.length; i++) {
144 if (!isUint8Array(arrays[i])) {
145 throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');
146 }
147
148 totalLength += arrays[i].length;
149 }
150
151 const result = new Uint8Array(totalLength);
152 let pos = 0;
153 arrays.forEach(function (element) {
154 result.set(element, pos);
155 pos += element.length;
156 });
157
158 return result;
159 }
160
161 const NodeBuffer = isNode && void('buffer').Buffer;
162 const NodeReadableStream$1 = isNode && void('stream').Readable;
163
164 /**
165 * Web / node stream conversion functions
166 * From https://github.com/gwicke/node-web-streams
167 */
168
169 let nodeToWeb;
170 let webToNode;
171
172 if (NodeReadableStream$1) {
173
174 /**
175 * Convert a Node Readable Stream to a Web ReadableStream
176 * @param {Readable} nodeStream
177 * @returns {ReadableStream}
178 */
179 nodeToWeb = function(nodeStream) {
180 let canceled = false;
181 return new ReadableStream({
182 start(controller) {
183 nodeStream.pause();
184 nodeStream.on('data', chunk => {
185 if (canceled) {
186 return;
187 }
188 if (NodeBuffer.isBuffer(chunk)) {
189 chunk = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
190 }
191 controller.enqueue(chunk);
192 nodeStream.pause();
193 });
194 nodeStream.on('end', () => {
195 if (canceled) {
196 return;
197 }
198 controller.close();
199 });
200 nodeStream.on('error', e => controller.error(e));
201 },
202 pull() {
203 nodeStream.resume();
204 },
205 cancel(reason) {
206 canceled = true;
207 nodeStream.destroy(reason);
208 }
209 });
210 };
211
212
213 class NodeReadable extends NodeReadableStream$1 {
214 constructor(webStream, options) {
215 super(options);
216 this._reader = getReader(webStream);
217 }
218
219 async _read(size) {
220 try {
221 while (true) {
222 const { done, value } = await this._reader.read();
223 if (done) {
224 this.push(null);
225 break;
226 }
227 if (!this.push(value) || this._cancelling) {
228 this._reading = false;
229 break;
230 }
231 }
232 } catch(e) {
233 this.emit('error', e);
234 }
235 }
236
237 _destroy(reason) {
238 this._reader.cancel(reason);
239 }
240 }
241
242 /**
243 * Convert a Web ReadableStream to a Node Readable Stream
244 * @param {ReadableStream} webStream
245 * @param {Object} options
246 * @returns {Readable}
247 */
248 webToNode = function(webStream, options) {
249 return new NodeReadable(webStream, options);
250 };
251
252 }
253
254 const doneReadingSet = new WeakSet();
255 const externalBuffer = Symbol('externalBuffer');
256
257 /**
258 * A wrapper class over the native ReadableStreamDefaultReader.
259 * This additionally implements pushing back data on the stream, which
260 * lets us implement peeking and a host of convenience functions.
261 * It also lets you read data other than streams, such as a Uint8Array.
262 * @class
263 */
264 function Reader(input) {
265 this.stream = input;
266 if (input[externalBuffer]) {
267 this[externalBuffer] = input[externalBuffer].slice();
268 }
269 if (isArrayStream(input)) {
270 const reader = input.getReader();
271 this._read = reader.read.bind(reader);
272 this._releaseLock = () => {};
273 this._cancel = () => {};
274 return;
275 }
276 let streamType = isStream(input);
277 if (streamType === 'node') {
278 input = nodeToWeb(input);
279 }
280 if (streamType) {
281 const reader = input.getReader();
282 this._read = reader.read.bind(reader);
283 this._releaseLock = () => {
284 reader.closed.catch(function() {});
285 reader.releaseLock();
286 };
287 this._cancel = reader.cancel.bind(reader);
288 return;
289 }
290 let doneReading = false;
291 this._read = async () => {
292 if (doneReading || doneReadingSet.has(input)) {
293 return { value: undefined, done: true };
294 }
295 doneReading = true;
296 return { value: input, done: false };
297 };
298 this._releaseLock = () => {
299 if (doneReading) {
300 try {
301 doneReadingSet.add(input);
302 } catch(e) {}
303 }
304 };
305 }
306
307 /**
308 * Read a chunk of data.
309 * @returns {Promise<Object>} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }
310 * @async
311 */
312 Reader.prototype.read = async function() {
313 if (this[externalBuffer] && this[externalBuffer].length) {
314 const value = this[externalBuffer].shift();
315 return { done: false, value };
316 }
317 return this._read();
318 };
319
320 /**
321 * Allow others to read the stream.
322 */
323 Reader.prototype.releaseLock = function() {
324 if (this[externalBuffer]) {
325 this.stream[externalBuffer] = this[externalBuffer];
326 }
327 this._releaseLock();
328 };
329
330 /**
331 * Cancel the stream.
332 */
333 Reader.prototype.cancel = function(reason) {
334 return this._cancel(reason);
335 };
336
337 /**
338 * Read up to and including the first \n character.
339 * @returns {Promise<String|Undefined>}
340 * @async
341 */
342 Reader.prototype.readLine = async function() {
343 let buffer = [];
344 let returnVal;
345 while (!returnVal) {
346 let { done, value } = await this.read();
347 value += '';
348 if (done) {
349 if (buffer.length) return concat(buffer);
350 return;
351 }
352 const lineEndIndex = value.indexOf('\n') + 1;
353 if (lineEndIndex) {
354 returnVal = concat(buffer.concat(value.substr(0, lineEndIndex)));
355 buffer = [];
356 }
357 if (lineEndIndex !== value.length) {
358 buffer.push(value.substr(lineEndIndex));
359 }
360 }
361 this.unshift(...buffer);
362 return returnVal;
363 };
364
365 /**
366 * Read a single byte/character.
367 * @returns {Promise<Number|String|Undefined>}
368 * @async
369 */
370 Reader.prototype.readByte = async function() {
371 const { done, value } = await this.read();
372 if (done) return;
373 const byte = value[0];
374 this.unshift(slice(value, 1));
375 return byte;
376 };
377
378 /**
379 * Read a specific amount of bytes/characters, unless the stream ends before that amount.
380 * @returns {Promise<Uint8Array|String|Undefined>}
381 * @async
382 */
383 Reader.prototype.readBytes = async function(length) {
384 const buffer = [];
385 let bufferLength = 0;
386 while (true) {
387 const { done, value } = await this.read();
388 if (done) {
389 if (buffer.length) return concat(buffer);
390 return;
391 }
392 buffer.push(value);
393 bufferLength += value.length;
394 if (bufferLength >= length) {
395 const bufferConcat = concat(buffer);
396 this.unshift(slice(bufferConcat, length));
397 return slice(bufferConcat, 0, length);
398 }
399 }
400 };
401
402 /**
403 * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.
404 * @returns {Promise<Uint8Array|String|Undefined>}
405 * @async
406 */
407 Reader.prototype.peekBytes = async function(length) {
408 const bytes = await this.readBytes(length);
409 this.unshift(bytes);
410 return bytes;
411 };
412
413 /**
414 * Push data to the front of the stream.
415 * Data must have been read in the last call to read*.
416 * @param {...(Uint8Array|String|Undefined)} values
417 */
418 Reader.prototype.unshift = function(...values) {
419 if (!this[externalBuffer]) {
420 this[externalBuffer] = [];
421 }
422 if (
423 values.length === 1 && isUint8Array(values[0]) &&
424 this[externalBuffer].length && values[0].length &&
425 this[externalBuffer][0].byteOffset >= values[0].length
426 ) {
427 this[externalBuffer][0] = new Uint8Array(
428 this[externalBuffer][0].buffer,
429 this[externalBuffer][0].byteOffset - values[0].length,
430 this[externalBuffer][0].byteLength + values[0].length
431 );
432 return;
433 }
434 this[externalBuffer].unshift(...values.filter(value => value && value.length));
435 };
436
437 /**
438 * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).
439 * @param {Function} join
440 * @returns {Promise<Uint8array|String|Any>} the return value of join()
441 * @async
442 */
443 Reader.prototype.readToEnd = async function(join=concat) {
444 const result = [];
445 while (true) {
446 const { done, value } = await this.read();
447 if (done) break;
448 result.push(value);
449 }
450 return join(result);
451 };
452
453 let { ReadableStream, WritableStream, TransformStream } = globalThis;
454
455 let toPonyfillReadable, toNativeReadable;
456
457 async function loadStreamsPonyfill() {
458 if (TransformStream) {
459 return;
460 }
461
462 const [ponyfill, adapter] = await Promise.all([
463 Promise.resolve().then(function () { return ponyfill_es6; }),
464 Promise.resolve().then(function () { return webStreamsAdapter; })
465 ]);
466
467 ({ ReadableStream, WritableStream, TransformStream } = ponyfill);
468
469 const { createReadableStreamWrapper } = adapter;
470
471 if (globalThis.ReadableStream && ReadableStream !== globalThis.ReadableStream) {
472 toPonyfillReadable = createReadableStreamWrapper(ReadableStream);
473 toNativeReadable = createReadableStreamWrapper(globalThis.ReadableStream);
474 }
475 }
476
477 const NodeBuffer$1 = isNode && void('buffer').Buffer;
478
479 /**
480 * Convert data to Stream
481 * @param {ReadableStream|Uint8array|String} input data to convert
482 * @returns {ReadableStream} Converted data
483 */
484 function toStream(input) {
485 let streamType = isStream(input);
486 if (streamType === 'node') {
487 return nodeToWeb(input);
488 }
489 if (streamType === 'web' && toPonyfillReadable) {
490 return toPonyfillReadable(input);
491 }
492 if (streamType) {
493 return input;
494 }
495 return new ReadableStream({
496 start(controller) {
497 controller.enqueue(input);
498 controller.close();
499 }
500 });
501 }
502
503 /**
504 * Convert data to ArrayStream
505 * @param {Object} input data to convert
506 * @returns {ArrayStream} Converted data
507 */
508 function toArrayStream(input) {
509 if (isStream(input)) {
510 return input;
511 }
512 const stream = new ArrayStream();
513 (async () => {
514 const writer = getWriter(stream);
515 await writer.write(input);
516 await writer.close();
517 })();
518 return stream;
519 }
520
521 /**
522 * Concat a list of Uint8Arrays, Strings or Streams
523 * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
524 * @param {Array<Uint8array|String|ReadableStream>} Array of Uint8Arrays/Strings/Streams to concatenate
525 * @returns {Uint8array|String|ReadableStream} Concatenated array
526 */
527 function concat(list) {
528 if (list.some(stream => isStream(stream) && !isArrayStream(stream))) {
529 return concatStream(list);
530 }
531 if (list.some(stream => isArrayStream(stream))) {
532 return concatArrayStream(list);
533 }
534 if (typeof list[0] === 'string') {
535 return list.join('');
536 }
537 if (NodeBuffer$1 && NodeBuffer$1.isBuffer(list[0])) {
538 return NodeBuffer$1.concat(list);
539 }
540 return concatUint8Array(list);
541 }
542
543 /**
544 * Concat a list of Streams
545 * @param {Array<ReadableStream|Uint8array|String>} list Array of Uint8Arrays/Strings/Streams to concatenate
546 * @returns {ReadableStream} Concatenated list
547 */
548 function concatStream(list) {
549 list = list.map(toStream);
550 const transform = transformWithCancel(async function(reason) {
551 await Promise.all(transforms.map(stream => cancel(stream, reason)));
552 });
553 let prev = Promise.resolve();
554 const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {
555 prev = prev.then(() => pipe(readable, transform.writable, {
556 preventClose: i !== list.length - 1
557 }));
558 return prev;
559 }));
560 return transform.readable;
561 }
562
563 /**
564 * Concat a list of ArrayStreams
565 * @param {Array<ArrayStream|Uint8array|String>} list Array of Uint8Arrays/Strings/ArrayStreams to concatenate
566 * @returns {ArrayStream} Concatenated streams
567 */
568 function concatArrayStream(list) {
569 const result = new ArrayStream();
570 let prev = Promise.resolve();
571 list.forEach((stream, i) => {
572 prev = prev.then(() => pipe(stream, result, {
573 preventClose: i !== list.length - 1
574 }));
575 return prev;
576 });
577 return result;
578 }
579
580 /**
581 * Get a Reader
582 * @param {ReadableStream|Uint8array|String} input
583 * @returns {Reader}
584 */
585 function getReader(input) {
586 return new Reader(input);
587 }
588
589 /**
590 * Get a Writer
591 * @param {WritableStream} input
592 * @returns {Writer}
593 */
594 function getWriter(input) {
595 return new Writer(input);
596 }
597
598 /**
599 * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.
600 * @param {ReadableStream|Uint8array|String} input
601 * @param {WritableStream} target
602 * @param {Object} (optional) options
603 * @returns {Promise<undefined>} Promise indicating when piping has finished (input stream closed or errored)
604 * @async
605 */
606 async function pipe(input, target, {
607 preventClose = false,
608 preventAbort = false,
609 preventCancel = false
610 } = {}) {
611 if (isStream(input) && !isArrayStream(input)) {
612 input = toStream(input);
613 try {
614 if (input[externalBuffer]) {
615 const writer = getWriter(target);
616 for (let i = 0; i < input[externalBuffer].length; i++) {
617 await writer.ready;
618 await writer.write(input[externalBuffer][i]);
619 }
620 writer.releaseLock();
621 }
622 await input.pipeTo(target, {
623 preventClose,
624 preventAbort,
625 preventCancel
626 });
627 } catch(e) {}
628 return;
629 }
630 input = toArrayStream(input);
631 const reader = getReader(input);
632 const writer = getWriter(target);
633 try {
634 while (true) {
635 await writer.ready;
636 const { done, value } = await reader.read();
637 if (done) {
638 if (!preventClose) await writer.close();
639 break;
640 }
641 await writer.write(value);
642 }
643 } catch (e) {
644 if (!preventAbort) await writer.abort(e);
645 } finally {
646 reader.releaseLock();
647 writer.releaseLock();
648 }
649 }
650
651 /**
652 * Pipe a readable stream through a transform stream.
653 * @param {ReadableStream|Uint8array|String} input
654 * @param {Object} (optional) options
655 * @returns {ReadableStream} transformed stream
656 */
657 function transformRaw(input, options) {
658 const transformStream = new TransformStream(options);
659 pipe(input, transformStream.writable);
660 return transformStream.readable;
661 }
662
663 /**
664 * Create a cancelable TransformStream.
665 * @param {Function} cancel
666 * @returns {TransformStream}
667 */
668 function transformWithCancel(cancel) {
669 let pulled = false;
670 let backpressureChangePromiseResolve;
671 let outputController;
672 return {
673 readable: new ReadableStream({
674 start(controller) {
675 outputController = controller;
676 },
677 pull() {
678 if (backpressureChangePromiseResolve) {
679 backpressureChangePromiseResolve();
680 } else {
681 pulled = true;
682 }
683 },
684 cancel
685 }, {highWaterMark: 0}),
686 writable: new WritableStream({
687 write: async function(chunk) {
688 outputController.enqueue(chunk);
689 if (!pulled) {
690 await new Promise(resolve => {
691 backpressureChangePromiseResolve = resolve;
692 });
693 backpressureChangePromiseResolve = null;
694 } else {
695 pulled = false;
696 }
697 },
698 close: outputController.close.bind(outputController),
699 abort: outputController.error.bind(outputController)
700 })
701 };
702 }
703
704 /**
705 * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.
706 * @param {ReadableStream|Uint8array|String} input
707 * @param {Function} process
708 * @param {Function} finish
709 * @returns {ReadableStream|Uint8array|String}
710 */
711 function transform(input, process = () => undefined, finish = () => undefined) {
712 if (isArrayStream(input)) {
713 const output = new ArrayStream();
714 (async () => {
715 const data = await readToEnd(input);
716 const result1 = process(data);
717 const result2 = finish();
718 let result;
719 if (result1 !== undefined && result2 !== undefined) result = concat([result1, result2]);
720 else result = result1 !== undefined ? result1 : result2;
721 const writer = getWriter(output);
722 await writer.write(result);
723 await writer.close();
724 })();
725 return output;
726 }
727 if (isStream(input)) {
728 return transformRaw(input, {
729 async transform(value, controller) {
730 try {
731 const result = await process(value);
732 if (result !== undefined) controller.enqueue(result);
733 } catch(e) {
734 controller.error(e);
735 }
736 },
737 async flush(controller) {
738 try {
739 const result = await finish();
740 if (result !== undefined) controller.enqueue(result);
741 } catch(e) {
742 controller.error(e);
743 }
744 }
745 });
746 }
747 const result1 = process(input);
748 const result2 = finish();
749 if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);
750 return result1 !== undefined ? result1 : result2;
751 }
752
753 /**
754 * Transform a stream using a helper function which is passed a readable and a writable stream.
755 * This function also maintains the possibility to cancel the input stream,
756 * and does so on cancelation of the output stream, despite cancelation
757 * normally being impossible when the input stream is being read from.
758 * @param {ReadableStream|Uint8array|String} input
759 * @param {Function} fn
760 * @returns {ReadableStream}
761 */
762 function transformPair(input, fn) {
763 if (isStream(input) && !isArrayStream(input)) {
764 let incomingTransformController;
765 const incoming = new TransformStream({
766 start(controller) {
767 incomingTransformController = controller;
768 }
769 });
770
771 const pipeDonePromise = pipe(input, incoming.writable);
772
773 const outgoing = transformWithCancel(async function() {
774 incomingTransformController.error(new Error('Readable side was canceled.'));
775 await pipeDonePromise;
776 await new Promise(setTimeout);
777 });
778 fn(incoming.readable, outgoing.writable);
779 return outgoing.readable;
780 }
781 input = toArrayStream(input);
782 const output = new ArrayStream();
783 fn(input, output);
784 return output;
785 }
786
787 /**
788 * Parse a stream using a helper function which is passed a Reader.
789 * The reader additionally has a remainder() method which returns a
790 * stream pointing to the remainder of input, and is linked to input
791 * for cancelation.
792 * @param {ReadableStream|Uint8array|String} input
793 * @param {Function} fn
794 * @returns {Any} the return value of fn()
795 */
796 function parse(input, fn) {
797 let returnValue;
798 const transformed = transformPair(input, (readable, writable) => {
799 const reader = getReader(readable);
800 reader.remainder = () => {
801 reader.releaseLock();
802 pipe(readable, writable);
803 return transformed;
804 };
805 returnValue = fn(reader);
806 });
807 return returnValue;
808 }
809
810 /**
811 * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.
812 * Reading either of the two returned streams will pull from the input stream.
813 * The input stream will only be canceled if both of the returned streams are canceled.
814 * @param {ReadableStream|Uint8array|String} input
815 * @returns {Array<ReadableStream|Uint8array|String>} array containing two copies of input
816 */
817 function tee(input) {
818 if (isArrayStream(input)) {
819 const tee0 = new ArrayStream();
820 const tee1 = new ArrayStream();
821 (async () => {
822 const reader = getReader(input);
823 const writer1 = getWriter(tee0);
824 const writer2 = getWriter(tee1);
825 try {
826 while (true) {
827 await writer1.ready;
828 await writer2.ready;
829 const { done, value } = await reader.read();
830 if (done) {
831 await writer1.close();
832 await writer2.close();
833 break;
834 }
835 await writer1.write(value);
836 await writer2.write(value);
837 }
838 } catch (e) {
839 await writer1.abort(e);
840 await writer2.abort(e);
841 } finally {
842 reader.releaseLock();
843 writer1.releaseLock();
844 writer2.releaseLock();
845 }
846 })();
847 return [tee0, tee1];
848 }
849 if (isStream(input)) {
850 const teed = toStream(input).tee();
851 teed[0][externalBuffer] = teed[1][externalBuffer] = input[externalBuffer];
852 return teed;
853 }
854 return [slice(input), slice(input)];
855 }
856
857 /**
858 * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.
859 * Reading from the clone will pull from the input stream.
860 * The input stream will only be canceled if both the clone and the input stream are canceled.
861 * @param {ReadableStream|Uint8array|String} input
862 * @returns {ReadableStream|Uint8array|String} cloned input
863 */
864 function clone(input) {
865 if (isStream(input)) {
866 const teed = tee(input);
867 overwrite(input, teed[0]);
868 return teed[1];
869 }
870 return slice(input);
871 }
872
873 /**
874 * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.
875 * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.
876 * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.
877 * If the input stream is canceled, the clone will be errored.
878 * @param {ReadableStream|Uint8array|String} input
879 * @returns {ReadableStream|Uint8array|String} cloned input
880 */
881 function passiveClone(input) {
882 if (isArrayStream(input)) {
883 return clone(input);
884 }
885 if (isStream(input)) {
886 return new ReadableStream({
887 start(controller) {
888 const transformed = transformPair(input, async (readable, writable) => {
889 const reader = getReader(readable);
890 const writer = getWriter(writable);
891 try {
892 while (true) {
893 await writer.ready;
894 const { done, value } = await reader.read();
895 if (done) {
896 try { controller.close(); } catch(e) {}
897 await writer.close();
898 return;
899 }
900 try { controller.enqueue(value); } catch(e) {}
901 await writer.write(value);
902 }
903 } catch(e) {
904 controller.error(e);
905 await writer.abort(e);
906 }
907 });
908 overwrite(input, transformed);
909 }
910 });
911 }
912 return slice(input);
913 }
914
915 /**
916 * Modify a stream object to point to a different stream object.
917 * This is used internally by clone() and passiveClone() to provide an abstraction over tee().
918 * @param {ReadableStream} input
919 * @param {ReadableStream} clone
920 */
921 function overwrite(input, clone) {
922 // Overwrite input.getReader, input.locked, etc to point to clone
923 Object.entries(Object.getOwnPropertyDescriptors(input.constructor.prototype)).forEach(([name, descriptor]) => {
924 if (name === 'constructor') {
925 return;
926 }
927 if (descriptor.value) {
928 descriptor.value = descriptor.value.bind(clone);
929 } else {
930 descriptor.get = descriptor.get.bind(clone);
931 }
932 Object.defineProperty(input, name, descriptor);
933 });
934 }
935
936 /**
937 * Return a stream pointing to a part of the input stream.
938 * @param {ReadableStream|Uint8array|String} input
939 * @returns {ReadableStream|Uint8array|String} clone
940 */
941 function slice(input, begin=0, end=Infinity) {
942 if (isArrayStream(input)) {
943 throw new Error('Not implemented');
944 }
945 if (isStream(input)) {
946 if (begin >= 0 && end >= 0) {
947 let bytesRead = 0;
948 return transformRaw(input, {
949 transform(value, controller) {
950 if (bytesRead < end) {
951 if (bytesRead + value.length >= begin) {
952 controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));
953 }
954 bytesRead += value.length;
955 } else {
956 controller.terminate();
957 }
958 }
959 });
960 }
961 if (begin < 0 && (end < 0 || end === Infinity)) {
962 let lastBytes = [];
963 return transform(input, value => {
964 if (value.length >= -begin) lastBytes = [value];
965 else lastBytes.push(value);
966 }, () => slice(concat(lastBytes), begin, end));
967 }
968 if (begin === 0 && end < 0) {
969 let lastBytes;
970 return transform(input, value => {
971 const returnValue = lastBytes ? concat([lastBytes, value]) : value;
972 if (returnValue.length >= -end) {
973 lastBytes = slice(returnValue, end);
974 return slice(returnValue, begin, end);
975 } else {
976 lastBytes = returnValue;
977 }
978 });
979 }
980 console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);
981 return fromAsync(async () => slice(await readToEnd(input), begin, end));
982 }
983 if (input[externalBuffer]) {
984 input = concat(input[externalBuffer].concat([input]));
985 }
986 if (isUint8Array(input) && !(NodeBuffer$1 && NodeBuffer$1.isBuffer(input))) {
987 if (end === Infinity) end = input.length;
988 return input.subarray(begin, end);
989 }
990 return input.slice(begin, end);
991 }
992
993 /**
994 * Read a stream to the end and return its contents, concatenated by the join function (defaults to concat).
995 * @param {ReadableStream|Uint8array|String} input
996 * @param {Function} join
997 * @returns {Promise<Uint8array|String|Any>} the return value of join()
998 * @async
999 */
1000 async function readToEnd(input, join=concat) {
1001 if (isStream(input)) {
1002 return getReader(input).readToEnd(join);
1003 }
1004 return input;
1005 }
1006
1007 /**
1008 * Cancel a stream.
1009 * @param {ReadableStream|Uint8array|String} input
1010 * @param {Any} reason
1011 * @returns {Promise<Any>} indicates when the stream has been canceled
1012 * @async
1013 */
1014 async function cancel(input, reason) {
1015 if (isStream(input)) {
1016 if (input.cancel) {
1017 return input.cancel(reason);
1018 }
1019 if (input.destroy) {
1020 input.destroy(reason);
1021 await new Promise(setTimeout);
1022 return reason;
1023 }
1024 }
1025 }
1026
1027 /**
1028 * Convert an async function to an ArrayStream. When the function returns, its return value is written to the stream.
1029 * @param {Function} fn
1030 * @returns {ArrayStream}
1031 */
1032 function fromAsync(fn) {
1033 const arrayStream = new ArrayStream();
1034 (async () => {
1035 const writer = getWriter(arrayStream);
1036 try {
1037 await writer.write(await fn());
1038 await writer.close();
1039 } catch (e) {
1040 await writer.abort(e);
1041 }
1042 })();
1043 return arrayStream;
1044 }
1045
1046 /* eslint-disable new-cap */
1047
1048 /**
1049 * @fileoverview
1050 * BigInteger implementation of basic operations
1051 * that wraps the native BigInt library.
1052 * Operations are not constant time,
1053 * but we try and limit timing leakage where we can
1054 * @module biginteger/native
1055 * @private
1056 */
1057
1058 /**
1059 * @private
1060 */
1061 class BigInteger {
1062 /**
1063 * Get a BigInteger (input must be big endian for strings and arrays)
1064 * @param {Number|String|Uint8Array} n - Value to convert
1065 * @throws {Error} on null or undefined input
1066 */
1067 constructor(n) {
1068 if (n === undefined) {
1069 throw new Error('Invalid BigInteger input');
1070 }
1071
1072 if (n instanceof Uint8Array) {
1073 const bytes = n;
1074 const hex = new Array(bytes.length);
1075 for (let i = 0; i < bytes.length; i++) {
1076 const hexByte = bytes[i].toString(16);
1077 hex[i] = (bytes[i] <= 0xF) ? ('0' + hexByte) : hexByte;
1078 }
1079 this.value = BigInt('0x0' + hex.join(''));
1080 } else {
1081 this.value = BigInt(n);
1082 }
1083 }
1084
1085 clone() {
1086 return new BigInteger(this.value);
1087 }
1088
1089 /**
1090 * BigInteger increment in place
1091 */
1092 iinc() {
1093 this.value++;
1094 return this;
1095 }
1096
1097 /**
1098 * BigInteger increment
1099 * @returns {BigInteger} this + 1.
1100 */
1101 inc() {
1102 return this.clone().iinc();
1103 }
1104
1105 /**
1106 * BigInteger decrement in place
1107 */
1108 idec() {
1109 this.value--;
1110 return this;
1111 }
1112
1113 /**
1114 * BigInteger decrement
1115 * @returns {BigInteger} this - 1.
1116 */
1117 dec() {
1118 return this.clone().idec();
1119 }
1120
1121 /**
1122 * BigInteger addition in place
1123 * @param {BigInteger} x - Value to add
1124 */
1125 iadd(x) {
1126 this.value += x.value;
1127 return this;
1128 }
1129
1130 /**
1131 * BigInteger addition
1132 * @param {BigInteger} x - Value to add
1133 * @returns {BigInteger} this + x.
1134 */
1135 add(x) {
1136 return this.clone().iadd(x);
1137 }
1138
1139 /**
1140 * BigInteger subtraction in place
1141 * @param {BigInteger} x - Value to subtract
1142 */
1143 isub(x) {
1144 this.value -= x.value;
1145 return this;
1146 }
1147
1148 /**
1149 * BigInteger subtraction
1150 * @param {BigInteger} x - Value to subtract
1151 * @returns {BigInteger} this - x.
1152 */
1153 sub(x) {
1154 return this.clone().isub(x);
1155 }
1156
1157 /**
1158 * BigInteger multiplication in place
1159 * @param {BigInteger} x - Value to multiply
1160 */
1161 imul(x) {
1162 this.value *= x.value;
1163 return this;
1164 }
1165
1166 /**
1167 * BigInteger multiplication
1168 * @param {BigInteger} x - Value to multiply
1169 * @returns {BigInteger} this * x.
1170 */
1171 mul(x) {
1172 return this.clone().imul(x);
1173 }
1174
1175 /**
1176 * Compute value modulo m, in place
1177 * @param {BigInteger} m - Modulo
1178 */
1179 imod(m) {
1180 this.value %= m.value;
1181 if (this.isNegative()) {
1182 this.iadd(m);
1183 }
1184 return this;
1185 }
1186
1187 /**
1188 * Compute value modulo m
1189 * @param {BigInteger} m - Modulo
1190 * @returns {BigInteger} this mod m.
1191 */
1192 mod(m) {
1193 return this.clone().imod(m);
1194 }
1195
1196 /**
1197 * Compute modular exponentiation using square and multiply
1198 * @param {BigInteger} e - Exponent
1199 * @param {BigInteger} n - Modulo
1200 * @returns {BigInteger} this ** e mod n.
1201 */
1202 modExp(e, n) {
1203 if (n.isZero()) throw Error('Modulo cannot be zero');
1204 if (n.isOne()) return new BigInteger(0);
1205 if (e.isNegative()) throw Error('Unsopported negative exponent');
1206
1207 let exp = e.value;
1208 let x = this.value;
1209
1210 x %= n.value;
1211 let r = BigInt(1);
1212 while (exp > BigInt(0)) {
1213 const lsb = exp & BigInt(1);
1214 exp >>= BigInt(1); // e / 2
1215 // Always compute multiplication step, to reduce timing leakage
1216 const rx = (r * x) % n.value;
1217 // Update r only if lsb is 1 (odd exponent)
1218 r = lsb ? rx : r;
1219 x = (x * x) % n.value; // Square
1220 }
1221 return new BigInteger(r);
1222 }
1223
1224
1225 /**
1226 * Compute the inverse of this value modulo n
1227 * Note: this and and n must be relatively prime
1228 * @param {BigInteger} n - Modulo
1229 * @returns {BigInteger} x such that this*x = 1 mod n
1230 * @throws {Error} if the inverse does not exist
1231 */
1232 modInv(n) {
1233 const { gcd, x } = this._egcd(n);
1234 if (!gcd.isOne()) {
1235 throw new Error('Inverse does not exist');
1236 }
1237 return x.add(n).mod(n);
1238 }
1239
1240 /**
1241 * Extended Eucleadian algorithm (http://anh.cs.luc.edu/331/notes/xgcd.pdf)
1242 * Given a = this and b, compute (x, y) such that ax + by = gdc(a, b)
1243 * @param {BigInteger} b - Second operand
1244 * @returns {{ gcd, x, y: BigInteger }}
1245 */
1246 _egcd(b) {
1247 let x = BigInt(0);
1248 let y = BigInt(1);
1249 let xPrev = BigInt(1);
1250 let yPrev = BigInt(0);
1251
1252 let a = this.value;
1253 b = b.value;
1254
1255 while (b !== BigInt(0)) {
1256 const q = a / b;
1257 let tmp = x;
1258 x = xPrev - q * x;
1259 xPrev = tmp;
1260
1261 tmp = y;
1262 y = yPrev - q * y;
1263 yPrev = tmp;
1264
1265 tmp = b;
1266 b = a % b;
1267 a = tmp;
1268 }
1269
1270 return {
1271 x: new BigInteger(xPrev),
1272 y: new BigInteger(yPrev),
1273 gcd: new BigInteger(a)
1274 };
1275 }
1276
1277 /**
1278 * Compute greatest common divisor between this and n
1279 * @param {BigInteger} b - Operand
1280 * @returns {BigInteger} gcd
1281 */
1282 gcd(b) {
1283 let a = this.value;
1284 b = b.value;
1285 while (b !== BigInt(0)) {
1286 const tmp = b;
1287 b = a % b;
1288 a = tmp;
1289 }
1290 return new BigInteger(a);
1291 }
1292
1293 /**
1294 * Shift this to the left by x, in place
1295 * @param {BigInteger} x - Shift value
1296 */
1297 ileftShift(x) {
1298 this.value <<= x.value;
1299 return this;
1300 }
1301
1302 /**
1303 * Shift this to the left by x
1304 * @param {BigInteger} x - Shift value
1305 * @returns {BigInteger} this << x.
1306 */
1307 leftShift(x) {
1308 return this.clone().ileftShift(x);
1309 }
1310
1311 /**
1312 * Shift this to the right by x, in place
1313 * @param {BigInteger} x - Shift value
1314 */
1315 irightShift(x) {
1316 this.value >>= x.value;
1317 return this;
1318 }
1319
1320 /**
1321 * Shift this to the right by x
1322 * @param {BigInteger} x - Shift value
1323 * @returns {BigInteger} this >> x.
1324 */
1325 rightShift(x) {
1326 return this.clone().irightShift(x);
1327 }
1328
1329 /**
1330 * Whether this value is equal to x
1331 * @param {BigInteger} x
1332 * @returns {Boolean}
1333 */
1334 equal(x) {
1335 return this.value === x.value;
1336 }
1337
1338 /**
1339 * Whether this value is less than x
1340 * @param {BigInteger} x
1341 * @returns {Boolean}
1342 */
1343 lt(x) {
1344 return this.value < x.value;
1345 }
1346
1347 /**
1348 * Whether this value is less than or equal to x
1349 * @param {BigInteger} x
1350 * @returns {Boolean}
1351 */
1352 lte(x) {
1353 return this.value <= x.value;
1354 }
1355
1356 /**
1357 * Whether this value is greater than x
1358 * @param {BigInteger} x
1359 * @returns {Boolean}
1360 */
1361 gt(x) {
1362 return this.value > x.value;
1363 }
1364
1365 /**
1366 * Whether this value is greater than or equal to x
1367 * @param {BigInteger} x
1368 * @returns {Boolean}
1369 */
1370 gte(x) {
1371 return this.value >= x.value;
1372 }
1373
1374 isZero() {
1375 return this.value === BigInt(0);
1376 }
1377
1378 isOne() {
1379 return this.value === BigInt(1);
1380 }
1381
1382 isNegative() {
1383 return this.value < BigInt(0);
1384 }
1385
1386 isEven() {
1387 return !(this.value & BigInt(1));
1388 }
1389
1390 abs() {
1391 const res = this.clone();
1392 if (this.isNegative()) {
1393 res.value = -res.value;
1394 }
1395 return res;
1396 }
1397
1398 /**
1399 * Get this value as a string
1400 * @returns {String} this value.
1401 */
1402 toString() {
1403 return this.value.toString();
1404 }
1405
1406 /**
1407 * Get this value as an exact Number (max 53 bits)
1408 * Fails if this value is too large
1409 * @returns {Number}
1410 */
1411 toNumber() {
1412 const number = Number(this.value);
1413 if (number > Number.MAX_SAFE_INTEGER) {
1414 // We throw and error to conform with the bn.js implementation
1415 throw new Error('Number can only safely store up to 53 bits');
1416 }
1417 return number;
1418 }
1419
1420 /**
1421 * Get value of i-th bit
1422 * @param {Number} i - Bit index
1423 * @returns {Number} Bit value.
1424 */
1425 getBit(i) {
1426 const bit = (this.value >> BigInt(i)) & BigInt(1);
1427 return (bit === BigInt(0)) ? 0 : 1;
1428 }
1429
1430 /**
1431 * Compute bit length
1432 * @returns {Number} Bit length.
1433 */
1434 bitLength() {
1435 const zero = new BigInteger(0);
1436 const one = new BigInteger(1);
1437 const negOne = new BigInteger(-1);
1438
1439 // -1n >> -1n is -1n
1440 // 1n >> 1n is 0n
1441 const target = this.isNegative() ? negOne : zero;
1442 let bitlen = 1;
1443 const tmp = this.clone();
1444 while (!tmp.irightShift(one).equal(target)) {
1445 bitlen++;
1446 }
1447 return bitlen;
1448 }
1449
1450 /**
1451 * Compute byte length
1452 * @returns {Number} Byte length.
1453 */
1454 byteLength() {
1455 const zero = new BigInteger(0);
1456 const negOne = new BigInteger(-1);
1457
1458 const target = this.isNegative() ? negOne : zero;
1459 const eight = new BigInteger(8);
1460 let len = 1;
1461 const tmp = this.clone();
1462 while (!tmp.irightShift(eight).equal(target)) {
1463 len++;
1464 }
1465 return len;
1466 }
1467
1468 /**
1469 * Get Uint8Array representation of this number
1470 * @param {String} endian - Endianess of output array (defaults to 'be')
1471 * @param {Number} length - Of output array
1472 * @returns {Uint8Array}
1473 */
1474 toUint8Array(endian = 'be', length) {
1475 // we get and parse the hex string (https://coolaj86.com/articles/convert-js-bigints-to-typedarrays/)
1476 // this is faster than shift+mod iterations
1477 let hex = this.value.toString(16);
1478 if (hex.length % 2 === 1) {
1479 hex = '0' + hex;
1480 }
1481
1482 const rawLength = hex.length / 2;
1483 const bytes = new Uint8Array(length || rawLength);
1484 // parse hex
1485 const offset = length ? (length - rawLength) : 0;
1486 let i = 0;
1487 while (i < rawLength) {
1488 bytes[i + offset] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);
1489 i++;
1490 }
1491
1492 if (endian !== 'be') {
1493 bytes.reverse();
1494 }
1495
1496 return bytes;
1497 }
1498 }
1499
1500 async function getBigInteger() {
1501 if (util.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 // GPG4Browsers - An OpenPGP implementation in javascript
1510
1511 const debugMode = globalThis.process && globalThis.process.env.NODE_ENV === 'development';
1512
1513 const util = {
1514 isString: function(data) {
1515 return typeof data === 'string' || String.prototype.isPrototypeOf(data);
1516 },
1517
1518 isArray: function(data) {
1519 return Array.prototype.isPrototypeOf(data);
1520 },
1521
1522 isUint8Array: isUint8Array,
1523
1524 isStream: isStream,
1525
1526 readNumber: function (bytes) {
1527 let n = 0;
1528 for (let i = 0; i < bytes.length; i++) {
1529 n += (256 ** i) * bytes[bytes.length - 1 - i];
1530 }
1531 return n;
1532 },
1533
1534 writeNumber: function (n, bytes) {
1535 const b = new Uint8Array(bytes);
1536 for (let i = 0; i < bytes; i++) {
1537 b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF;
1538 }
1539
1540 return b;
1541 },
1542
1543 readDate: function (bytes) {
1544 const n = util.readNumber(bytes);
1545 const d = new Date(n * 1000);
1546 return d;
1547 },
1548
1549 writeDate: function (time) {
1550 const numeric = Math.floor(time.getTime() / 1000);
1551
1552 return util.writeNumber(numeric, 4);
1553 },
1554
1555 normalizeDate: function (time = Date.now()) {
1556 return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);
1557 },
1558
1559 /**
1560 * Read one MPI from bytes in input
1561 * @param {Uint8Array} bytes - Input data to parse
1562 * @returns {Uint8Array} Parsed MPI.
1563 */
1564 readMPI: function (bytes) {
1565 const bits = (bytes[0] << 8) | bytes[1];
1566 const bytelen = (bits + 7) >>> 3;
1567 return bytes.subarray(2, 2 + bytelen);
1568 },
1569
1570 /**
1571 * Left-pad Uint8Array to length by adding 0x0 bytes
1572 * @param {Uint8Array} bytes - Data to pad
1573 * @param {Number} length - Padded length
1574 * @returns {Uint8Array} Padded bytes.
1575 */
1576 leftPad(bytes, length) {
1577 const padded = new Uint8Array(length);
1578 const offset = length - bytes.length;
1579 padded.set(bytes, offset);
1580 return padded;
1581 },
1582
1583 /**
1584 * Convert a Uint8Array to an MPI-formatted Uint8Array.
1585 * @param {Uint8Array} bin - An array of 8-bit integers to convert
1586 * @returns {Uint8Array} MPI-formatted Uint8Array.
1587 */
1588 uint8ArrayToMPI: function (bin) {
1589 const bitSize = util.uint8ArrayBitLength(bin);
1590 if (bitSize === 0) {
1591 throw new Error('Zero MPI');
1592 }
1593 const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8));
1594 const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]);
1595 return util.concatUint8Array([prefix, stripped]);
1596 },
1597
1598 /**
1599 * Return bit length of the input data
1600 * @param {Uint8Array} bin input data (big endian)
1601 * @returns bit length
1602 */
1603 uint8ArrayBitLength: function (bin) {
1604 let i; // index of leading non-zero byte
1605 for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break;
1606 if (i === bin.length) {
1607 return 0;
1608 }
1609 const stripped = bin.subarray(i);
1610 return (stripped.length - 1) * 8 + util.nbits(stripped[0]);
1611 },
1612
1613 /**
1614 * Convert a hex string to an array of 8-bit integers
1615 * @param {String} hex - A hex string to convert
1616 * @returns {Uint8Array} An array of 8-bit integers.
1617 */
1618 hexToUint8Array: function (hex) {
1619 const result = new Uint8Array(hex.length >> 1);
1620 for (let k = 0; k < hex.length >> 1; k++) {
1621 result[k] = parseInt(hex.substr(k << 1, 2), 16);
1622 }
1623 return result;
1624 },
1625
1626 /**
1627 * Convert an array of 8-bit integers to a hex string
1628 * @param {Uint8Array} bytes - Array of 8-bit integers to convert
1629 * @returns {String} Hexadecimal representation of the array.
1630 */
1631 uint8ArrayToHex: function (bytes) {
1632 const r = [];
1633 const e = bytes.length;
1634 let c = 0;
1635 let h;
1636 while (c < e) {
1637 h = bytes[c++].toString(16);
1638 while (h.length < 2) {
1639 h = '0' + h;
1640 }
1641 r.push('' + h);
1642 }
1643 return r.join('');
1644 },
1645
1646 /**
1647 * Convert a string to an array of 8-bit integers
1648 * @param {String} str - String to convert
1649 * @returns {Uint8Array} An array of 8-bit integers.
1650 */
1651 stringToUint8Array: function (str) {
1652 return transform(str, str => {
1653 if (!util.isString(str)) {
1654 throw new Error('stringToUint8Array: Data must be in the form of a string');
1655 }
1656
1657 const result = new Uint8Array(str.length);
1658 for (let i = 0; i < str.length; i++) {
1659 result[i] = str.charCodeAt(i);
1660 }
1661 return result;
1662 });
1663 },
1664
1665 /**
1666 * Convert an array of 8-bit integers to a string
1667 * @param {Uint8Array} bytes - An array of 8-bit integers to convert
1668 * @returns {String} String representation of the array.
1669 */
1670 uint8ArrayToString: function (bytes) {
1671 bytes = new Uint8Array(bytes);
1672 const result = [];
1673 const bs = 1 << 14;
1674 const j = bytes.length;
1675
1676 for (let i = 0; i < j; i += bs) {
1677 result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));
1678 }
1679 return result.join('');
1680 },
1681
1682 /**
1683 * Convert a native javascript string to a Uint8Array of utf8 bytes
1684 * @param {String|ReadableStream} str - The string to convert
1685 * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes.
1686 */
1687 encodeUTF8: function (str) {
1688 const encoder = new TextEncoder('utf-8');
1689 // eslint-disable-next-line no-inner-declarations
1690 function process(value, lastChunk = false) {
1691 return encoder.encode(value, { stream: !lastChunk });
1692 }
1693 return transform(str, process, () => process('', true));
1694 },
1695
1696 /**
1697 * Convert a Uint8Array of utf8 bytes to a native javascript string
1698 * @param {Uint8Array|ReadableStream} utf8 - A valid squence of utf8 bytes
1699 * @returns {String|ReadableStream} A native javascript string.
1700 */
1701 decodeUTF8: function (utf8) {
1702 const decoder = new TextDecoder('utf-8');
1703 // eslint-disable-next-line no-inner-declarations
1704 function process(value, lastChunk = false) {
1705 return decoder.decode(value, { stream: !lastChunk });
1706 }
1707 return transform(utf8, process, () => process(new Uint8Array(), true));
1708 },
1709
1710 /**
1711 * Concat a list of Uint8Arrays, Strings or Streams
1712 * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
1713 * @param {Array<Uint8Array|String|ReadableStream>} Array - Of Uint8Arrays/Strings/Streams to concatenate
1714 * @returns {Uint8Array|String|ReadableStream} Concatenated array.
1715 */
1716 concat: concat,
1717
1718 /**
1719 * Concat Uint8Arrays
1720 * @param {Array<Uint8Array>} Array - Of Uint8Arrays to concatenate
1721 * @returns {Uint8Array} Concatenated array.
1722 */
1723 concatUint8Array: concatUint8Array,
1724
1725 /**
1726 * Check Uint8Array equality
1727 * @param {Uint8Array} array1 - First array
1728 * @param {Uint8Array} array2 - Second array
1729 * @returns {Boolean} Equality.
1730 */
1731 equalsUint8Array: function (array1, array2) {
1732 if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) {
1733 throw new Error('Data must be in the form of a Uint8Array');
1734 }
1735
1736 if (array1.length !== array2.length) {
1737 return false;
1738 }
1739
1740 for (let i = 0; i < array1.length; i++) {
1741 if (array1[i] !== array2[i]) {
1742 return false;
1743 }
1744 }
1745 return true;
1746 },
1747
1748 /**
1749 * Calculates a 16bit sum of a Uint8Array by adding each character
1750 * codes modulus 65535
1751 * @param {Uint8Array} Uint8Array - To create a sum of
1752 * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535.
1753 */
1754 writeChecksum: function (text) {
1755 let s = 0;
1756 for (let i = 0; i < text.length; i++) {
1757 s = (s + text[i]) & 0xFFFF;
1758 }
1759 return util.writeNumber(s, 2);
1760 },
1761
1762 /**
1763 * Helper function to print a debug message. Debug
1764 * messages are only printed if
1765 * @param {String} str - String of the debug message
1766 */
1767 printDebug: function (str) {
1768 if (debugMode) {
1769 console.log(str);
1770 }
1771 },
1772
1773 /**
1774 * Helper function to print a debug error. Debug
1775 * messages are only printed if
1776 * @param {String} str - String of the debug message
1777 */
1778 printDebugError: function (error) {
1779 if (debugMode) {
1780 console.error(error);
1781 }
1782 },
1783
1784 // returns bit length of the integer x
1785 nbits: function (x) {
1786 let r = 1;
1787 let t = x >>> 16;
1788 if (t !== 0) {
1789 x = t;
1790 r += 16;
1791 }
1792 t = x >> 8;
1793 if (t !== 0) {
1794 x = t;
1795 r += 8;
1796 }
1797 t = x >> 4;
1798 if (t !== 0) {
1799 x = t;
1800 r += 4;
1801 }
1802 t = x >> 2;
1803 if (t !== 0) {
1804 x = t;
1805 r += 2;
1806 }
1807 t = x >> 1;
1808 if (t !== 0) {
1809 x = t;
1810 r += 1;
1811 }
1812 return r;
1813 },
1814
1815 /**
1816 * If S[1] == 0, then double(S) == (S[2..128] || 0);
1817 * otherwise, double(S) == (S[2..128] || 0) xor
1818 * (zeros(120) || 10000111).
1819 *
1820 * Both OCB and EAX (through CMAC) require this function to be constant-time.
1821 *
1822 * @param {Uint8Array} data
1823 */
1824 double: function(data) {
1825 const doubleVar = new Uint8Array(data.length);
1826 const last = data.length - 1;
1827 for (let i = 0; i < last; i++) {
1828 doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7);
1829 }
1830 doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87);
1831 return doubleVar;
1832 },
1833
1834 /**
1835 * Shift a Uint8Array to the right by n bits
1836 * @param {Uint8Array} array - The array to shift
1837 * @param {Integer} bits - Amount of bits to shift (MUST be smaller
1838 * than 8)
1839 * @returns {String} Resulting array.
1840 */
1841 shiftRight: function (array, bits) {
1842 if (bits) {
1843 for (let i = array.length - 1; i >= 0; i--) {
1844 array[i] >>= bits;
1845 if (i > 0) {
1846 array[i] |= (array[i - 1] << (8 - bits));
1847 }
1848 }
1849 }
1850 return array;
1851 },
1852
1853 /**
1854 * Get native Web Cryptography api, only the current version of the spec.
1855 * @returns {Object} The SubtleCrypto api or 'undefined'.
1856 */
1857 getWebCrypto: function() {
1858 return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;
1859 },
1860
1861 /**
1862 * Detect Node.js runtime.
1863 */
1864 detectNode: function() {
1865 return typeof globalThis.process === 'object' &&
1866 typeof globalThis.process.versions === 'object';
1867 },
1868
1869 /**
1870 * Detect native BigInt support
1871 */
1872 detectBigInt: () => typeof BigInt !== 'undefined',
1873
1874 /**
1875 * Get BigInteger class
1876 * It wraps the native BigInt type if it's available
1877 * Otherwise it relies on bn.js
1878 * @returns {BigInteger}
1879 * @async
1880 */
1881 getBigInteger,
1882
1883 /**
1884 * Get native Node.js crypto api.
1885 * @returns {Object} The crypto module or 'undefined'.
1886 */
1887 getNodeCrypto: function() {
1888 return void('crypto');
1889 },
1890
1891 getNodeZlib: function() {
1892 return void('zlib');
1893 },
1894
1895 /**
1896 * Get native Node.js Buffer constructor. This should be used since
1897 * Buffer is not available under browserify.
1898 * @returns {Function} The Buffer constructor or 'undefined'.
1899 */
1900 getNodeBuffer: function() {
1901 return ({}).Buffer;
1902 },
1903
1904 getHardwareConcurrency: function() {
1905 if (util.detectNode()) {
1906 const os = void('os');
1907 return os.cpus().length;
1908 }
1909
1910 return navigator.hardwareConcurrency || 1;
1911 },
1912
1913 isEmailAddress: function(data) {
1914 if (!util.isString(data)) {
1915 return false;
1916 }
1917 const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+([a-zA-Z]{2,}|xn--[a-zA-Z\-0-9]+)))$/;
1918 return re.test(data);
1919 },
1920
1921 /**
1922 * Normalize line endings to <CR><LF>
1923 * Support any encoding where CR=0x0D, LF=0x0A
1924 */
1925 canonicalizeEOL: function(data) {
1926 const CR = 13;
1927 const LF = 10;
1928 let carryOverCR = false;
1929
1930 return transform(data, bytes => {
1931 if (carryOverCR) {
1932 bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);
1933 }
1934
1935 if (bytes[bytes.length - 1] === CR) {
1936 carryOverCR = true;
1937 bytes = bytes.subarray(0, -1);
1938 } else {
1939 carryOverCR = false;
1940 }
1941
1942 let index;
1943 const indices = [];
1944 for (let i = 0; ; i = index) {
1945 index = bytes.indexOf(LF, i) + 1;
1946 if (index) {
1947 if (bytes[index - 2] !== CR) indices.push(index);
1948 } else {
1949 break;
1950 }
1951 }
1952 if (!indices.length) {
1953 return bytes;
1954 }
1955
1956 const normalized = new Uint8Array(bytes.length + indices.length);
1957 let j = 0;
1958 for (let i = 0; i < indices.length; i++) {
1959 const sub = bytes.subarray(indices[i - 1] || 0, indices[i]);
1960 normalized.set(sub, j);
1961 j += sub.length;
1962 normalized[j - 1] = CR;
1963 normalized[j] = LF;
1964 j++;
1965 }
1966 normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j);
1967 return normalized;
1968 }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));
1969 },
1970
1971 /**
1972 * Convert line endings from canonicalized <CR><LF> to native <LF>
1973 * Support any encoding where CR=0x0D, LF=0x0A
1974 */
1975 nativeEOL: function(data) {
1976 const CR = 13;
1977 const LF = 10;
1978 let carryOverCR = false;
1979
1980 return transform(data, bytes => {
1981 if (carryOverCR && bytes[0] !== LF) {
1982 bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]);
1983 } else {
1984 bytes = new Uint8Array(bytes); // Don't mutate passed bytes
1985 }
1986
1987 if (bytes[bytes.length - 1] === CR) {
1988 carryOverCR = true;
1989 bytes = bytes.subarray(0, -1);
1990 } else {
1991 carryOverCR = false;
1992 }
1993
1994 let index;
1995 let j = 0;
1996 for (let i = 0; i !== bytes.length; i = index) {
1997 index = bytes.indexOf(CR, i) + 1;
1998 if (!index) index = bytes.length;
1999 const last = index - (bytes[index] === LF ? 1 : 0);
2000 if (i) bytes.copyWithin(j, i, last);
2001 j += last - i;
2002 }
2003 return bytes.subarray(0, j);
2004 }, () => (carryOverCR ? new Uint8Array([CR]) : undefined));
2005 },
2006
2007 /**
2008 * Remove trailing spaces and tabs from each line
2009 */
2010 removeTrailingSpaces: function(text) {
2011 return text.split('\n').map(line => {
2012 let i = line.length - 1;
2013 for (; i >= 0 && (line[i] === ' ' || line[i] === '\t'); i--);
2014 return line.substr(0, i + 1);
2015 }).join('\n');
2016 },
2017
2018 wrapError: function(message, error) {
2019 if (!error) {
2020 return new Error(message);
2021 }
2022
2023 // update error message
2024 try {
2025 error.message = message + ': ' + error.message;
2026 } catch (e) {}
2027
2028 return error;
2029 },
2030
2031 /**
2032 * Map allowed packet tags to corresponding classes
2033 * Meant to be used to format `allowedPacket` for Packetlist.read
2034 * @param {Array<Object>} allowedClasses
2035 * @returns {Object} map from enum.packet to corresponding *Packet class
2036 */
2037 constructAllowedPackets: function(allowedClasses) {
2038 const map = {};
2039 allowedClasses.forEach(PacketClass => {
2040 if (!PacketClass.tag) {
2041 throw new Error('Invalid input: expected a packet class');
2042 }
2043 map[PacketClass.tag] = PacketClass;
2044 });
2045 return map;
2046 },
2047
2048 /**
2049 * Return a Promise that will resolve as soon as one of the promises in input resolves
2050 * or will reject if all input promises all rejected
2051 * (similar to Promise.any, but with slightly different error handling)
2052 * @param {Array<Promise>} promises
2053 * @return {Promise<Any>} Promise resolving to the result of the fastest fulfilled promise
2054 * or rejected with the Error of the last resolved Promise (if all promises are rejected)
2055 */
2056 anyPromise: function(promises) {
2057 return new Promise(async (resolve, reject) => {
2058 let exception;
2059 await Promise.all(promises.map(async promise => {
2060 try {
2061 resolve(await promise);
2062 } catch (e) {
2063 exception = e;
2064 }
2065 }));
2066 reject(exception);
2067 });
2068 }
2069 };
2070
2071 /* OpenPGP radix-64/base64 string encoding/decoding
2072 * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de
2073 * version 1.0, check www.haneWIN.de for the latest version
2074 *
2075 * This software is provided as-is, without express or implied warranty.
2076 * Permission to use, copy, modify, distribute or sell this software, with or
2077 * without fee, for any purpose and by any individual or organization, is hereby
2078 * granted, provided that the above copyright notice and this paragraph appear
2079 * in all copies. Distribution as a part of an application or binary must
2080 * include the above copyright notice in the documentation and/or other materials
2081 * provided with the application or distribution.
2082 */
2083
2084 const Buffer = util.getNodeBuffer();
2085
2086 let encodeChunk;
2087 let decodeChunk;
2088 if (Buffer) {
2089 encodeChunk = buf => Buffer.from(buf).toString('base64');
2090 decodeChunk = str => {
2091 const b = Buffer.from(str, 'base64');
2092 return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
2093 };
2094 } else {
2095 encodeChunk = buf => btoa(util.uint8ArrayToString(buf));
2096 decodeChunk = str => util.stringToUint8Array(atob(str));
2097 }
2098
2099 /**
2100 * Convert binary array to radix-64
2101 * @param {Uint8Array | ReadableStream<Uint8Array>} data - Uint8Array to convert
2102 * @returns {String | ReadableStream<String>} Radix-64 version of input string.
2103 * @static
2104 */
2105 function encode(data) {
2106 let buf = new Uint8Array();
2107 return transform(data, value => {
2108 buf = util.concatUint8Array([buf, value]);
2109 const r = [];
2110 const bytesPerLine = 45; // 60 chars per line * (3 bytes / 4 chars of base64).
2111 const lines = Math.floor(buf.length / bytesPerLine);
2112 const bytes = lines * bytesPerLine;
2113 const encoded = encodeChunk(buf.subarray(0, bytes));
2114 for (let i = 0; i < lines; i++) {
2115 r.push(encoded.substr(i * 60, 60));
2116 r.push('\n');
2117 }
2118 buf = buf.subarray(bytes);
2119 return r.join('');
2120 }, () => (buf.length ? encodeChunk(buf) + '\n' : ''));
2121 }
2122
2123 /**
2124 * Convert radix-64 to binary array
2125 * @param {String | ReadableStream<String>} data - Radix-64 string to convert
2126 * @returns {Uint8Array | ReadableStream<Uint8Array>} Binary array version of input string.
2127 * @static
2128 */
2129 function decode(data) {
2130 let buf = '';
2131 return transform(data, value => {
2132 buf += value;
2133
2134 // Count how many whitespace characters there are in buf
2135 let spaces = 0;
2136 const spacechars = [' ', '\t', '\r', '\n'];
2137 for (let i = 0; i < spacechars.length; i++) {
2138 const spacechar = spacechars[i];
2139 for (let pos = buf.indexOf(spacechar); pos !== -1; pos = buf.indexOf(spacechar, pos + 1)) {
2140 spaces++;
2141 }
2142 }
2143
2144 // Backtrack until we have 4n non-whitespace characters
2145 // that we can safely base64-decode
2146 let length = buf.length;
2147 for (; length > 0 && (length - spaces) % 4 !== 0; length--) {
2148 if (spacechars.includes(buf[length])) spaces--;
2149 }
2150
2151 const decoded = decodeChunk(buf.substr(0, length));
2152 buf = buf.substr(length);
2153 return decoded;
2154 }, () => decodeChunk(buf));
2155 }
2156
2157 /**
2158 * Convert a Base-64 encoded string an array of 8-bit integer
2159 *
2160 * Note: accepts both Radix-64 and URL-safe strings
2161 * @param {String} base64 - Base-64 encoded string to convert
2162 * @returns {Uint8Array} An array of 8-bit integers.
2163 */
2164 function b64ToUint8Array(base64) {
2165 return decode(base64.replace(/-/g, '+').replace(/_/g, '/'));
2166 }
2167
2168 /**
2169 * Convert an array of 8-bit integer to a Base-64 encoded string
2170 * @param {Uint8Array} bytes - An array of 8-bit integers to convert
2171 * @param {bool} url - If true, output is URL-safe
2172 * @returns {String} Base-64 encoded string.
2173 */
2174 function uint8ArrayToB64(bytes, url) {
2175 let encoded = encode(bytes).replace(/[\r\n]/g, '');
2176 if (url) {
2177 encoded = encoded.replace(/[+]/g, '-').replace(/[/]/g, '_').replace(/[=]/g, '');
2178 }
2179 return encoded;
2180 }
2181
2182 /**
2183 * @module enums
2184 */
2185
2186 const byValue = Symbol('byValue');
2187
2188 var enums = {
2189
2190 /** Maps curve names under various standards to one
2191 * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}
2192 * @enum {String}
2193 * @readonly
2194 */
2195 curve: {
2196 /** NIST P-256 Curve */
2197 'p256': 'p256',
2198 'P-256': 'p256',
2199 'secp256r1': 'p256',
2200 'prime256v1': 'p256',
2201 '1.2.840.10045.3.1.7': 'p256',
2202 '2a8648ce3d030107': 'p256',
2203 '2A8648CE3D030107': 'p256',
2204
2205 /** NIST P-384 Curve */
2206 'p384': 'p384',
2207 'P-384': 'p384',
2208 'secp384r1': 'p384',
2209 '1.3.132.0.34': 'p384',
2210 '2b81040022': 'p384',
2211 '2B81040022': 'p384',
2212
2213 /** NIST P-521 Curve */
2214 'p521': 'p521',
2215 'P-521': 'p521',
2216 'secp521r1': 'p521',
2217 '1.3.132.0.35': 'p521',
2218 '2b81040023': 'p521',
2219 '2B81040023': 'p521',
2220
2221 /** SECG SECP256k1 Curve */
2222 'secp256k1': 'secp256k1',
2223 '1.3.132.0.10': 'secp256k1',
2224 '2b8104000a': 'secp256k1',
2225 '2B8104000A': 'secp256k1',
2226
2227 /** Ed25519 */
2228 'ED25519': 'ed25519',
2229 'ed25519': 'ed25519',
2230 'Ed25519': 'ed25519',
2231 '1.3.6.1.4.1.11591.15.1': 'ed25519',
2232 '2b06010401da470f01': 'ed25519',
2233 '2B06010401DA470F01': 'ed25519',
2234
2235 /** Curve25519 */
2236 'X25519': 'curve25519',
2237 'cv25519': 'curve25519',
2238 'curve25519': 'curve25519',
2239 'Curve25519': 'curve25519',
2240 '1.3.6.1.4.1.3029.1.5.1': 'curve25519',
2241 '2b060104019755010501': 'curve25519',
2242 '2B060104019755010501': 'curve25519',
2243
2244 /** BrainpoolP256r1 Curve */
2245 'brainpoolP256r1': 'brainpoolP256r1',
2246 '1.3.36.3.3.2.8.1.1.7': 'brainpoolP256r1',
2247 '2b2403030208010107': 'brainpoolP256r1',
2248 '2B2403030208010107': 'brainpoolP256r1',
2249
2250 /** BrainpoolP384r1 Curve */
2251 'brainpoolP384r1': 'brainpoolP384r1',
2252 '1.3.36.3.3.2.8.1.1.11': 'brainpoolP384r1',
2253 '2b240303020801010b': 'brainpoolP384r1',
2254 '2B240303020801010B': 'brainpoolP384r1',
2255
2256 /** BrainpoolP512r1 Curve */
2257 'brainpoolP512r1': 'brainpoolP512r1',
2258 '1.3.36.3.3.2.8.1.1.13': 'brainpoolP512r1',
2259 '2b240303020801010d': 'brainpoolP512r1',
2260 '2B240303020801010D': 'brainpoolP512r1'
2261 },
2262
2263 /** A string to key specifier type
2264 * @enum {Integer}
2265 * @readonly
2266 */
2267 s2k: {
2268 simple: 0,
2269 salted: 1,
2270 iterated: 3,
2271 gnu: 101
2272 },
2273
2274 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.1|RFC4880bis-04, section 9.1}
2275 * @enum {Integer}
2276 * @readonly
2277 */
2278 publicKey: {
2279 /** RSA (Encrypt or Sign) [HAC] */
2280 rsaEncryptSign: 1,
2281 /** RSA (Encrypt only) [HAC] */
2282 rsaEncrypt: 2,
2283 /** RSA (Sign only) [HAC] */
2284 rsaSign: 3,
2285 /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */
2286 elgamal: 16,
2287 /** DSA (Sign only) [FIPS186] [HAC] */
2288 dsa: 17,
2289 /** ECDH (Encrypt only) [RFC6637] */
2290 ecdh: 18,
2291 /** ECDSA (Sign only) [RFC6637] */
2292 ecdsa: 19,
2293 /** EdDSA (Sign only)
2294 * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */
2295 eddsa: 22,
2296 /** Reserved for AEDH */
2297 aedh: 23,
2298 /** Reserved for AEDSA */
2299 aedsa: 24
2300 },
2301
2302 /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}
2303 * @enum {Integer}
2304 * @readonly
2305 */
2306 symmetric: {
2307 plaintext: 0,
2308 /** Not implemented! */
2309 idea: 1,
2310 tripledes: 2,
2311 cast5: 3,
2312 blowfish: 4,
2313 aes128: 7,
2314 aes192: 8,
2315 aes256: 9,
2316 twofish: 10
2317 },
2318
2319 /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}
2320 * @enum {Integer}
2321 * @readonly
2322 */
2323 compression: {
2324 uncompressed: 0,
2325 /** RFC1951 */
2326 zip: 1,
2327 /** RFC1950 */
2328 zlib: 2,
2329 bzip2: 3
2330 },
2331
2332 /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}
2333 * @enum {Integer}
2334 * @readonly
2335 */
2336 hash: {
2337 md5: 1,
2338 sha1: 2,
2339 ripemd: 3,
2340 sha256: 8,
2341 sha384: 9,
2342 sha512: 10,
2343 sha224: 11
2344 },
2345
2346 /** A list of hash names as accepted by webCrypto functions.
2347 * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}
2348 * @enum {String}
2349 */
2350 webHash: {
2351 'SHA-1': 2,
2352 'SHA-256': 8,
2353 'SHA-384': 9,
2354 'SHA-512': 10
2355 },
2356
2357 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}
2358 * @enum {Integer}
2359 * @readonly
2360 */
2361 aead: {
2362 eax: 1,
2363 ocb: 2,
2364 experimentalGCM: 100 // Private algorithm
2365 },
2366
2367 /** A list of packet types and numeric tags associated with them.
2368 * @enum {Integer}
2369 * @readonly
2370 */
2371 packet: {
2372 publicKeyEncryptedSessionKey: 1,
2373 signature: 2,
2374 symEncryptedSessionKey: 3,
2375 onePassSignature: 4,
2376 secretKey: 5,
2377 publicKey: 6,
2378 secretSubkey: 7,
2379 compressedData: 8,
2380 symmetricallyEncryptedData: 9,
2381 marker: 10,
2382 literalData: 11,
2383 trust: 12,
2384 userID: 13,
2385 publicSubkey: 14,
2386 userAttribute: 17,
2387 symEncryptedIntegrityProtectedData: 18,
2388 modificationDetectionCode: 19,
2389 aeadEncryptedData: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1
2390 },
2391
2392 /** Data types in the literal packet
2393 * @enum {Integer}
2394 * @readonly
2395 */
2396 literal: {
2397 /** Binary data 'b' */
2398 binary: 'b'.charCodeAt(),
2399 /** Text data 't' */
2400 text: 't'.charCodeAt(),
2401 /** Utf8 data 'u' */
2402 utf8: 'u'.charCodeAt(),
2403 /** MIME message body part 'm' */
2404 mime: 'm'.charCodeAt()
2405 },
2406
2407
2408 /** One pass signature packet type
2409 * @enum {Integer}
2410 * @readonly
2411 */
2412 signature: {
2413 /** 0x00: Signature of a binary document. */
2414 binary: 0,
2415 /** 0x01: Signature of a canonical text document.
2416 *
2417 * Canonicalyzing the document by converting line endings. */
2418 text: 1,
2419 /** 0x02: Standalone signature.
2420 *
2421 * This signature is a signature of only its own subpacket contents.
2422 * It is calculated identically to a signature over a zero-lengh
2423 * binary document. Note that it doesn't make sense to have a V3
2424 * standalone signature. */
2425 standalone: 2,
2426 /** 0x10: Generic certification of a User ID and Public-Key packet.
2427 *
2428 * The issuer of this certification does not make any particular
2429 * assertion as to how well the certifier has checked that the owner
2430 * of the key is in fact the person described by the User ID. */
2431 certGeneric: 16,
2432 /** 0x11: Persona certification of a User ID and Public-Key packet.
2433 *
2434 * The issuer of this certification has not done any verification of
2435 * the claim that the owner of this key is the User ID specified. */
2436 certPersona: 17,
2437 /** 0x12: Casual certification of a User ID and Public-Key packet.
2438 *
2439 * The issuer of this certification has done some casual
2440 * verification of the claim of identity. */
2441 certCasual: 18,
2442 /** 0x13: Positive certification of a User ID and Public-Key packet.
2443 *
2444 * The issuer of this certification has done substantial
2445 * verification of the claim of identity.
2446 *
2447 * Most OpenPGP implementations make their "key signatures" as 0x10
2448 * certifications. Some implementations can issue 0x11-0x13
2449 * certifications, but few differentiate between the types. */
2450 certPositive: 19,
2451 /** 0x30: Certification revocation signature
2452 *
2453 * This signature revokes an earlier User ID certification signature
2454 * (signature class 0x10 through 0x13) or direct-key signature
2455 * (0x1F). It should be issued by the same key that issued the
2456 * revoked signature or an authorized revocation key. The signature
2457 * is computed over the same data as the certificate that it
2458 * revokes, and should have a later creation date than that
2459 * certificate. */
2460 certRevocation: 48,
2461 /** 0x18: Subkey Binding Signature
2462 *
2463 * This signature is a statement by the top-level signing key that
2464 * indicates that it owns the subkey. This signature is calculated
2465 * directly on the primary key and subkey, and not on any User ID or
2466 * other packets. A signature that binds a signing subkey MUST have
2467 * an Embedded Signature subpacket in this binding signature that
2468 * contains a 0x19 signature made by the signing subkey on the
2469 * primary key and subkey. */
2470 subkeyBinding: 24,
2471 /** 0x19: Primary Key Binding Signature
2472 *
2473 * This signature is a statement by a signing subkey, indicating
2474 * that it is owned by the primary key and subkey. This signature
2475 * is calculated the same way as a 0x18 signature: directly on the
2476 * primary key and subkey, and not on any User ID or other packets.
2477 *
2478 * When a signature is made over a key, the hash data starts with the
2479 * octet 0x99, followed by a two-octet length of the key, and then body
2480 * of the key packet. (Note that this is an old-style packet header for
2481 * a key packet with two-octet length.) A subkey binding signature
2482 * (type 0x18) or primary key binding signature (type 0x19) then hashes
2483 * the subkey using the same format as the main key (also using 0x99 as
2484 * the first octet). */
2485 keyBinding: 25,
2486 /** 0x1F: Signature directly on a key
2487 *
2488 * This signature is calculated directly on a key. It binds the
2489 * information in the Signature subpackets to the key, and is
2490 * appropriate to be used for subpackets that provide information
2491 * about the key, such as the Revocation Key subpacket. It is also
2492 * appropriate for statements that non-self certifiers want to make
2493 * about the key itself, rather than the binding between a key and a
2494 * name. */
2495 key: 31,
2496 /** 0x20: Key revocation signature
2497 *
2498 * The signature is calculated directly on the key being revoked. A
2499 * revoked key is not to be used. Only revocation signatures by the
2500 * key being revoked, or by an authorized revocation key, should be
2501 * considered valid revocation signatures.a */
2502 keyRevocation: 32,
2503 /** 0x28: Subkey revocation signature
2504 *
2505 * The signature is calculated directly on the subkey being revoked.
2506 * A revoked subkey is not to be used. Only revocation signatures
2507 * by the top-level signature key that is bound to this subkey, or
2508 * by an authorized revocation key, should be considered valid
2509 * revocation signatures.
2510 *
2511 * Key revocation signatures (types 0x20 and 0x28)
2512 * hash only the key being revoked. */
2513 subkeyRevocation: 40,
2514 /** 0x40: Timestamp signature.
2515 * This signature is only meaningful for the timestamp contained in
2516 * it. */
2517 timestamp: 64,
2518 /** 0x50: Third-Party Confirmation signature.
2519 *
2520 * This signature is a signature over some other OpenPGP Signature
2521 * packet(s). It is analogous to a notary seal on the signed data.
2522 * A third-party signature SHOULD include Signature Target
2523 * subpacket(s) to give easy identification. Note that we really do
2524 * mean SHOULD. There are plausible uses for this (such as a blind
2525 * party that only sees the signature, not the key or source
2526 * document) that cannot include a target subpacket. */
2527 thirdParty: 80
2528 },
2529
2530 /** Signature subpacket type
2531 * @enum {Integer}
2532 * @readonly
2533 */
2534 signatureSubpacket: {
2535 signatureCreationTime: 2,
2536 signatureExpirationTime: 3,
2537 exportableCertification: 4,
2538 trustSignature: 5,
2539 regularExpression: 6,
2540 revocable: 7,
2541 keyExpirationTime: 9,
2542 placeholderBackwardsCompatibility: 10,
2543 preferredSymmetricAlgorithms: 11,
2544 revocationKey: 12,
2545 issuer: 16,
2546 notationData: 20,
2547 preferredHashAlgorithms: 21,
2548 preferredCompressionAlgorithms: 22,
2549 keyServerPreferences: 23,
2550 preferredKeyServer: 24,
2551 primaryUserID: 25,
2552 policyURI: 26,
2553 keyFlags: 27,
2554 signersUserID: 28,
2555 reasonForRevocation: 29,
2556 features: 30,
2557 signatureTarget: 31,
2558 embeddedSignature: 32,
2559 issuerFingerprint: 33,
2560 preferredAEADAlgorithms: 34
2561 },
2562
2563 /** Key flags
2564 * @enum {Integer}
2565 * @readonly
2566 */
2567 keyFlags: {
2568 /** 0x01 - This key may be used to certify other keys. */
2569 certifyKeys: 1,
2570 /** 0x02 - This key may be used to sign data. */
2571 signData: 2,
2572 /** 0x04 - This key may be used to encrypt communications. */
2573 encryptCommunication: 4,
2574 /** 0x08 - This key may be used to encrypt storage. */
2575 encryptStorage: 8,
2576 /** 0x10 - The private component of this key may have been split
2577 * by a secret-sharing mechanism. */
2578 splitPrivateKey: 16,
2579 /** 0x20 - This key may be used for authentication. */
2580 authentication: 32,
2581 /** 0x80 - The private component of this key may be in the
2582 * possession of more than one person. */
2583 sharedPrivateKey: 128
2584 },
2585
2586 /** Armor type
2587 * @enum {Integer}
2588 * @readonly
2589 */
2590 armor: {
2591 multipartSection: 0,
2592 multipartLast: 1,
2593 signed: 2,
2594 message: 3,
2595 publicKey: 4,
2596 privateKey: 5,
2597 signature: 6
2598 },
2599
2600 /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}
2601 * @enum {Integer}
2602 * @readonly
2603 */
2604 reasonForRevocation: {
2605 /** No reason specified (key revocations or cert revocations) */
2606 noReason: 0,
2607 /** Key is superseded (key revocations) */
2608 keySuperseded: 1,
2609 /** Key material has been compromised (key revocations) */
2610 keyCompromised: 2,
2611 /** Key is retired and no longer used (key revocations) */
2612 keyRetired: 3,
2613 /** User ID information is no longer valid (cert revocations) */
2614 userIDInvalid: 32
2615 },
2616
2617 /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}
2618 * @enum {Integer}
2619 * @readonly
2620 */
2621 features: {
2622 /** 0x01 - Modification Detection (packets 18 and 19) */
2623 modificationDetection: 1,
2624 /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5
2625 * Symmetric-Key Encrypted Session Key Packets (packet 3) */
2626 aead: 2,
2627 /** 0x04 - Version 5 Public-Key Packet format and corresponding new
2628 * fingerprint format */
2629 v5Keys: 4
2630 },
2631
2632 /** Asserts validity and converts from string/integer to integer. */
2633 write: function(type, e) {
2634 if (typeof e === 'number') {
2635 e = this.read(type, e);
2636 }
2637
2638 if (type[e] !== undefined) {
2639 return type[e];
2640 }
2641
2642 throw new Error('Invalid enum value.');
2643 },
2644
2645 /** Converts from an integer to string. */
2646 read: function(type, e) {
2647 if (!type[byValue]) {
2648 type[byValue] = [];
2649 Object.entries(type).forEach(([key, value]) => {
2650 type[byValue][value] = key;
2651 });
2652 }
2653
2654 if (type[byValue][e] !== undefined) {
2655 return type[byValue][e];
2656 }
2657
2658 throw new Error('Invalid enum value.');
2659 }
2660
2661 };
2662
2663 // GPG4Browsers - An OpenPGP implementation in javascript
2664
2665 var defaultConfig = {
2666 /**
2667 * @memberof module:config
2668 * @property {Integer} preferredHashAlgorithm Default hash algorithm {@link module:enums.hash}
2669 */
2670 preferredHashAlgorithm: enums.hash.sha256,
2671 /**
2672 * @memberof module:config
2673 * @property {Integer} preferredSymmetricAlgorithm Default encryption cipher {@link module:enums.symmetric}
2674 */
2675 preferredSymmetricAlgorithm: enums.symmetric.aes256,
2676 /**
2677 * @memberof module:config
2678 * @property {Integer} compression Default compression algorithm {@link module:enums.compression}
2679 */
2680 preferredCompressionAlgorithm: enums.compression.uncompressed,
2681 /**
2682 * @memberof module:config
2683 * @property {Integer} deflateLevel Default zip/zlib compression level, between 1 and 9
2684 */
2685 deflateLevel: 6,
2686
2687 /**
2688 * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.
2689 * Note: not all OpenPGP implementations are compatible with this option.
2690 * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
2691 * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07}
2692 * @memberof module:config
2693 * @property {Boolean} aeadProtect
2694 */
2695 aeadProtect: false,
2696 /**
2697 * Default Authenticated Encryption with Additional Data (AEAD) encryption mode
2698 * Only has an effect when aeadProtect is set to true.
2699 * @memberof module:config
2700 * @property {Integer} preferredAEADAlgorithm Default AEAD mode {@link module:enums.aead}
2701 */
2702 preferredAEADAlgorithm: enums.aead.eax,
2703 /**
2704 * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode
2705 * Only has an effect when aeadProtect is set to true.
2706 * Must be an integer value from 0 to 56.
2707 * @memberof module:config
2708 * @property {Integer} aeadChunkSizeByte
2709 */
2710 aeadChunkSizeByte: 12,
2711 /**
2712 * Use V5 keys.
2713 * Note: not all OpenPGP implementations are compatible with this option.
2714 * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
2715 * @memberof module:config
2716 * @property {Boolean} v5Keys
2717 */
2718 v5Keys: false,
2719 /**
2720 * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}:
2721 * Iteration Count Byte for S2K (String to Key)
2722 * @memberof module:config
2723 * @property {Integer} s2kIterationCountByte
2724 */
2725 s2kIterationCountByte: 224,
2726 /**
2727 * Allow decryption of messages without integrity protection.
2728 * This is an **insecure** setting:
2729 * - message modifications cannot be detected, thus processing the decrypted data is potentially unsafe.
2730 * - it enables downgrade attacks against integrity-protected messages.
2731 * @memberof module:config
2732 * @property {Boolean} allowUnauthenticatedMessages
2733 */
2734 allowUnauthenticatedMessages: false,
2735 /**
2736 * Allow streaming unauthenticated data before its integrity has been checked.
2737 * This setting is **insecure** if the partially decrypted message is processed further or displayed to the user.
2738 * @memberof module:config
2739 * @property {Boolean} allowUnauthenticatedStream
2740 */
2741 allowUnauthenticatedStream: false,
2742 /**
2743 * @memberof module:config
2744 * @property {Boolean} checksumRequired Do not throw error when armor is missing a checksum
2745 */
2746 checksumRequired: false,
2747 /**
2748 * Minimum RSA key size allowed for key generation and message signing, verification and encryption.
2749 * The default is 2047 since due to a bug, previous versions of OpenPGP.js could generate 2047-bit keys instead of 2048-bit ones.
2750 * @memberof module:config
2751 * @property {Number} minRSABits
2752 */
2753 minRSABits: 2047,
2754 /**
2755 * Work-around for rare GPG decryption bug when encrypting with multiple passwords.
2756 * **Slower and slightly less secure**
2757 * @memberof module:config
2758 * @property {Boolean} passwordCollisionCheck
2759 */
2760 passwordCollisionCheck: false,
2761 /**
2762 * @memberof module:config
2763 * @property {Boolean} revocationsExpire If true, expired revocation signatures are ignored
2764 */
2765 revocationsExpire: false,
2766 /**
2767 * Allow decryption using RSA keys without `encrypt` flag.
2768 * This setting is potentially insecure, but it is needed to get around an old openpgpjs bug
2769 * where key flags were ignored when selecting a key for encryption.
2770 * @memberof module:config
2771 * @property {Boolean} allowInsecureDecryptionWithSigningKeys
2772 */
2773 allowInsecureDecryptionWithSigningKeys: false,
2774
2775 /**
2776 * @memberof module:config
2777 * @property {Integer} minBytesForWebCrypto The minimum amount of bytes for which to use native WebCrypto APIs when available
2778 */
2779 minBytesForWebCrypto: 1000,
2780 /**
2781 * @memberof module:config
2782 * @property {Boolean} ignoreUnsupportedPackets Ignore unsupported/unrecognizable packets on parsing instead of throwing an error
2783 */
2784 ignoreUnsupportedPackets: true,
2785 /**
2786 * @memberof module:config
2787 * @property {Boolean} ignoreMalformedPackets Ignore malformed packets on parsing instead of throwing an error
2788 */
2789 ignoreMalformedPackets: false,
2790 /**
2791 * @memberof module:config
2792 * @property {Boolean} showVersion Whether to include {@link module:config/config.versionString} in armored messages
2793 */
2794 showVersion: false,
2795 /**
2796 * @memberof module:config
2797 * @property {Boolean} showComment Whether to include {@link module:config/config.commentString} in armored messages
2798 */
2799 showComment: false,
2800 /**
2801 * @memberof module:config
2802 * @property {String} versionString A version string to be included in armored messages
2803 */
2804 versionString: 'OpenPGP.js 5.0.0',
2805 /**
2806 * @memberof module:config
2807 * @property {String} commentString A comment string to be included in armored messages
2808 */
2809 commentString: 'https://openpgpjs.org',
2810
2811 /**
2812 * Max userID string length (used for parsing)
2813 * @memberof module:config
2814 * @property {Integer} maxUserIDLength
2815 */
2816 maxUserIDLength: 1024 * 5,
2817 /**
2818 * Contains notatations that are considered "known". Known notations do not trigger
2819 * validation error when the notation is marked as critical.
2820 * @memberof module:config
2821 * @property {Array} knownNotations
2822 */
2823 knownNotations: ['preferred-email-encoding@pgp.com', 'pka-address@gnupg.org'],
2824 /**
2825 * Whether to use the indutny/elliptic library for curves (other than Curve25519) that are not supported by the available native crypto API.
2826 * When false, certain standard curves will not be supported (depending on the platform).
2827 * Note: the indutny/elliptic curve library is not designed to be constant time.
2828 * @memberof module:config
2829 * @property {Boolean} useIndutnyElliptic
2830 */
2831 useIndutnyElliptic: true,
2832 /**
2833 * Reject insecure hash algorithms
2834 * @memberof module:config
2835 * @property {Set<Integer>} rejectHashAlgorithms {@link module:enums.hash}
2836 */
2837 rejectHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd]),
2838 /**
2839 * Reject insecure message hash algorithms
2840 * @memberof module:config
2841 * @property {Set<Integer>} rejectMessageHashAlgorithms {@link module:enums.hash}
2842 */
2843 rejectMessageHashAlgorithms: new Set([enums.hash.md5, enums.hash.ripemd, enums.hash.sha1]),
2844 /**
2845 * Reject insecure public key algorithms for key generation and message encryption, signing or verification
2846 * @memberof module:config
2847 * @property {Set<Integer>} rejectPublicKeyAlgorithms {@link module:enums.publicKey}
2848 */
2849 rejectPublicKeyAlgorithms: new Set([enums.publicKey.elgamal, enums.publicKey.dsa]),
2850 /**
2851 * Reject non-standard curves for key generation, message encryption, signing or verification
2852 * @memberof module:config
2853 * @property {Set<String>} rejectCurves {@link module:enums.curve}
2854 */
2855 rejectCurves: new Set([enums.curve.brainpoolP256r1, enums.curve.brainpoolP384r1, enums.curve.brainpoolP512r1, enums.curve.secp256k1])
2856 };
2857
2858 // GPG4Browsers - An OpenPGP implementation in javascript
2859
2860 /**
2861 * Finds out which Ascii Armoring type is used. Throws error if unknown type.
2862 * @param {String} text - ascii armored text
2863 * @returns {Integer} 0 = MESSAGE PART n of m.
2864 * 1 = MESSAGE PART n
2865 * 2 = SIGNED MESSAGE
2866 * 3 = PGP MESSAGE
2867 * 4 = PUBLIC KEY BLOCK
2868 * 5 = PRIVATE KEY BLOCK
2869 * 6 = SIGNATURE
2870 * @private
2871 */
2872 function getType(text) {
2873 const reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;
2874
2875 const header = text.match(reHeader);
2876
2877 if (!header) {
2878 throw new Error('Unknown ASCII armor type');
2879 }
2880
2881 // BEGIN PGP MESSAGE, PART X/Y
2882 // Used for multi-part messages, where the armor is split amongst Y
2883 // parts, and this is the Xth part out of Y.
2884 if (/MESSAGE, PART \d+\/\d+/.test(header[1])) {
2885 return enums.armor.multipartSection;
2886 } else
2887 // BEGIN PGP MESSAGE, PART X
2888 // Used for multi-part messages, where this is the Xth part of an
2889 // unspecified number of parts. Requires the MESSAGE-ID Armor
2890 // Header to be used.
2891 if (/MESSAGE, PART \d+/.test(header[1])) {
2892 return enums.armor.multipartLast;
2893 } else
2894 // BEGIN PGP SIGNED MESSAGE
2895 if (/SIGNED MESSAGE/.test(header[1])) {
2896 return enums.armor.signed;
2897 } else
2898 // BEGIN PGP MESSAGE
2899 // Used for signed, encrypted, or compressed files.
2900 if (/MESSAGE/.test(header[1])) {
2901 return enums.armor.message;
2902 } else
2903 // BEGIN PGP PUBLIC KEY BLOCK
2904 // Used for armoring public keys.
2905 if (/PUBLIC KEY BLOCK/.test(header[1])) {
2906 return enums.armor.publicKey;
2907 } else
2908 // BEGIN PGP PRIVATE KEY BLOCK
2909 // Used for armoring private keys.
2910 if (/PRIVATE KEY BLOCK/.test(header[1])) {
2911 return enums.armor.privateKey;
2912 } else
2913 // BEGIN PGP SIGNATURE
2914 // Used for detached signatures, OpenPGP/MIME signatures, and
2915 // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE
2916 // for detached signatures.
2917 if (/SIGNATURE/.test(header[1])) {
2918 return enums.armor.signature;
2919 }
2920 }
2921
2922 /**
2923 * Add additional information to the armor version of an OpenPGP binary
2924 * packet block.
2925 * @author Alex
2926 * @version 2011-12-16
2927 * @param {String} [customComment] - Additional comment to add to the armored string
2928 * @returns {String} The header information.
2929 * @private
2930 */
2931 function addheader(customComment, config) {
2932 let result = '';
2933 if (config.showVersion) {
2934 result += 'Version: ' + config.versionString + '\n';
2935 }
2936 if (config.showComment) {
2937 result += 'Comment: ' + config.commentString + '\n';
2938 }
2939 if (customComment) {
2940 result += 'Comment: ' + customComment + '\n';
2941 }
2942 result += '\n';
2943 return result;
2944 }
2945
2946
2947 /**
2948 * Calculates a checksum over the given data and returns it base64 encoded
2949 * @param {String | ReadableStream<String>} data - Data to create a CRC-24 checksum for
2950 * @returns {String | ReadableStream<String>} Base64 encoded checksum.
2951 * @private
2952 */
2953 function getCheckSum(data) {
2954 const crc = createcrc24(data);
2955 return encode(crc);
2956 }
2957
2958 // https://create.stephan-brumme.com/crc32/#slicing-by-8-overview
2959
2960 const crc_table = [
2961 new Array(0xFF),
2962 new Array(0xFF),
2963 new Array(0xFF),
2964 new Array(0xFF)
2965 ];
2966
2967 for (let i = 0; i <= 0xFF; i++) {
2968 let crc = i << 16;
2969 for (let j = 0; j < 8; j++) {
2970 crc = (crc << 1) ^ ((crc & 0x800000) !== 0 ? 0x864CFB : 0);
2971 }
2972 crc_table[0][i] =
2973 ((crc & 0xFF0000) >> 16) |
2974 (crc & 0x00FF00) |
2975 ((crc & 0x0000FF) << 16);
2976 }
2977 for (let i = 0; i <= 0xFF; i++) {
2978 crc_table[1][i] = (crc_table[0][i] >> 8) ^ crc_table[0][crc_table[0][i] & 0xFF];
2979 }
2980 for (let i = 0; i <= 0xFF; i++) {
2981 crc_table[2][i] = (crc_table[1][i] >> 8) ^ crc_table[0][crc_table[1][i] & 0xFF];
2982 }
2983 for (let i = 0; i <= 0xFF; i++) {
2984 crc_table[3][i] = (crc_table[2][i] >> 8) ^ crc_table[0][crc_table[2][i] & 0xFF];
2985 }
2986
2987 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness
2988 const isLittleEndian = (function() {
2989 const buffer = new ArrayBuffer(2);
2990 new DataView(buffer).setInt16(0, 0xFF, true /* littleEndian */);
2991 // Int16Array uses the platform's endianness.
2992 return new Int16Array(buffer)[0] === 0xFF;
2993 }());
2994
2995 /**
2996 * Internal function to calculate a CRC-24 checksum over a given string (data)
2997 * @param {String | ReadableStream<String>} input - Data to create a CRC-24 checksum for
2998 * @returns {Uint8Array | ReadableStream<Uint8Array>} The CRC-24 checksum.
2999 * @private
3000 */
3001 function createcrc24(input) {
3002 let crc = 0xCE04B7;
3003 return transform(input, value => {
3004 const len32 = isLittleEndian ? Math.floor(value.length / 4) : 0;
3005 const arr32 = new Uint32Array(value.buffer, value.byteOffset, len32);
3006 for (let i = 0; i < len32; i++) {
3007 crc ^= arr32[i];
3008 crc =
3009 crc_table[0][(crc >> 24) & 0xFF] ^
3010 crc_table[1][(crc >> 16) & 0xFF] ^
3011 crc_table[2][(crc >> 8) & 0xFF] ^
3012 crc_table[3][(crc >> 0) & 0xFF];
3013 }
3014 for (let i = len32 * 4; i < value.length; i++) {
3015 crc = (crc >> 8) ^ crc_table[0][(crc & 0xFF) ^ value[i]];
3016 }
3017 }, () => new Uint8Array([crc, crc >> 8, crc >> 16]));
3018 }
3019
3020 /**
3021 * Verify armored headers. RFC4880, section 6.3: "OpenPGP should consider improperly formatted
3022 * Armor Headers to be corruption of the ASCII Armor."
3023 * @private
3024 * @param {Array<String>} headers - Armor headers
3025 */
3026 function verifyHeaders(headers) {
3027 for (let i = 0; i < headers.length; i++) {
3028 if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) {
3029 throw new Error('Improperly formatted armor header: ' + headers[i]);
3030 }
3031 if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {
3032 util.printDebugError(new Error('Unknown header: ' + headers[i]));
3033 }
3034 }
3035 }
3036
3037 /**
3038 * Splits a message into two parts, the body and the checksum. This is an internal function
3039 * @param {String} text - OpenPGP armored message part
3040 * @returns {Object} An object with attribute "body" containing the body.
3041 * and an attribute "checksum" containing the checksum.
3042 * @private
3043 */
3044 function splitChecksum(text) {
3045 let body = text;
3046 let checksum = '';
3047
3048 const lastEquals = text.lastIndexOf('=');
3049
3050 if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum
3051 body = text.slice(0, lastEquals);
3052 checksum = text.slice(lastEquals + 1).substr(0, 4);
3053 }
3054
3055 return { body: body, checksum: checksum };
3056 }
3057
3058 /**
3059 * Dearmor an OpenPGP armored message; verify the checksum and return
3060 * the encoded bytes
3061 * @param {String} input - OpenPGP armored message
3062 * @returns {Promise<Object>} An object with attribute "text" containing the message text,
3063 * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type
3064 * @async
3065 * @static
3066 */
3067 function unarmor(input, config = defaultConfig) {
3068 return new Promise(async (resolve, reject) => {
3069 try {
3070 const reSplit = /^-----[^-]+-----$/m;
3071 const reEmptyLine = /^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;
3072
3073 let type;
3074 const headers = [];
3075 let lastHeaders = headers;
3076 let headersDone;
3077 let text = [];
3078 let textDone;
3079 let checksum;
3080 let data = decode(transformPair(input, async (readable, writable) => {
3081 const reader = getReader(readable);
3082 try {
3083 while (true) {
3084 let line = await reader.readLine();
3085 if (line === undefined) {
3086 throw new Error('Misformed armored text');
3087 }
3088 // remove trailing whitespace at end of lines
3089 line = util.removeTrailingSpaces(line.replace(/[\r\n]/g, ''));
3090 if (!type) {
3091 if (reSplit.test(line)) {
3092 type = getType(line);
3093 }
3094 } else if (!headersDone) {
3095 if (reSplit.test(line)) {
3096 reject(new Error('Mandatory blank line missing between armor headers and armor data'));
3097 }
3098 if (!reEmptyLine.test(line)) {
3099 lastHeaders.push(line);
3100 } else {
3101 verifyHeaders(lastHeaders);
3102 headersDone = true;
3103 if (textDone || type !== 2) {
3104 resolve({ text, data, headers, type });
3105 break;
3106 }
3107 }
3108 } else if (!textDone && type === 2) {
3109 if (!reSplit.test(line)) {
3110 // Reverse dash-escaping for msg
3111 text.push(line.replace(/^- /, ''));
3112 } else {
3113 text = text.join('\r\n');
3114 textDone = true;
3115 verifyHeaders(lastHeaders);
3116 lastHeaders = [];
3117 headersDone = false;
3118 }
3119 }
3120 }
3121 } catch (e) {
3122 reject(e);
3123 return;
3124 }
3125 const writer = getWriter(writable);
3126 try {
3127 while (true) {
3128 await writer.ready;
3129 const { done, value } = await reader.read();
3130 if (done) {
3131 throw new Error('Misformed armored text');
3132 }
3133 const line = value + '';
3134 if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {
3135 await writer.write(line);
3136 } else {
3137 let remainder = await reader.readToEnd();
3138 if (!remainder.length) remainder = '';
3139 remainder = line + remainder;
3140 remainder = util.removeTrailingSpaces(remainder.replace(/\r/g, ''));
3141 const parts = remainder.split(reSplit);
3142 if (parts.length === 1) {
3143 throw new Error('Misformed armored text');
3144 }
3145 const split = splitChecksum(parts[0].slice(0, -1));
3146 checksum = split.checksum;
3147 await writer.write(split.body);
3148 break;
3149 }
3150 }
3151 await writer.ready;
3152 await writer.close();
3153 } catch (e) {
3154 await writer.abort(e);
3155 }
3156 }));
3157 data = transformPair(data, async (readable, writable) => {
3158 const checksumVerified = readToEnd(getCheckSum(passiveClone(readable)));
3159 checksumVerified.catch(() => {});
3160 await pipe(readable, writable, {
3161 preventClose: true
3162 });
3163 const writer = getWriter(writable);
3164 try {
3165 const checksumVerifiedString = (await checksumVerified).replace('\n', '');
3166 if (checksum !== checksumVerifiedString && (checksum || config.checksumRequired)) {
3167 throw new Error("Ascii armor integrity check on message failed: '" + checksum + "' should be '" +
3168 checksumVerifiedString + "'");
3169 }
3170 await writer.ready;
3171 await writer.close();
3172 } catch (e) {
3173 await writer.abort(e);
3174 }
3175 });
3176 } catch (e) {
3177 reject(e);
3178 }
3179 }).then(async result => {
3180 if (isArrayStream(result.data)) {
3181 result.data = await readToEnd(result.data);
3182 }
3183 return result;
3184 });
3185 }
3186
3187
3188 /**
3189 * Armor an OpenPGP binary packet block
3190 * @param {module:enums.armor} messageType - Type of the message
3191 * @param {Uint8Array | ReadableStream<Uint8Array>} body - The message body to armor
3192 * @param {Integer} [partIndex]
3193 * @param {Integer} [partTotal]
3194 * @param {String} [customComment] - Additional comment to add to the armored string
3195 * @returns {String | ReadableStream<String>} Armored text.
3196 * @static
3197 */
3198 function armor(messageType, body, partIndex, partTotal, customComment, config = defaultConfig) {
3199 let text;
3200 let hash;
3201 if (messageType === enums.armor.signed) {
3202 text = body.text;
3203 hash = body.hash;
3204 body = body.data;
3205 }
3206 const bodyClone = passiveClone(body);
3207 const result = [];
3208 switch (messageType) {
3209 case enums.armor.multipartSection:
3210 result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n');
3211 result.push(addheader(customComment, config));
3212 result.push(encode(body));
3213 result.push('=', getCheckSum(bodyClone));
3214 result.push('-----END PGP MESSAGE, PART ' + partIndex + '/' + partTotal + '-----\n');
3215 break;
3216 case enums.armor.multipartLast:
3217 result.push('-----BEGIN PGP MESSAGE, PART ' + partIndex + '-----\n');
3218 result.push(addheader(customComment, config));
3219 result.push(encode(body));
3220 result.push('=', getCheckSum(bodyClone));
3221 result.push('-----END PGP MESSAGE, PART ' + partIndex + '-----\n');
3222 break;
3223 case enums.armor.signed:
3224 result.push('\n-----BEGIN PGP SIGNED MESSAGE-----\n');
3225 result.push('Hash: ' + hash + '\n\n');
3226 result.push(text.replace(/^-/mg, '- -'));
3227 result.push('\n-----BEGIN PGP SIGNATURE-----\n');
3228 result.push(addheader(customComment, config));
3229 result.push(encode(body));
3230 result.push('=', getCheckSum(bodyClone));
3231 result.push('-----END PGP SIGNATURE-----\n');
3232 break;
3233 case enums.armor.message:
3234 result.push('-----BEGIN PGP MESSAGE-----\n');
3235 result.push(addheader(customComment, config));
3236 result.push(encode(body));
3237 result.push('=', getCheckSum(bodyClone));
3238 result.push('-----END PGP MESSAGE-----\n');
3239 break;
3240 case enums.armor.publicKey:
3241 result.push('-----BEGIN PGP PUBLIC KEY BLOCK-----\n');
3242 result.push(addheader(customComment, config));
3243 result.push(encode(body));
3244 result.push('=', getCheckSum(bodyClone));
3245 result.push('-----END PGP PUBLIC KEY BLOCK-----\n');
3246 break;
3247 case enums.armor.privateKey:
3248 result.push('-----BEGIN PGP PRIVATE KEY BLOCK-----\n');
3249 result.push(addheader(customComment, config));
3250 result.push(encode(body));
3251 result.push('=', getCheckSum(bodyClone));
3252 result.push('-----END PGP PRIVATE KEY BLOCK-----\n');
3253 break;
3254 case enums.armor.signature:
3255 result.push('-----BEGIN PGP SIGNATURE-----\n');
3256 result.push(addheader(customComment, config));
3257 result.push(encode(body));
3258 result.push('=', getCheckSum(bodyClone));
3259 result.push('-----END PGP SIGNATURE-----\n');
3260 break;
3261 }
3262
3263 return util.concat(result);
3264 }
3265
3266 // GPG4Browsers - An OpenPGP implementation in javascript
3267
3268 /**
3269 * Implementation of type key id
3270 *
3271 * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:
3272 * A Key ID is an eight-octet scalar that identifies a key.
3273 * Implementations SHOULD NOT assume that Key IDs are unique. The
3274 * section "Enhanced Key Formats" below describes how Key IDs are
3275 * formed.
3276 */
3277 class KeyID {
3278 constructor() {
3279 this.bytes = '';
3280 }
3281
3282 /**
3283 * Parsing method for a key id
3284 * @param {Uint8Array} bytes - Input to read the key id from
3285 */
3286 read(bytes) {
3287 this.bytes = util.uint8ArrayToString(bytes.subarray(0, 8));
3288 }
3289
3290 /**
3291 * Serializes the Key ID
3292 * @returns {Uint8Array} Key ID as a Uint8Array.
3293 */
3294 write() {
3295 return util.stringToUint8Array(this.bytes);
3296 }
3297
3298 /**
3299 * Returns the Key ID represented as a hexadecimal string
3300 * @returns {String} Key ID as a hexadecimal string.
3301 */
3302 toHex() {
3303 return util.uint8ArrayToHex(util.stringToUint8Array(this.bytes));
3304 }
3305
3306 /**
3307 * Checks equality of Key ID's
3308 * @param {KeyID} keyID
3309 * @param {Boolean} matchWildcard - Indicates whether to check if either keyID is a wildcard
3310 */
3311 equals(keyID, matchWildcard = false) {
3312 return (matchWildcard && (keyID.isWildcard() || this.isWildcard())) || this.bytes === keyID.bytes;
3313 }
3314
3315 /**
3316 * Checks to see if the Key ID is unset
3317 * @returns {Boolean} True if the Key ID is null.
3318 */
3319 isNull() {
3320 return this.bytes === '';
3321 }
3322
3323 /**
3324 * Checks to see if the Key ID is a "wildcard" Key ID (all zeros)
3325 * @returns {Boolean} True if this is a wildcard Key ID.
3326 */
3327 isWildcard() {
3328 return /^0+$/.test(this.toHex());
3329 }
3330
3331 static mapToHex(keyID) {
3332 return keyID.toHex();
3333 }
3334
3335 static fromID(hex) {
3336 const keyID = new KeyID();
3337 keyID.read(util.hexToUint8Array(hex));
3338 return keyID;
3339 }
3340
3341 static wildcard() {
3342 const keyID = new KeyID();
3343 keyID.read(new Uint8Array(8));
3344 return keyID;
3345 }
3346 }
3347
3348 /**
3349 * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}.
3350 * @author Artem S Vybornov <vybornov@gmail.com>
3351 * @license MIT
3352 */
3353 var AES_asm = function () {
3354
3355 /**
3356 * Galois Field stuff init flag
3357 */
3358 var ginit_done = false;
3359
3360 /**
3361 * Galois Field exponentiation and logarithm tables for 3 (the generator)
3362 */
3363 var gexp3, glog3;
3364
3365 /**
3366 * Init Galois Field tables
3367 */
3368 function ginit() {
3369 gexp3 = [],
3370 glog3 = [];
3371
3372 var a = 1, c, d;
3373 for (c = 0; c < 255; c++) {
3374 gexp3[c] = a;
3375
3376 // Multiply by three
3377 d = a & 0x80, a <<= 1, a &= 255;
3378 if (d === 0x80) a ^= 0x1b;
3379 a ^= gexp3[c];
3380
3381 // Set the log table value
3382 glog3[gexp3[c]] = c;
3383 }
3384 gexp3[255] = gexp3[0];
3385 glog3[0] = 0;
3386
3387 ginit_done = true;
3388 }
3389
3390 /**
3391 * Galois Field multiplication
3392 * @param {number} a
3393 * @param {number} b
3394 * @return {number}
3395 */
3396 function gmul(a, b) {
3397 var c = gexp3[(glog3[a] + glog3[b]) % 255];
3398 if (a === 0 || b === 0) c = 0;
3399 return c;
3400 }
3401
3402 /**
3403 * Galois Field reciprocal
3404 * @param {number} a
3405 * @return {number}
3406 */
3407 function ginv(a) {
3408 var i = gexp3[255 - glog3[a]];
3409 if (a === 0) i = 0;
3410 return i;
3411 }
3412
3413 /**
3414 * AES stuff init flag
3415 */
3416 var aes_init_done = false;
3417
3418 /**
3419 * Encryption, Decryption, S-Box and KeyTransform tables
3420 *
3421 * @type {number[]}
3422 */
3423 var aes_sbox;
3424
3425 /**
3426 * @type {number[]}
3427 */
3428 var aes_sinv;
3429
3430 /**
3431 * @type {number[][]}
3432 */
3433 var aes_enc;
3434
3435 /**
3436 * @type {number[][]}
3437 */
3438 var aes_dec;
3439
3440 /**
3441 * Init AES tables
3442 */
3443 function aes_init() {
3444 if (!ginit_done) ginit();
3445
3446 // Calculates AES S-Box value
3447 function _s(a) {
3448 var c, s, x;
3449 s = x = ginv(a);
3450 for (c = 0; c < 4; c++) {
3451 s = ((s << 1) | (s >>> 7)) & 255;
3452 x ^= s;
3453 }
3454 x ^= 99;
3455 return x;
3456 }
3457
3458 // Tables
3459 aes_sbox = [],
3460 aes_sinv = [],
3461 aes_enc = [[], [], [], []],
3462 aes_dec = [[], [], [], []];
3463
3464 for (var i = 0; i < 256; i++) {
3465 var s = _s(i);
3466
3467 // S-Box and its inverse
3468 aes_sbox[i] = s;
3469 aes_sinv[s] = i;
3470
3471 // Ecryption and Decryption tables
3472 aes_enc[0][i] = (gmul(2, s) << 24) | (s << 16) | (s << 8) | gmul(3, s);
3473 aes_dec[0][s] = (gmul(14, i) << 24) | (gmul(9, i) << 16) | (gmul(13, i) << 8) | gmul(11, i);
3474 // Rotate tables
3475 for (var t = 1; t < 4; t++) {
3476 aes_enc[t][i] = (aes_enc[t - 1][i] >>> 8) | (aes_enc[t - 1][i] << 24);
3477 aes_dec[t][s] = (aes_dec[t - 1][s] >>> 8) | (aes_dec[t - 1][s] << 24);
3478 }
3479 }
3480
3481 aes_init_done = true;
3482 }
3483
3484 /**
3485 * Asm.js module constructor.
3486 *
3487 * <p>
3488 * Heap buffer layout by offset:
3489 * <pre>
3490 * 0x0000 encryption key schedule
3491 * 0x0400 decryption key schedule
3492 * 0x0800 sbox
3493 * 0x0c00 inv sbox
3494 * 0x1000 encryption tables
3495 * 0x2000 decryption tables
3496 * 0x3000 reserved (future GCM multiplication lookup table)
3497 * 0x4000 data
3498 * </pre>
3499 * Don't touch anything before <code>0x400</code>.
3500 * </p>
3501 *
3502 * @alias AES_asm
3503 * @class
3504 * @param foreign - <i>ignored</i>
3505 * @param buffer - heap buffer to link with
3506 */
3507 var wrapper = function (foreign, buffer) {
3508 // Init AES stuff for the first time
3509 if (!aes_init_done) aes_init();
3510
3511 // Fill up AES tables
3512 var heap = new Uint32Array(buffer);
3513 heap.set(aes_sbox, 0x0800 >> 2);
3514 heap.set(aes_sinv, 0x0c00 >> 2);
3515 for (var i = 0; i < 4; i++) {
3516 heap.set(aes_enc[i], (0x1000 + 0x400 * i) >> 2);
3517 heap.set(aes_dec[i], (0x2000 + 0x400 * i) >> 2);
3518 }
3519
3520 /**
3521 * Calculate AES key schedules.
3522 * @instance
3523 * @memberof AES_asm
3524 * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly)
3525 * @param {number} k0 - key vector components
3526 * @param {number} k1 - key vector components
3527 * @param {number} k2 - key vector components
3528 * @param {number} k3 - key vector components
3529 * @param {number} k4 - key vector components
3530 * @param {number} k5 - key vector components
3531 * @param {number} k6 - key vector components
3532 * @param {number} k7 - key vector components
3533 */
3534 function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) {
3535 var ekeys = heap.subarray(0x000, 60),
3536 dkeys = heap.subarray(0x100, 0x100 + 60);
3537
3538 // Encryption key schedule
3539 ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]);
3540 for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) {
3541 var k = ekeys[i - 1];
3542 if ((i % ks === 0) || (ks === 8 && i % ks === 4)) {
3543 k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255];
3544 }
3545 if (i % ks === 0) {
3546 k = (k << 8) ^ (k >>> 24) ^ (rcon << 24);
3547 rcon = (rcon << 1) ^ ((rcon & 0x80) ? 0x1b : 0);
3548 }
3549 ekeys[i] = ekeys[i - ks] ^ k;
3550 }
3551
3552 // Decryption key schedule
3553 for (var j = 0; j < i; j += 4) {
3554 for (var jj = 0; jj < 4; jj++) {
3555 var k = ekeys[i - (4 + j) + (4 - jj) % 4];
3556 if (j < 4 || j >= i - 4) {
3557 dkeys[j + jj] = k;
3558 } else {
3559 dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]]
3560 ^ aes_dec[1][aes_sbox[k >>> 16 & 255]]
3561 ^ aes_dec[2][aes_sbox[k >>> 8 & 255]]
3562 ^ aes_dec[3][aes_sbox[k & 255]];
3563 }
3564 }
3565 }
3566
3567 // Set rounds number
3568 asm.set_rounds(ks + 5);
3569 }
3570
3571 // create library object with necessary properties
3572 var stdlib = {Uint8Array: Uint8Array, Uint32Array: Uint32Array};
3573
3574 var asm = function (stdlib, foreign, buffer) {
3575 "use asm";
3576
3577 var S0 = 0, S1 = 0, S2 = 0, S3 = 0,
3578 I0 = 0, I1 = 0, I2 = 0, I3 = 0,
3579 N0 = 0, N1 = 0, N2 = 0, N3 = 0,
3580 M0 = 0, M1 = 0, M2 = 0, M3 = 0,
3581 H0 = 0, H1 = 0, H2 = 0, H3 = 0,
3582 R = 0;
3583
3584 var HEAP = new stdlib.Uint32Array(buffer),
3585 DATA = new stdlib.Uint8Array(buffer);
3586
3587 /**
3588 * AES core
3589 * @param {number} k - precomputed key schedule offset
3590 * @param {number} s - precomputed sbox table offset
3591 * @param {number} t - precomputed round table offset
3592 * @param {number} r - number of inner rounds to perform
3593 * @param {number} x0 - 128-bit input block vector
3594 * @param {number} x1 - 128-bit input block vector
3595 * @param {number} x2 - 128-bit input block vector
3596 * @param {number} x3 - 128-bit input block vector
3597 */
3598 function _core(k, s, t, r, x0, x1, x2, x3) {
3599 k = k | 0;
3600 s = s | 0;
3601 t = t | 0;
3602 r = r | 0;
3603 x0 = x0 | 0;
3604 x1 = x1 | 0;
3605 x2 = x2 | 0;
3606 x3 = x3 | 0;
3607
3608 var t1 = 0, t2 = 0, t3 = 0,
3609 y0 = 0, y1 = 0, y2 = 0, y3 = 0,
3610 i = 0;
3611
3612 t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00;
3613
3614 // round 0
3615 x0 = x0 ^ HEAP[(k | 0) >> 2],
3616 x1 = x1 ^ HEAP[(k | 4) >> 2],
3617 x2 = x2 ^ HEAP[(k | 8) >> 2],
3618 x3 = x3 ^ HEAP[(k | 12) >> 2];
3619
3620 // round 1..r
3621 for (i = 16; (i | 0) <= (r << 4); i = (i + 16) | 0) {
3622 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],
3623 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],
3624 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],
3625 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];
3626 x0 = y0, x1 = y1, x2 = y2, x3 = y3;
3627 }
3628
3629 // final round
3630 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],
3631 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],
3632 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],
3633 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];
3634 }
3635
3636 /**
3637 * ECB mode encryption
3638 * @param {number} x0 - 128-bit input block vector
3639 * @param {number} x1 - 128-bit input block vector
3640 * @param {number} x2 - 128-bit input block vector
3641 * @param {number} x3 - 128-bit input block vector
3642 */
3643 function _ecb_enc(x0, x1, x2, x3) {
3644 x0 = x0 | 0;
3645 x1 = x1 | 0;
3646 x2 = x2 | 0;
3647 x3 = x3 | 0;
3648
3649 _core(
3650 0x0000, 0x0800, 0x1000,
3651 R,
3652 x0,
3653 x1,
3654 x2,
3655 x3
3656 );
3657 }
3658
3659 /**
3660 * ECB mode decryption
3661 * @param {number} x0 - 128-bit input block vector
3662 * @param {number} x1 - 128-bit input block vector
3663 * @param {number} x2 - 128-bit input block vector
3664 * @param {number} x3 - 128-bit input block vector
3665 */
3666 function _ecb_dec(x0, x1, x2, x3) {
3667 x0 = x0 | 0;
3668 x1 = x1 | 0;
3669 x2 = x2 | 0;
3670 x3 = x3 | 0;
3671
3672 var t = 0;
3673
3674 _core(
3675 0x0400, 0x0c00, 0x2000,
3676 R,
3677 x0,
3678 x3,
3679 x2,
3680 x1
3681 );
3682
3683 t = S1, S1 = S3, S3 = t;
3684 }
3685
3686
3687 /**
3688 * CBC mode encryption
3689 * @param {number} x0 - 128-bit input block vector
3690 * @param {number} x1 - 128-bit input block vector
3691 * @param {number} x2 - 128-bit input block vector
3692 * @param {number} x3 - 128-bit input block vector
3693 */
3694 function _cbc_enc(x0, x1, x2, x3) {
3695 x0 = x0 | 0;
3696 x1 = x1 | 0;
3697 x2 = x2 | 0;
3698 x3 = x3 | 0;
3699
3700 _core(
3701 0x0000, 0x0800, 0x1000,
3702 R,
3703 I0 ^ x0,
3704 I1 ^ x1,
3705 I2 ^ x2,
3706 I3 ^ x3
3707 );
3708
3709 I0 = S0,
3710 I1 = S1,
3711 I2 = S2,
3712 I3 = S3;
3713 }
3714
3715 /**
3716 * CBC mode decryption
3717 * @param {number} x0 - 128-bit input block vector
3718 * @param {number} x1 - 128-bit input block vector
3719 * @param {number} x2 - 128-bit input block vector
3720 * @param {number} x3 - 128-bit input block vector
3721 */
3722 function _cbc_dec(x0, x1, x2, x3) {
3723 x0 = x0 | 0;
3724 x1 = x1 | 0;
3725 x2 = x2 | 0;
3726 x3 = x3 | 0;
3727
3728 var t = 0;
3729
3730 _core(
3731 0x0400, 0x0c00, 0x2000,
3732 R,
3733 x0,
3734 x3,
3735 x2,
3736 x1
3737 );
3738
3739 t = S1, S1 = S3, S3 = t;
3740
3741 S0 = S0 ^ I0,
3742 S1 = S1 ^ I1,
3743 S2 = S2 ^ I2,
3744 S3 = S3 ^ I3;
3745
3746 I0 = x0,
3747 I1 = x1,
3748 I2 = x2,
3749 I3 = x3;
3750 }
3751
3752 /**
3753 * CFB mode encryption
3754 * @param {number} x0 - 128-bit input block vector
3755 * @param {number} x1 - 128-bit input block vector
3756 * @param {number} x2 - 128-bit input block vector
3757 * @param {number} x3 - 128-bit input block vector
3758 */
3759 function _cfb_enc(x0, x1, x2, x3) {
3760 x0 = x0 | 0;
3761 x1 = x1 | 0;
3762 x2 = x2 | 0;
3763 x3 = x3 | 0;
3764
3765 _core(
3766 0x0000, 0x0800, 0x1000,
3767 R,
3768 I0,
3769 I1,
3770 I2,
3771 I3
3772 );
3773
3774 I0 = S0 = S0 ^ x0,
3775 I1 = S1 = S1 ^ x1,
3776 I2 = S2 = S2 ^ x2,
3777 I3 = S3 = S3 ^ x3;
3778 }
3779
3780
3781 /**
3782 * CFB mode decryption
3783 * @param {number} x0 - 128-bit input block vector
3784 * @param {number} x1 - 128-bit input block vector
3785 * @param {number} x2 - 128-bit input block vector
3786 * @param {number} x3 - 128-bit input block vector
3787 */
3788 function _cfb_dec(x0, x1, x2, x3) {
3789 x0 = x0 | 0;
3790 x1 = x1 | 0;
3791 x2 = x2 | 0;
3792 x3 = x3 | 0;
3793
3794 _core(
3795 0x0000, 0x0800, 0x1000,
3796 R,
3797 I0,
3798 I1,
3799 I2,
3800 I3
3801 );
3802
3803 S0 = S0 ^ x0,
3804 S1 = S1 ^ x1,
3805 S2 = S2 ^ x2,
3806 S3 = S3 ^ x3;
3807
3808 I0 = x0,
3809 I1 = x1,
3810 I2 = x2,
3811 I3 = x3;
3812 }
3813
3814 /**
3815 * OFB mode encryption / decryption
3816 * @param {number} x0 - 128-bit input block vector
3817 * @param {number} x1 - 128-bit input block vector
3818 * @param {number} x2 - 128-bit input block vector
3819 * @param {number} x3 - 128-bit input block vector
3820 */
3821 function _ofb(x0, x1, x2, x3) {
3822 x0 = x0 | 0;
3823 x1 = x1 | 0;
3824 x2 = x2 | 0;
3825 x3 = x3 | 0;
3826
3827 _core(
3828 0x0000, 0x0800, 0x1000,
3829 R,
3830 I0,
3831 I1,
3832 I2,
3833 I3
3834 );
3835
3836 I0 = S0,
3837 I1 = S1,
3838 I2 = S2,
3839 I3 = S3;
3840
3841 S0 = S0 ^ x0,
3842 S1 = S1 ^ x1,
3843 S2 = S2 ^ x2,
3844 S3 = S3 ^ x3;
3845 }
3846
3847 /**
3848 * CTR mode encryption / decryption
3849 * @param {number} x0 - 128-bit input block vector
3850 * @param {number} x1 - 128-bit input block vector
3851 * @param {number} x2 - 128-bit input block vector
3852 * @param {number} x3 - 128-bit input block vector
3853 */
3854 function _ctr(x0, x1, x2, x3) {
3855 x0 = x0 | 0;
3856 x1 = x1 | 0;
3857 x2 = x2 | 0;
3858 x3 = x3 | 0;
3859
3860 _core(
3861 0x0000, 0x0800, 0x1000,
3862 R,
3863 N0,
3864 N1,
3865 N2,
3866 N3
3867 );
3868
3869 N3 = (~M3 & N3) | M3 & (N3 + 1);
3870 N2 = (~M2 & N2) | M2 & (N2 + ((N3 | 0) == 0));
3871 N1 = (~M1 & N1) | M1 & (N1 + ((N2 | 0) == 0));
3872 N0 = (~M0 & N0) | M0 & (N0 + ((N1 | 0) == 0));
3873
3874 S0 = S0 ^ x0;
3875 S1 = S1 ^ x1;
3876 S2 = S2 ^ x2;
3877 S3 = S3 ^ x3;
3878 }
3879
3880 /**
3881 * GCM mode MAC calculation
3882 * @param {number} x0 - 128-bit input block vector
3883 * @param {number} x1 - 128-bit input block vector
3884 * @param {number} x2 - 128-bit input block vector
3885 * @param {number} x3 - 128-bit input block vector
3886 */
3887 function _gcm_mac(x0, x1, x2, x3) {
3888 x0 = x0 | 0;
3889 x1 = x1 | 0;
3890 x2 = x2 | 0;
3891 x3 = x3 | 0;
3892
3893 var y0 = 0, y1 = 0, y2 = 0, y3 = 0,
3894 z0 = 0, z1 = 0, z2 = 0, z3 = 0,
3895 i = 0, c = 0;
3896
3897 x0 = x0 ^ I0,
3898 x1 = x1 ^ I1,
3899 x2 = x2 ^ I2,
3900 x3 = x3 ^ I3;
3901
3902 y0 = H0 | 0,
3903 y1 = H1 | 0,
3904 y2 = H2 | 0,
3905 y3 = H3 | 0;
3906
3907 for (; (i | 0) < 128; i = (i + 1) | 0) {
3908 if (y0 >>> 31) {
3909 z0 = z0 ^ x0,
3910 z1 = z1 ^ x1,
3911 z2 = z2 ^ x2,
3912 z3 = z3 ^ x3;
3913 }
3914
3915 y0 = (y0 << 1) | (y1 >>> 31),
3916 y1 = (y1 << 1) | (y2 >>> 31),
3917 y2 = (y2 << 1) | (y3 >>> 31),
3918 y3 = (y3 << 1);
3919
3920 c = x3 & 1;
3921
3922 x3 = (x3 >>> 1) | (x2 << 31),
3923 x2 = (x2 >>> 1) | (x1 << 31),
3924 x1 = (x1 >>> 1) | (x0 << 31),
3925 x0 = (x0 >>> 1);
3926
3927 if (c) x0 = x0 ^ 0xe1000000;
3928 }
3929
3930 I0 = z0,
3931 I1 = z1,
3932 I2 = z2,
3933 I3 = z3;
3934 }
3935
3936 /**
3937 * Set the internal rounds number.
3938 * @instance
3939 * @memberof AES_asm
3940 * @param {number} r - number if inner AES rounds
3941 */
3942 function set_rounds(r) {
3943 r = r | 0;
3944 R = r;
3945 }
3946
3947 /**
3948 * Populate the internal state of the module.
3949 * @instance
3950 * @memberof AES_asm
3951 * @param {number} s0 - state vector
3952 * @param {number} s1 - state vector
3953 * @param {number} s2 - state vector
3954 * @param {number} s3 - state vector
3955 */
3956 function set_state(s0, s1, s2, s3) {
3957 s0 = s0 | 0;
3958 s1 = s1 | 0;
3959 s2 = s2 | 0;
3960 s3 = s3 | 0;
3961
3962 S0 = s0,
3963 S1 = s1,
3964 S2 = s2,
3965 S3 = s3;
3966 }
3967
3968 /**
3969 * Populate the internal iv of the module.
3970 * @instance
3971 * @memberof AES_asm
3972 * @param {number} i0 - iv vector
3973 * @param {number} i1 - iv vector
3974 * @param {number} i2 - iv vector
3975 * @param {number} i3 - iv vector
3976 */
3977 function set_iv(i0, i1, i2, i3) {
3978 i0 = i0 | 0;
3979 i1 = i1 | 0;
3980 i2 = i2 | 0;
3981 i3 = i3 | 0;
3982
3983 I0 = i0,
3984 I1 = i1,
3985 I2 = i2,
3986 I3 = i3;
3987 }
3988
3989 /**
3990 * Set nonce for CTR-family modes.
3991 * @instance
3992 * @memberof AES_asm
3993 * @param {number} n0 - nonce vector
3994 * @param {number} n1 - nonce vector
3995 * @param {number} n2 - nonce vector
3996 * @param {number} n3 - nonce vector
3997 */
3998 function set_nonce(n0, n1, n2, n3) {
3999 n0 = n0 | 0;
4000 n1 = n1 | 0;
4001 n2 = n2 | 0;
4002 n3 = n3 | 0;
4003
4004 N0 = n0,
4005 N1 = n1,
4006 N2 = n2,
4007 N3 = n3;
4008 }
4009
4010 /**
4011 * Set counter mask for CTR-family modes.
4012 * @instance
4013 * @memberof AES_asm
4014 * @param {number} m0 - counter mask vector
4015 * @param {number} m1 - counter mask vector
4016 * @param {number} m2 - counter mask vector
4017 * @param {number} m3 - counter mask vector
4018 */
4019 function set_mask(m0, m1, m2, m3) {
4020 m0 = m0 | 0;
4021 m1 = m1 | 0;
4022 m2 = m2 | 0;
4023 m3 = m3 | 0;
4024
4025 M0 = m0,
4026 M1 = m1,
4027 M2 = m2,
4028 M3 = m3;
4029 }
4030
4031 /**
4032 * Set counter for CTR-family modes.
4033 * @instance
4034 * @memberof AES_asm
4035 * @param {number} c0 - counter vector
4036 * @param {number} c1 - counter vector
4037 * @param {number} c2 - counter vector
4038 * @param {number} c3 - counter vector
4039 */
4040 function set_counter(c0, c1, c2, c3) {
4041 c0 = c0 | 0;
4042 c1 = c1 | 0;
4043 c2 = c2 | 0;
4044 c3 = c3 | 0;
4045
4046 N3 = (~M3 & N3) | M3 & c3,
4047 N2 = (~M2 & N2) | M2 & c2,
4048 N1 = (~M1 & N1) | M1 & c1,
4049 N0 = (~M0 & N0) | M0 & c0;
4050 }
4051
4052 /**
4053 * Store the internal state vector into the heap.
4054 * @instance
4055 * @memberof AES_asm
4056 * @param {number} pos - offset where to put the data
4057 * @return {number} The number of bytes have been written into the heap, always 16.
4058 */
4059 function get_state(pos) {
4060 pos = pos | 0;
4061
4062 if (pos & 15) return -1;
4063
4064 DATA[pos | 0] = S0 >>> 24,
4065 DATA[pos | 1] = S0 >>> 16 & 255,
4066 DATA[pos | 2] = S0 >>> 8 & 255,
4067 DATA[pos | 3] = S0 & 255,
4068 DATA[pos | 4] = S1 >>> 24,
4069 DATA[pos | 5] = S1 >>> 16 & 255,
4070 DATA[pos | 6] = S1 >>> 8 & 255,
4071 DATA[pos | 7] = S1 & 255,
4072 DATA[pos | 8] = S2 >>> 24,
4073 DATA[pos | 9] = S2 >>> 16 & 255,
4074 DATA[pos | 10] = S2 >>> 8 & 255,
4075 DATA[pos | 11] = S2 & 255,
4076 DATA[pos | 12] = S3 >>> 24,
4077 DATA[pos | 13] = S3 >>> 16 & 255,
4078 DATA[pos | 14] = S3 >>> 8 & 255,
4079 DATA[pos | 15] = S3 & 255;
4080
4081 return 16;
4082 }
4083
4084 /**
4085 * Store the internal iv vector into the heap.
4086 * @instance
4087 * @memberof AES_asm
4088 * @param {number} pos - offset where to put the data
4089 * @return {number} The number of bytes have been written into the heap, always 16.
4090 */
4091 function get_iv(pos) {
4092 pos = pos | 0;
4093
4094 if (pos & 15) return -1;
4095
4096 DATA[pos | 0] = I0 >>> 24,
4097 DATA[pos | 1] = I0 >>> 16 & 255,
4098 DATA[pos | 2] = I0 >>> 8 & 255,
4099 DATA[pos | 3] = I0 & 255,
4100 DATA[pos | 4] = I1 >>> 24,
4101 DATA[pos | 5] = I1 >>> 16 & 255,
4102 DATA[pos | 6] = I1 >>> 8 & 255,
4103 DATA[pos | 7] = I1 & 255,
4104 DATA[pos | 8] = I2 >>> 24,
4105 DATA[pos | 9] = I2 >>> 16 & 255,
4106 DATA[pos | 10] = I2 >>> 8 & 255,
4107 DATA[pos | 11] = I2 & 255,
4108 DATA[pos | 12] = I3 >>> 24,
4109 DATA[pos | 13] = I3 >>> 16 & 255,
4110 DATA[pos | 14] = I3 >>> 8 & 255,
4111 DATA[pos | 15] = I3 & 255;
4112
4113 return 16;
4114 }
4115
4116 /**
4117 * GCM initialization.
4118 * @instance
4119 * @memberof AES_asm
4120 */
4121 function gcm_init() {
4122 _ecb_enc(0, 0, 0, 0);
4123 H0 = S0,
4124 H1 = S1,
4125 H2 = S2,
4126 H3 = S3;
4127 }
4128
4129 /**
4130 * Perform ciphering operation on the supplied data.
4131 * @instance
4132 * @memberof AES_asm
4133 * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)
4134 * @param {number} pos - offset of the data being processed
4135 * @param {number} len - length of the data being processed
4136 * @return {number} Actual amount of data have been processed.
4137 */
4138 function cipher(mode, pos, len) {
4139 mode = mode | 0;
4140 pos = pos | 0;
4141 len = len | 0;
4142
4143 var ret = 0;
4144
4145 if (pos & 15) return -1;
4146
4147 while ((len | 0) >= 16) {
4148 _cipher_modes[mode & 7](
4149 DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],
4150 DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],
4151 DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],
4152 DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]
4153 );
4154
4155 DATA[pos | 0] = S0 >>> 24,
4156 DATA[pos | 1] = S0 >>> 16 & 255,
4157 DATA[pos | 2] = S0 >>> 8 & 255,
4158 DATA[pos | 3] = S0 & 255,
4159 DATA[pos | 4] = S1 >>> 24,
4160 DATA[pos | 5] = S1 >>> 16 & 255,
4161 DATA[pos | 6] = S1 >>> 8 & 255,
4162 DATA[pos | 7] = S1 & 255,
4163 DATA[pos | 8] = S2 >>> 24,
4164 DATA[pos | 9] = S2 >>> 16 & 255,
4165 DATA[pos | 10] = S2 >>> 8 & 255,
4166 DATA[pos | 11] = S2 & 255,
4167 DATA[pos | 12] = S3 >>> 24,
4168 DATA[pos | 13] = S3 >>> 16 & 255,
4169 DATA[pos | 14] = S3 >>> 8 & 255,
4170 DATA[pos | 15] = S3 & 255;
4171
4172 ret = (ret + 16) | 0,
4173 pos = (pos + 16) | 0,
4174 len = (len - 16) | 0;
4175 }
4176
4177 return ret | 0;
4178 }
4179
4180 /**
4181 * Calculates MAC of the supplied data.
4182 * @instance
4183 * @memberof AES_asm
4184 * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)
4185 * @param {number} pos - offset of the data being processed
4186 * @param {number} len - length of the data being processed
4187 * @return {number} Actual amount of data have been processed.
4188 */
4189 function mac(mode, pos, len) {
4190 mode = mode | 0;
4191 pos = pos | 0;
4192 len = len | 0;
4193
4194 var ret = 0;
4195
4196 if (pos & 15) return -1;
4197
4198 while ((len | 0) >= 16) {
4199 _mac_modes[mode & 1](
4200 DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3],
4201 DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7],
4202 DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11],
4203 DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]
4204 );
4205
4206 ret = (ret + 16) | 0,
4207 pos = (pos + 16) | 0,
4208 len = (len - 16) | 0;
4209 }
4210
4211 return ret | 0;
4212 }
4213
4214 /**
4215 * AES cipher modes table (virual methods)
4216 */
4217 var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr];
4218
4219 /**
4220 * AES MAC modes table (virual methods)
4221 */
4222 var _mac_modes = [_cbc_enc, _gcm_mac];
4223
4224 /**
4225 * Asm.js module exports
4226 */
4227 return {
4228 set_rounds: set_rounds,
4229 set_state: set_state,
4230 set_iv: set_iv,
4231 set_nonce: set_nonce,
4232 set_mask: set_mask,
4233 set_counter: set_counter,
4234 get_state: get_state,
4235 get_iv: get_iv,
4236 gcm_init: gcm_init,
4237 cipher: cipher,
4238 mac: mac,
4239 };
4240 }(stdlib, foreign, buffer);
4241
4242 asm.set_key = set_key;
4243
4244 return asm;
4245 };
4246
4247 /**
4248 * AES enciphering mode constants
4249 * @enum {number}
4250 * @const
4251 */
4252 wrapper.ENC = {
4253 ECB: 0,
4254 CBC: 2,
4255 CFB: 4,
4256 OFB: 6,
4257 CTR: 7,
4258 },
4259
4260 /**
4261 * AES deciphering mode constants
4262 * @enum {number}
4263 * @const
4264 */
4265 wrapper.DEC = {
4266 ECB: 1,
4267 CBC: 3,
4268 CFB: 5,
4269 OFB: 6,
4270 CTR: 7,
4271 },
4272
4273 /**
4274 * AES MAC mode constants
4275 * @enum {number}
4276 * @const
4277 */
4278 wrapper.MAC = {
4279 CBC: 0,
4280 GCM: 1,
4281 };
4282
4283 /**
4284 * Heap data offset
4285 * @type {number}
4286 * @const
4287 */
4288 wrapper.HEAP_DATA = 0x4000;
4289
4290 return wrapper;
4291 }();
4292
4293 function is_bytes(a) {
4294 return a instanceof Uint8Array;
4295 }
4296 function _heap_init(heap, heapSize) {
4297 const size = heap ? heap.byteLength : heapSize || 65536;
4298 if (size & 0xfff || size <= 0)
4299 throw new Error('heap size must be a positive integer and a multiple of 4096');
4300 heap = heap || new Uint8Array(new ArrayBuffer(size));
4301 return heap;
4302 }
4303 function _heap_write(heap, hpos, data, dpos, dlen) {
4304 const hlen = heap.length - hpos;
4305 const wlen = hlen < dlen ? hlen : dlen;
4306 heap.set(data.subarray(dpos, dpos + wlen), hpos);
4307 return wlen;
4308 }
4309 function joinBytes(...arg) {
4310 const totalLenght = arg.reduce((sum, curr) => sum + curr.length, 0);
4311 const ret = new Uint8Array(totalLenght);
4312 let cursor = 0;
4313 for (let i = 0; i < arg.length; i++) {
4314 ret.set(arg[i], cursor);
4315 cursor += arg[i].length;
4316 }
4317 return ret;
4318 }
4319
4320 class IllegalStateError extends Error {
4321 constructor(...args) {
4322 super(...args);
4323 }
4324 }
4325 class IllegalArgumentError extends Error {
4326 constructor(...args) {
4327 super(...args);
4328 }
4329 }
4330 class SecurityError extends Error {
4331 constructor(...args) {
4332 super(...args);
4333 }
4334 }
4335
4336 const heap_pool = [];
4337 const asm_pool = [];
4338 class AES {
4339 constructor(key, iv, padding = true, mode, heap, asm) {
4340 this.pos = 0;
4341 this.len = 0;
4342 this.mode = mode;
4343 // The AES object state
4344 this.pos = 0;
4345 this.len = 0;
4346 this.key = key;
4347 this.iv = iv;
4348 this.padding = padding;
4349 // The AES "worker"
4350 this.acquire_asm(heap, asm);
4351 }
4352 acquire_asm(heap, asm) {
4353 if (this.heap === undefined || this.asm === undefined) {
4354 this.heap = heap || heap_pool.pop() || _heap_init().subarray(AES_asm.HEAP_DATA);
4355 this.asm = asm || asm_pool.pop() || new AES_asm(null, this.heap.buffer);
4356 this.reset(this.key, this.iv);
4357 }
4358 return { heap: this.heap, asm: this.asm };
4359 }
4360 release_asm() {
4361 if (this.heap !== undefined && this.asm !== undefined) {
4362 heap_pool.push(this.heap);
4363 asm_pool.push(this.asm);
4364 }
4365 this.heap = undefined;
4366 this.asm = undefined;
4367 }
4368 reset(key, iv) {
4369 const { asm } = this.acquire_asm();
4370 // Key
4371 const keylen = key.length;
4372 if (keylen !== 16 && keylen !== 24 && keylen !== 32)
4373 throw new IllegalArgumentError('illegal key size');
4374 const keyview = new DataView(key.buffer, key.byteOffset, key.byteLength);
4375 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);
4376 // IV
4377 if (iv !== undefined) {
4378 if (iv.length !== 16)
4379 throw new IllegalArgumentError('illegal iv size');
4380 let ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);
4381 asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12));
4382 }
4383 else {
4384 asm.set_iv(0, 0, 0, 0);
4385 }
4386 }
4387 AES_Encrypt_process(data) {
4388 if (!is_bytes(data))
4389 throw new TypeError("data isn't of expected type");
4390 let { heap, asm } = this.acquire_asm();
4391 let amode = AES_asm.ENC[this.mode];
4392 let hpos = AES_asm.HEAP_DATA;
4393 let pos = this.pos;
4394 let len = this.len;
4395 let dpos = 0;
4396 let dlen = data.length || 0;
4397 let rpos = 0;
4398 let rlen = (len + dlen) & -16;
4399 let wlen = 0;
4400 let result = new Uint8Array(rlen);
4401 while (dlen > 0) {
4402 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
4403 len += wlen;
4404 dpos += wlen;
4405 dlen -= wlen;
4406 wlen = asm.cipher(amode, hpos + pos, len);
4407 if (wlen)
4408 result.set(heap.subarray(pos, pos + wlen), rpos);
4409 rpos += wlen;
4410 if (wlen < len) {
4411 pos += wlen;
4412 len -= wlen;
4413 }
4414 else {
4415 pos = 0;
4416 len = 0;
4417 }
4418 }
4419 this.pos = pos;
4420 this.len = len;
4421 return result;
4422 }
4423 AES_Encrypt_finish() {
4424 let { heap, asm } = this.acquire_asm();
4425 let amode = AES_asm.ENC[this.mode];
4426 let hpos = AES_asm.HEAP_DATA;
4427 let pos = this.pos;
4428 let len = this.len;
4429 let plen = 16 - (len % 16);
4430 let rlen = len;
4431 if (this.hasOwnProperty('padding')) {
4432 if (this.padding) {
4433 for (let p = 0; p < plen; ++p) {
4434 heap[pos + len + p] = plen;
4435 }
4436 len += plen;
4437 rlen = len;
4438 }
4439 else if (len % 16) {
4440 throw new IllegalArgumentError('data length must be a multiple of the block size');
4441 }
4442 }
4443 else {
4444 len += plen;
4445 }
4446 const result = new Uint8Array(rlen);
4447 if (len)
4448 asm.cipher(amode, hpos + pos, len);
4449 if (rlen)
4450 result.set(heap.subarray(pos, pos + rlen));
4451 this.pos = 0;
4452 this.len = 0;
4453 this.release_asm();
4454 return result;
4455 }
4456 AES_Decrypt_process(data) {
4457 if (!is_bytes(data))
4458 throw new TypeError("data isn't of expected type");
4459 let { heap, asm } = this.acquire_asm();
4460 let amode = AES_asm.DEC[this.mode];
4461 let hpos = AES_asm.HEAP_DATA;
4462 let pos = this.pos;
4463 let len = this.len;
4464 let dpos = 0;
4465 let dlen = data.length || 0;
4466 let rpos = 0;
4467 let rlen = (len + dlen) & -16;
4468 let plen = 0;
4469 let wlen = 0;
4470 if (this.padding) {
4471 plen = len + dlen - rlen || 16;
4472 rlen -= plen;
4473 }
4474 const result = new Uint8Array(rlen);
4475 while (dlen > 0) {
4476 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
4477 len += wlen;
4478 dpos += wlen;
4479 dlen -= wlen;
4480 wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0));
4481 if (wlen)
4482 result.set(heap.subarray(pos, pos + wlen), rpos);
4483 rpos += wlen;
4484 if (wlen < len) {
4485 pos += wlen;
4486 len -= wlen;
4487 }
4488 else {
4489 pos = 0;
4490 len = 0;
4491 }
4492 }
4493 this.pos = pos;
4494 this.len = len;
4495 return result;
4496 }
4497 AES_Decrypt_finish() {
4498 let { heap, asm } = this.acquire_asm();
4499 let amode = AES_asm.DEC[this.mode];
4500 let hpos = AES_asm.HEAP_DATA;
4501 let pos = this.pos;
4502 let len = this.len;
4503 let rlen = len;
4504 if (len > 0) {
4505 if (len % 16) {
4506 if (this.hasOwnProperty('padding')) {
4507 throw new IllegalArgumentError('data length must be a multiple of the block size');
4508 }
4509 else {
4510 len += 16 - (len % 16);
4511 }
4512 }
4513 asm.cipher(amode, hpos + pos, len);
4514 if (this.hasOwnProperty('padding') && this.padding) {
4515 let pad = heap[pos + rlen - 1];
4516 if (pad < 1 || pad > 16 || pad > rlen)
4517 throw new SecurityError('bad padding');
4518 let pcheck = 0;
4519 for (let i = pad; i > 1; i--)
4520 pcheck |= pad ^ heap[pos + rlen - i];
4521 if (pcheck)
4522 throw new SecurityError('bad padding');
4523 rlen -= pad;
4524 }
4525 }
4526 const result = new Uint8Array(rlen);
4527 if (rlen > 0) {
4528 result.set(heap.subarray(pos, pos + rlen));
4529 }
4530 this.pos = 0;
4531 this.len = 0;
4532 this.release_asm();
4533 return result;
4534 }
4535 }
4536
4537 class AES_ECB {
4538 static encrypt(data, key, padding = false) {
4539 return new AES_ECB(key, padding).encrypt(data);
4540 }
4541 static decrypt(data, key, padding = false) {
4542 return new AES_ECB(key, padding).decrypt(data);
4543 }
4544 constructor(key, padding = false, aes) {
4545 this.aes = aes ? aes : new AES(key, undefined, padding, 'ECB');
4546 }
4547 encrypt(data) {
4548 const r1 = this.aes.AES_Encrypt_process(data);
4549 const r2 = this.aes.AES_Encrypt_finish();
4550 return joinBytes(r1, r2);
4551 }
4552 decrypt(data) {
4553 const r1 = this.aes.AES_Decrypt_process(data);
4554 const r2 = this.aes.AES_Decrypt_finish();
4555 return joinBytes(r1, r2);
4556 }
4557 }
4558
4559 // TODO use webCrypto or nodeCrypto when possible.
4560 function aes(length) {
4561 const C = function(key) {
4562 const aesECB = new AES_ECB(key);
4563
4564 this.encrypt = function(block) {
4565 return aesECB.encrypt(block);
4566 };
4567
4568 this.decrypt = function(block) {
4569 return aesECB.decrypt(block);
4570 };
4571 };
4572
4573 C.blockSize = C.prototype.blockSize = 16;
4574 C.keySize = C.prototype.keySize = length / 8;
4575
4576 return C;
4577 }
4578
4579 //Paul Tero, July 2001
4580 //http://www.tero.co.uk/des/
4581 //
4582 //Optimised for performance with large blocks by Michael Hayworth, November 2001
4583 //http://www.netdealing.com
4584 //
4585 // Modified by Recurity Labs GmbH
4586
4587 //THIS SOFTWARE IS PROVIDED "AS IS" AND
4588 //ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4589 //IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4590 //ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
4591 //FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4592 //DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4593 //OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4594 //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4595 //LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
4596 //OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
4597 //SUCH DAMAGE.
4598
4599 //des
4600 //this takes the key, the message, and whether to encrypt or decrypt
4601
4602 function des(keys, message, encrypt, mode, iv, padding) {
4603 //declaring this locally speeds things up a bit
4604 const spfunction1 = [
4605 0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400,
4606 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000,
4607 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4,
4608 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404,
4609 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400,
4610 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004
4611 ];
4612 const spfunction2 = [
4613 -0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0,
4614 -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020,
4615 -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000,
4616 -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000,
4617 -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0,
4618 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0,
4619 -0x7fef7fe0, 0x108000
4620 ];
4621 const spfunction3 = [
4622 0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008,
4623 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000,
4624 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000,
4625 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0,
4626 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208,
4627 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200
4628 ];
4629 const spfunction4 = [
4630 0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000,
4631 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080,
4632 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0,
4633 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001,
4634 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080
4635 ];
4636 const spfunction5 = [
4637 0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000,
4638 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000,
4639 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100,
4640 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100,
4641 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100,
4642 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0,
4643 0x40080000, 0x2080100, 0x40000100
4644 ];
4645 const spfunction6 = [
4646 0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000,
4647 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010,
4648 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000,
4649 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000,
4650 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000,
4651 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010
4652 ];
4653 const spfunction7 = [
4654 0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802,
4655 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002,
4656 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000,
4657 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000,
4658 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0,
4659 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002
4660 ];
4661 const spfunction8 = [
4662 0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000,
4663 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000,
4664 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040,
4665 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040,
4666 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000,
4667 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000
4668 ];
4669
4670 //create the 16 or 48 subkeys we will need
4671 let m = 0;
4672 let i;
4673 let j;
4674 let temp;
4675 let right1;
4676 let right2;
4677 let left;
4678 let right;
4679 let looping;
4680 let cbcleft;
4681 let cbcleft2;
4682 let cbcright;
4683 let cbcright2;
4684 let endloop;
4685 let loopinc;
4686 let len = message.length;
4687
4688 //set up the loops for single and triple des
4689 const iterations = keys.length === 32 ? 3 : 9; //single or triple des
4690 if (iterations === 3) {
4691 looping = encrypt ? [0, 32, 2] : [30, -2, -2];
4692 } else {
4693 looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];
4694 }
4695
4696 //pad the message depending on the padding parameter
4697 //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt
4698 if (encrypt) {
4699 message = desAddPadding(message, padding);
4700 len = message.length;
4701 }
4702
4703 //store the result here
4704 let result = new Uint8Array(len);
4705 let k = 0;
4706
4707 if (mode === 1) { //CBC mode
4708 cbcleft = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];
4709 cbcright = (iv[m++] << 24) | (iv[m++] << 16) | (iv[m++] << 8) | iv[m++];
4710 m = 0;
4711 }
4712
4713 //loop through each 64 bit chunk of the message
4714 while (m < len) {
4715 left = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];
4716 right = (message[m++] << 24) | (message[m++] << 16) | (message[m++] << 8) | message[m++];
4717
4718 //for Cipher Block Chaining mode, xor the message with the previous result
4719 if (mode === 1) {
4720 if (encrypt) {
4721 left ^= cbcleft;
4722 right ^= cbcright;
4723 } else {
4724 cbcleft2 = cbcleft;
4725 cbcright2 = cbcright;
4726 cbcleft = left;
4727 cbcright = right;
4728 }
4729 }
4730
4731 //first each 64 but chunk of the message must be permuted according to IP
4732 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
4733 right ^= temp;
4734 left ^= (temp << 4);
4735 temp = ((left >>> 16) ^ right) & 0x0000ffff;
4736 right ^= temp;
4737 left ^= (temp << 16);
4738 temp = ((right >>> 2) ^ left) & 0x33333333;
4739 left ^= temp;
4740 right ^= (temp << 2);
4741 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
4742 left ^= temp;
4743 right ^= (temp << 8);
4744 temp = ((left >>> 1) ^ right) & 0x55555555;
4745 right ^= temp;
4746 left ^= (temp << 1);
4747
4748 left = ((left << 1) | (left >>> 31));
4749 right = ((right << 1) | (right >>> 31));
4750
4751 //do this either 1 or 3 times for each chunk of the message
4752 for (j = 0; j < iterations; j += 3) {
4753 endloop = looping[j + 1];
4754 loopinc = looping[j + 2];
4755 //now go through and perform the encryption or decryption
4756 for (i = looping[j]; i !== endloop; i += loopinc) { //for efficiency
4757 right1 = right ^ keys[i];
4758 right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];
4759 //the result is attained by passing these bytes through the S selection functions
4760 temp = left;
4761 left = right;
4762 right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>>
4763 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) &
4764 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);
4765 }
4766 temp = left;
4767 left = right;
4768 right = temp; //unreverse left and right
4769 } //for either 1 or 3 iterations
4770
4771 //move then each one bit to the right
4772 left = ((left >>> 1) | (left << 31));
4773 right = ((right >>> 1) | (right << 31));
4774
4775 //now perform IP-1, which is IP in the opposite direction
4776 temp = ((left >>> 1) ^ right) & 0x55555555;
4777 right ^= temp;
4778 left ^= (temp << 1);
4779 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
4780 left ^= temp;
4781 right ^= (temp << 8);
4782 temp = ((right >>> 2) ^ left) & 0x33333333;
4783 left ^= temp;
4784 right ^= (temp << 2);
4785 temp = ((left >>> 16) ^ right) & 0x0000ffff;
4786 right ^= temp;
4787 left ^= (temp << 16);
4788 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
4789 right ^= temp;
4790 left ^= (temp << 4);
4791
4792 //for Cipher Block Chaining mode, xor the message with the previous result
4793 if (mode === 1) {
4794 if (encrypt) {
4795 cbcleft = left;
4796 cbcright = right;
4797 } else {
4798 left ^= cbcleft2;
4799 right ^= cbcright2;
4800 }
4801 }
4802
4803 result[k++] = (left >>> 24);
4804 result[k++] = ((left >>> 16) & 0xff);
4805 result[k++] = ((left >>> 8) & 0xff);
4806 result[k++] = (left & 0xff);
4807 result[k++] = (right >>> 24);
4808 result[k++] = ((right >>> 16) & 0xff);
4809 result[k++] = ((right >>> 8) & 0xff);
4810 result[k++] = (right & 0xff);
4811 } //for every 8 characters, or 64 bits in the message
4812
4813 //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt
4814 if (!encrypt) {
4815 result = desRemovePadding(result, padding);
4816 }
4817
4818 return result;
4819 } //end of des
4820
4821
4822 //desCreateKeys
4823 //this takes as input a 64 bit key (even though only 56 bits are used)
4824 //as an array of 2 integers, and returns 16 48 bit keys
4825
4826 function desCreateKeys(key) {
4827 //declaring this locally speeds things up a bit
4828 const pc2bytes0 = [
4829 0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204,
4830 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204
4831 ];
4832 const pc2bytes1 = [
4833 0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100,
4834 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101
4835 ];
4836 const pc2bytes2 = [
4837 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808,
4838 0x1000000, 0x1000008, 0x1000800, 0x1000808
4839 ];
4840 const pc2bytes3 = [
4841 0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000,
4842 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000
4843 ];
4844 const pc2bytes4 = [
4845 0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000,
4846 0x41000, 0x1010, 0x41010
4847 ];
4848 const pc2bytes5 = [
4849 0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420,
4850 0x2000000, 0x2000400, 0x2000020, 0x2000420
4851 ];
4852 const pc2bytes6 = [
4853 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000,
4854 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002
4855 ];
4856 const pc2bytes7 = [
4857 0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000,
4858 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800
4859 ];
4860 const pc2bytes8 = [
4861 0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000,
4862 0x2000002, 0x2040002, 0x2000002, 0x2040002
4863 ];
4864 const pc2bytes9 = [
4865 0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408,
4866 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408
4867 ];
4868 const pc2bytes10 = [
4869 0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020,
4870 0x102000, 0x102020, 0x102000, 0x102020
4871 ];
4872 const pc2bytes11 = [
4873 0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000,
4874 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200
4875 ];
4876 const pc2bytes12 = [
4877 0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010,
4878 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010
4879 ];
4880 const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];
4881
4882 //how many iterations (1 for des, 3 for triple des)
4883 const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys
4884 //stores the return keys
4885 const keys = new Array(32 * iterations);
4886 //now define the left shifts which need to be done
4887 const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];
4888 //other variables
4889 let lefttemp;
4890 let righttemp;
4891 let m = 0;
4892 let n = 0;
4893 let temp;
4894
4895 for (let j = 0; j < iterations; j++) { //either 1 or 3 iterations
4896 let left = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];
4897 let right = (key[m++] << 24) | (key[m++] << 16) | (key[m++] << 8) | key[m++];
4898
4899 temp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
4900 right ^= temp;
4901 left ^= (temp << 4);
4902 temp = ((right >>> -16) ^ left) & 0x0000ffff;
4903 left ^= temp;
4904 right ^= (temp << -16);
4905 temp = ((left >>> 2) ^ right) & 0x33333333;
4906 right ^= temp;
4907 left ^= (temp << 2);
4908 temp = ((right >>> -16) ^ left) & 0x0000ffff;
4909 left ^= temp;
4910 right ^= (temp << -16);
4911 temp = ((left >>> 1) ^ right) & 0x55555555;
4912 right ^= temp;
4913 left ^= (temp << 1);
4914 temp = ((right >>> 8) ^ left) & 0x00ff00ff;
4915 left ^= temp;
4916 right ^= (temp << 8);
4917 temp = ((left >>> 1) ^ right) & 0x55555555;
4918 right ^= temp;
4919 left ^= (temp << 1);
4920
4921 //the right side needs to be shifted and to get the last four bits of the left side
4922 temp = (left << 8) | ((right >>> 20) & 0x000000f0);
4923 //left needs to be put upside down
4924 left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);
4925 right = temp;
4926
4927 //now go through and perform these shifts on the left and right keys
4928 for (let i = 0; i < shifts.length; i++) {
4929 //shift the keys either one or two bits to the left
4930 if (shifts[i]) {
4931 left = (left << 2) | (left >>> 26);
4932 right = (right << 2) | (right >>> 26);
4933 } else {
4934 left = (left << 1) | (left >>> 27);
4935 right = (right << 1) | (right >>> 27);
4936 }
4937 left &= -0xf;
4938 right &= -0xf;
4939
4940 //now apply PC-2, in such a way that E is easier when encrypting or decrypting
4941 //this conversion will look like PC-2 except only the last 6 bits of each byte are used
4942 //rather than 48 consecutive bits and the order of lines will be according to
4943 //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7
4944 lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(
4945 left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) &
4946 0xf];
4947 righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] |
4948 pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |
4949 pc2bytes13[(right >>> 4) & 0xf];
4950 temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;
4951 keys[n++] = lefttemp ^ temp;
4952 keys[n++] = righttemp ^ (temp << 16);
4953 }
4954 } //for each iterations
4955 //return the keys we've created
4956 return keys;
4957 } //end of desCreateKeys
4958
4959
4960 function desAddPadding(message, padding) {
4961 const padLength = 8 - (message.length % 8);
4962
4963 let pad;
4964 if (padding === 2 && (padLength < 8)) { //pad the message with spaces
4965 pad = ' '.charCodeAt(0);
4966 } else if (padding === 1) { //PKCS7 padding
4967 pad = padLength;
4968 } else if (!padding && (padLength < 8)) { //pad the message out with null bytes
4969 pad = 0;
4970 } else if (padLength === 8) {
4971 return message;
4972 } else {
4973 throw new Error('des: invalid padding');
4974 }
4975
4976 const paddedMessage = new Uint8Array(message.length + padLength);
4977 for (let i = 0; i < message.length; i++) {
4978 paddedMessage[i] = message[i];
4979 }
4980 for (let j = 0; j < padLength; j++) {
4981 paddedMessage[message.length + j] = pad;
4982 }
4983
4984 return paddedMessage;
4985 }
4986
4987 function desRemovePadding(message, padding) {
4988 let padLength = null;
4989 let pad;
4990 if (padding === 2) { // space padded
4991 pad = ' '.charCodeAt(0);
4992 } else if (padding === 1) { // PKCS7
4993 padLength = message[message.length - 1];
4994 } else if (!padding) { // null padding
4995 pad = 0;
4996 } else {
4997 throw new Error('des: invalid padding');
4998 }
4999
5000 if (!padLength) {
5001 padLength = 1;
5002 while (message[message.length - padLength] === pad) {
5003 padLength++;
5004 }
5005 padLength--;
5006 }
5007
5008 return message.subarray(0, message.length - padLength);
5009 }
5010
5011 // added by Recurity Labs
5012
5013 function TripleDES(key) {
5014 this.key = [];
5015
5016 for (let i = 0; i < 3; i++) {
5017 this.key.push(new Uint8Array(key.subarray(i * 8, (i * 8) + 8)));
5018 }
5019
5020 this.encrypt = function(block) {
5021 return des(
5022 desCreateKeys(this.key[2]),
5023 des(
5024 desCreateKeys(this.key[1]),
5025 des(
5026 desCreateKeys(this.key[0]),
5027 block, true, 0, null, null
5028 ),
5029 false, 0, null, null
5030 ), true, 0, null, null
5031 );
5032 };
5033 }
5034
5035 TripleDES.keySize = TripleDES.prototype.keySize = 24;
5036 TripleDES.blockSize = TripleDES.prototype.blockSize = 8;
5037
5038 // This is "original" DES
5039
5040 function DES(key) {
5041 this.key = key;
5042
5043 this.encrypt = function(block, padding) {
5044 const keys = desCreateKeys(this.key);
5045 return des(keys, block, true, 0, null, padding);
5046 };
5047
5048 this.decrypt = function(block, padding) {
5049 const keys = desCreateKeys(this.key);
5050 return des(keys, block, false, 0, null, padding);
5051 };
5052 }
5053
5054 // Use of this source code is governed by a BSD-style
5055 // license that can be found in the LICENSE file.
5056
5057 // Copyright 2010 pjacobs@xeekr.com . All rights reserved.
5058
5059 // Modified by Recurity Labs GmbH
5060
5061 // fixed/modified by Herbert Hanewinkel, www.haneWIN.de
5062 // check www.haneWIN.de for the latest version
5063
5064 // cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.
5065 // CAST-128 is a common OpenPGP cipher.
5066
5067
5068 // CAST5 constructor
5069
5070 function OpenPGPSymEncCAST5() {
5071 this.BlockSize = 8;
5072 this.KeySize = 16;
5073
5074 this.setKey = function(key) {
5075 this.masking = new Array(16);
5076 this.rotate = new Array(16);
5077
5078 this.reset();
5079
5080 if (key.length === this.KeySize) {
5081 this.keySchedule(key);
5082 } else {
5083 throw new Error('CAST-128: keys must be 16 bytes');
5084 }
5085 return true;
5086 };
5087
5088 this.reset = function() {
5089 for (let i = 0; i < 16; i++) {
5090 this.masking[i] = 0;
5091 this.rotate[i] = 0;
5092 }
5093 };
5094
5095 this.getBlockSize = function() {
5096 return this.BlockSize;
5097 };
5098
5099 this.encrypt = function(src) {
5100 const dst = new Array(src.length);
5101
5102 for (let i = 0; i < src.length; i += 8) {
5103 let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];
5104 let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];
5105 let t;
5106
5107 t = r;
5108 r = l ^ f1(r, this.masking[0], this.rotate[0]);
5109 l = t;
5110 t = r;
5111 r = l ^ f2(r, this.masking[1], this.rotate[1]);
5112 l = t;
5113 t = r;
5114 r = l ^ f3(r, this.masking[2], this.rotate[2]);
5115 l = t;
5116 t = r;
5117 r = l ^ f1(r, this.masking[3], this.rotate[3]);
5118 l = t;
5119
5120 t = r;
5121 r = l ^ f2(r, this.masking[4], this.rotate[4]);
5122 l = t;
5123 t = r;
5124 r = l ^ f3(r, this.masking[5], this.rotate[5]);
5125 l = t;
5126 t = r;
5127 r = l ^ f1(r, this.masking[6], this.rotate[6]);
5128 l = t;
5129 t = r;
5130 r = l ^ f2(r, this.masking[7], this.rotate[7]);
5131 l = t;
5132
5133 t = r;
5134 r = l ^ f3(r, this.masking[8], this.rotate[8]);
5135 l = t;
5136 t = r;
5137 r = l ^ f1(r, this.masking[9], this.rotate[9]);
5138 l = t;
5139 t = r;
5140 r = l ^ f2(r, this.masking[10], this.rotate[10]);
5141 l = t;
5142 t = r;
5143 r = l ^ f3(r, this.masking[11], this.rotate[11]);
5144 l = t;
5145
5146 t = r;
5147 r = l ^ f1(r, this.masking[12], this.rotate[12]);
5148 l = t;
5149 t = r;
5150 r = l ^ f2(r, this.masking[13], this.rotate[13]);
5151 l = t;
5152 t = r;
5153 r = l ^ f3(r, this.masking[14], this.rotate[14]);
5154 l = t;
5155 t = r;
5156 r = l ^ f1(r, this.masking[15], this.rotate[15]);
5157 l = t;
5158
5159 dst[i] = (r >>> 24) & 255;
5160 dst[i + 1] = (r >>> 16) & 255;
5161 dst[i + 2] = (r >>> 8) & 255;
5162 dst[i + 3] = r & 255;
5163 dst[i + 4] = (l >>> 24) & 255;
5164 dst[i + 5] = (l >>> 16) & 255;
5165 dst[i + 6] = (l >>> 8) & 255;
5166 dst[i + 7] = l & 255;
5167 }
5168
5169 return dst;
5170 };
5171
5172 this.decrypt = function(src) {
5173 const dst = new Array(src.length);
5174
5175 for (let i = 0; i < src.length; i += 8) {
5176 let l = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];
5177 let r = (src[i + 4] << 24) | (src[i + 5] << 16) | (src[i + 6] << 8) | src[i + 7];
5178 let t;
5179
5180 t = r;
5181 r = l ^ f1(r, this.masking[15], this.rotate[15]);
5182 l = t;
5183 t = r;
5184 r = l ^ f3(r, this.masking[14], this.rotate[14]);
5185 l = t;
5186 t = r;
5187 r = l ^ f2(r, this.masking[13], this.rotate[13]);
5188 l = t;
5189 t = r;
5190 r = l ^ f1(r, this.masking[12], this.rotate[12]);
5191 l = t;
5192
5193 t = r;
5194 r = l ^ f3(r, this.masking[11], this.rotate[11]);
5195 l = t;
5196 t = r;
5197 r = l ^ f2(r, this.masking[10], this.rotate[10]);
5198 l = t;
5199 t = r;
5200 r = l ^ f1(r, this.masking[9], this.rotate[9]);
5201 l = t;
5202 t = r;
5203 r = l ^ f3(r, this.masking[8], this.rotate[8]);
5204 l = t;
5205
5206 t = r;
5207 r = l ^ f2(r, this.masking[7], this.rotate[7]);
5208 l = t;
5209 t = r;
5210 r = l ^ f1(r, this.masking[6], this.rotate[6]);
5211 l = t;
5212 t = r;
5213 r = l ^ f3(r, this.masking[5], this.rotate[5]);
5214 l = t;
5215 t = r;
5216 r = l ^ f2(r, this.masking[4], this.rotate[4]);
5217 l = t;
5218
5219 t = r;
5220 r = l ^ f1(r, this.masking[3], this.rotate[3]);
5221 l = t;
5222 t = r;
5223 r = l ^ f3(r, this.masking[2], this.rotate[2]);
5224 l = t;
5225 t = r;
5226 r = l ^ f2(r, this.masking[1], this.rotate[1]);
5227 l = t;
5228 t = r;
5229 r = l ^ f1(r, this.masking[0], this.rotate[0]);
5230 l = t;
5231
5232 dst[i] = (r >>> 24) & 255;
5233 dst[i + 1] = (r >>> 16) & 255;
5234 dst[i + 2] = (r >>> 8) & 255;
5235 dst[i + 3] = r & 255;
5236 dst[i + 4] = (l >>> 24) & 255;
5237 dst[i + 5] = (l >> 16) & 255;
5238 dst[i + 6] = (l >> 8) & 255;
5239 dst[i + 7] = l & 255;
5240 }
5241
5242 return dst;
5243 };
5244 const scheduleA = new Array(4);
5245
5246 scheduleA[0] = new Array(4);
5247 scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];
5248 scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
5249 scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
5250 scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
5251
5252 scheduleA[1] = new Array(4);
5253 scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
5254 scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
5255 scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
5256 scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
5257
5258 scheduleA[2] = new Array(4);
5259 scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];
5260 scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
5261 scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
5262 scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
5263
5264
5265 scheduleA[3] = new Array(4);
5266 scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
5267 scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
5268 scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
5269 scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
5270
5271 const scheduleB = new Array(4);
5272
5273 scheduleB[0] = new Array(4);
5274 scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];
5275 scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];
5276 scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];
5277 scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];
5278
5279 scheduleB[1] = new Array(4);
5280 scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];
5281 scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];
5282 scheduleB[1][2] = [7, 6, 8, 9, 3];
5283 scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];
5284
5285
5286 scheduleB[2] = new Array(4);
5287 scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];
5288 scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];
5289 scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];
5290 scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];
5291
5292
5293 scheduleB[3] = new Array(4);
5294 scheduleB[3][0] = [8, 9, 7, 6, 3];
5295 scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];
5296 scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];
5297 scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];
5298
5299 // changed 'in' to 'inn' (in javascript 'in' is a reserved word)
5300 this.keySchedule = function(inn) {
5301 const t = new Array(8);
5302 const k = new Array(32);
5303
5304 let j;
5305
5306 for (let i = 0; i < 4; i++) {
5307 j = i * 4;
5308 t[i] = (inn[j] << 24) | (inn[j + 1] << 16) | (inn[j + 2] << 8) | inn[j + 3];
5309 }
5310
5311 const x = [6, 7, 4, 5];
5312 let ki = 0;
5313 let w;
5314
5315 for (let half = 0; half < 2; half++) {
5316 for (let round = 0; round < 4; round++) {
5317 for (j = 0; j < 4; j++) {
5318 const a = scheduleA[round][j];
5319 w = t[a[1]];
5320
5321 w ^= sBox[4][(t[a[2] >>> 2] >>> (24 - 8 * (a[2] & 3))) & 0xff];
5322 w ^= sBox[5][(t[a[3] >>> 2] >>> (24 - 8 * (a[3] & 3))) & 0xff];
5323 w ^= sBox[6][(t[a[4] >>> 2] >>> (24 - 8 * (a[4] & 3))) & 0xff];
5324 w ^= sBox[7][(t[a[5] >>> 2] >>> (24 - 8 * (a[5] & 3))) & 0xff];
5325 w ^= sBox[x[j]][(t[a[6] >>> 2] >>> (24 - 8 * (a[6] & 3))) & 0xff];
5326 t[a[0]] = w;
5327 }
5328
5329 for (j = 0; j < 4; j++) {
5330 const b = scheduleB[round][j];
5331 w = sBox[4][(t[b[0] >>> 2] >>> (24 - 8 * (b[0] & 3))) & 0xff];
5332
5333 w ^= sBox[5][(t[b[1] >>> 2] >>> (24 - 8 * (b[1] & 3))) & 0xff];
5334 w ^= sBox[6][(t[b[2] >>> 2] >>> (24 - 8 * (b[2] & 3))) & 0xff];
5335 w ^= sBox[7][(t[b[3] >>> 2] >>> (24 - 8 * (b[3] & 3))) & 0xff];
5336 w ^= sBox[4 + j][(t[b[4] >>> 2] >>> (24 - 8 * (b[4] & 3))) & 0xff];
5337 k[ki] = w;
5338 ki++;
5339 }
5340 }
5341 }
5342
5343 for (let i = 0; i < 16; i++) {
5344 this.masking[i] = k[i];
5345 this.rotate[i] = k[16 + i] & 0x1f;
5346 }
5347 };
5348
5349 // These are the three 'f' functions. See RFC 2144, section 2.2.
5350
5351 function f1(d, m, r) {
5352 const t = m + d;
5353 const I = (t << r) | (t >>> (32 - r));
5354 return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];
5355 }
5356
5357 function f2(d, m, r) {
5358 const t = m ^ d;
5359 const I = (t << r) | (t >>> (32 - r));
5360 return ((sBox[0][I >>> 24] - sBox[1][(I >>> 16) & 255]) + sBox[2][(I >>> 8) & 255]) ^ sBox[3][I & 255];
5361 }
5362
5363 function f3(d, m, r) {
5364 const t = m - d;
5365 const I = (t << r) | (t >>> (32 - r));
5366 return ((sBox[0][I >>> 24] + sBox[1][(I >>> 16) & 255]) ^ sBox[2][(I >>> 8) & 255]) - sBox[3][I & 255];
5367 }
5368
5369 const sBox = new Array(8);
5370 sBox[0] = [
5371 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,
5372 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,
5373 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,
5374 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,
5375 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,
5376 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,
5377 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,
5378 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,
5379 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,
5380 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,
5381 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,
5382 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,
5383 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,
5384 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,
5385 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,
5386 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,
5387 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,
5388 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,
5389 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,
5390 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,
5391 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,
5392 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,
5393 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,
5394 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,
5395 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,
5396 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,
5397 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,
5398 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,
5399 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,
5400 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,
5401 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,
5402 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf
5403 ];
5404
5405 sBox[1] = [
5406 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,
5407 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,
5408 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,
5409 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,
5410 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,
5411 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,
5412 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,
5413 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,
5414 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,
5415 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,
5416 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,
5417 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,
5418 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,
5419 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,
5420 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,
5421 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,
5422 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,
5423 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,
5424 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,
5425 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,
5426 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,
5427 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,
5428 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,
5429 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,
5430 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,
5431 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,
5432 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,
5433 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,
5434 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,
5435 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,
5436 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,
5437 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1
5438 ];
5439
5440 sBox[2] = [
5441 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,
5442 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,
5443 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,
5444 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,
5445 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,
5446 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,
5447 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,
5448 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,
5449 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,
5450 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,
5451 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,
5452 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,
5453 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,
5454 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,
5455 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,
5456 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,
5457 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,
5458 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,
5459 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,
5460 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,
5461 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,
5462 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,
5463 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,
5464 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,
5465 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,
5466 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,
5467 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,
5468 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,
5469 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,
5470 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,
5471 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,
5472 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783
5473 ];
5474
5475 sBox[3] = [
5476 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,
5477 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,
5478 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,
5479 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,
5480 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,
5481 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,
5482 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,
5483 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,
5484 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,
5485 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,
5486 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,
5487 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,
5488 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,
5489 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,
5490 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,
5491 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,
5492 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,
5493 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,
5494 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,
5495 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,
5496 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,
5497 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,
5498 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,
5499 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,
5500 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,
5501 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,
5502 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,
5503 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,
5504 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,
5505 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,
5506 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,
5507 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2
5508 ];
5509
5510 sBox[4] = [
5511 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,
5512 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,
5513 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,
5514 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,
5515 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,
5516 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,
5517 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,
5518 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,
5519 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,
5520 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,
5521 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,
5522 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,
5523 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,
5524 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,
5525 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,
5526 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,
5527 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,
5528 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,
5529 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,
5530 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,
5531 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,
5532 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,
5533 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,
5534 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,
5535 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,
5536 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,
5537 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,
5538 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,
5539 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,
5540 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,
5541 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,
5542 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4
5543 ];
5544
5545 sBox[5] = [
5546 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,
5547 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,
5548 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,
5549 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,
5550 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,
5551 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,
5552 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,
5553 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,
5554 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,
5555 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,
5556 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,
5557 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,
5558 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,
5559 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,
5560 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,
5561 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,
5562 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,
5563 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,
5564 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,
5565 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,
5566 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,
5567 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,
5568 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,
5569 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,
5570 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,
5571 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,
5572 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,
5573 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,
5574 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,
5575 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,
5576 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,
5577 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f
5578 ];
5579
5580 sBox[6] = [
5581 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,
5582 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,
5583 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,
5584 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,
5585 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,
5586 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,
5587 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,
5588 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,
5589 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,
5590 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,
5591 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,
5592 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,
5593 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,
5594 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,
5595 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,
5596 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,
5597 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,
5598 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,
5599 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,
5600 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,
5601 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,
5602 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,
5603 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,
5604 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,
5605 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,
5606 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,
5607 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,
5608 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,
5609 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,
5610 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,
5611 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,
5612 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3
5613 ];
5614
5615 sBox[7] = [
5616 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,
5617 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,
5618 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,
5619 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,
5620 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,
5621 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,
5622 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,
5623 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,
5624 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,
5625 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,
5626 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,
5627 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,
5628 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,
5629 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,
5630 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,
5631 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,
5632 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,
5633 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,
5634 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,
5635 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,
5636 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,
5637 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,
5638 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,
5639 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,
5640 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,
5641 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,
5642 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,
5643 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,
5644 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,
5645 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,
5646 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,
5647 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e
5648 ];
5649 }
5650
5651 function CAST5(key) {
5652 this.cast5 = new OpenPGPSymEncCAST5();
5653 this.cast5.setKey(key);
5654
5655 this.encrypt = function(block) {
5656 return this.cast5.encrypt(block);
5657 };
5658 }
5659
5660 CAST5.blockSize = CAST5.prototype.blockSize = 8;
5661 CAST5.keySize = CAST5.prototype.keySize = 16;
5662
5663 /* eslint-disable no-mixed-operators, no-fallthrough */
5664
5665
5666 /* Modified by Recurity Labs GmbH
5667 *
5668 * Cipher.js
5669 * A block-cipher algorithm implementation on JavaScript
5670 * See Cipher.readme.txt for further information.
5671 *
5672 * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]
5673 * This script file is distributed under the LGPL
5674 *
5675 * ACKNOWLEDGMENT
5676 *
5677 * The main subroutines are written by Michiel van Everdingen.
5678 *
5679 * Michiel van Everdingen
5680 * http://home.versatel.nl/MAvanEverdingen/index.html
5681 *
5682 * All rights for these routines are reserved to Michiel van Everdingen.
5683 *
5684 */
5685
5686 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5687 //Math
5688 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5689
5690 const MAXINT = 0xFFFFFFFF;
5691
5692 function rotw(w, n) {
5693 return (w << n | w >>> (32 - n)) & MAXINT;
5694 }
5695
5696 function getW(a, i) {
5697 return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;
5698 }
5699
5700 function setW(a, i, w) {
5701 a.splice(i, 4, w & 0xFF, (w >>> 8) & 0xFF, (w >>> 16) & 0xFF, (w >>> 24) & 0xFF);
5702 }
5703
5704 function getB(x, n) {
5705 return (x >>> (n * 8)) & 0xFF;
5706 }
5707
5708 // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5709 // Twofish
5710 // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
5711
5712 function createTwofish() {
5713 //
5714 let keyBytes = null;
5715 let dataBytes = null;
5716 let dataOffset = -1;
5717 // var dataLength = -1;
5718 // var idx2 = -1;
5719 //
5720
5721 let tfsKey = [];
5722 let tfsM = [
5723 [],
5724 [],
5725 [],
5726 []
5727 ];
5728
5729 function tfsInit(key) {
5730 keyBytes = key;
5731 let i;
5732 let a;
5733 let b;
5734 let c;
5735 let d;
5736 const meKey = [];
5737 const moKey = [];
5738 const inKey = [];
5739 let kLen;
5740 const sKey = [];
5741 let f01;
5742 let f5b;
5743 let fef;
5744
5745 const q0 = [
5746 [8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4],
5747 [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]
5748 ];
5749 const q1 = [
5750 [14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13],
5751 [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]
5752 ];
5753 const q2 = [
5754 [11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1],
5755 [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]
5756 ];
5757 const q3 = [
5758 [13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10],
5759 [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]
5760 ];
5761 const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];
5762 const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];
5763 const q = [
5764 [],
5765 []
5766 ];
5767 const m = [
5768 [],
5769 [],
5770 [],
5771 []
5772 ];
5773
5774 function ffm5b(x) {
5775 return x ^ (x >> 2) ^ [0, 90, 180, 238][x & 3];
5776 }
5777
5778 function ffmEf(x) {
5779 return x ^ (x >> 1) ^ (x >> 2) ^ [0, 238, 180, 90][x & 3];
5780 }
5781
5782 function mdsRem(p, q) {
5783 let i;
5784 let t;
5785 let u;
5786 for (i = 0; i < 8; i++) {
5787 t = q >>> 24;
5788 q = ((q << 8) & MAXINT) | p >>> 24;
5789 p = (p << 8) & MAXINT;
5790 u = t << 1;
5791 if (t & 128) {
5792 u ^= 333;
5793 }
5794 q ^= t ^ (u << 16);
5795 u ^= t >>> 1;
5796 if (t & 1) {
5797 u ^= 166;
5798 }
5799 q ^= u << 24 | u << 8;
5800 }
5801 return q;
5802 }
5803
5804 function qp(n, x) {
5805 const a = x >> 4;
5806 const b = x & 15;
5807 const c = q0[n][a ^ b];
5808 const d = q1[n][ror4[b] ^ ashx[a]];
5809 return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];
5810 }
5811
5812 function hFun(x, key) {
5813 let a = getB(x, 0);
5814 let b = getB(x, 1);
5815 let c = getB(x, 2);
5816 let d = getB(x, 3);
5817 switch (kLen) {
5818 case 4:
5819 a = q[1][a] ^ getB(key[3], 0);
5820 b = q[0][b] ^ getB(key[3], 1);
5821 c = q[0][c] ^ getB(key[3], 2);
5822 d = q[1][d] ^ getB(key[3], 3);
5823 case 3:
5824 a = q[1][a] ^ getB(key[2], 0);
5825 b = q[1][b] ^ getB(key[2], 1);
5826 c = q[0][c] ^ getB(key[2], 2);
5827 d = q[0][d] ^ getB(key[2], 3);
5828 case 2:
5829 a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);
5830 b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);
5831 c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);
5832 d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);
5833 }
5834 return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];
5835 }
5836
5837 keyBytes = keyBytes.slice(0, 32);
5838 i = keyBytes.length;
5839 while (i !== 16 && i !== 24 && i !== 32) {
5840 keyBytes[i++] = 0;
5841 }
5842
5843 for (i = 0; i < keyBytes.length; i += 4) {
5844 inKey[i >> 2] = getW(keyBytes, i);
5845 }
5846 for (i = 0; i < 256; i++) {
5847 q[0][i] = qp(0, i);
5848 q[1][i] = qp(1, i);
5849 }
5850 for (i = 0; i < 256; i++) {
5851 f01 = q[1][i];
5852 f5b = ffm5b(f01);
5853 fef = ffmEf(f01);
5854 m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);
5855 m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);
5856 f01 = q[0][i];
5857 f5b = ffm5b(f01);
5858 fef = ffmEf(f01);
5859 m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);
5860 m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);
5861 }
5862
5863 kLen = inKey.length / 2;
5864 for (i = 0; i < kLen; i++) {
5865 a = inKey[i + i];
5866 meKey[i] = a;
5867 b = inKey[i + i + 1];
5868 moKey[i] = b;
5869 sKey[kLen - i - 1] = mdsRem(a, b);
5870 }
5871 for (i = 0; i < 40; i += 2) {
5872 a = 0x1010101 * i;
5873 b = a + 0x1010101;
5874 a = hFun(a, meKey);
5875 b = rotw(hFun(b, moKey), 8);
5876 tfsKey[i] = (a + b) & MAXINT;
5877 tfsKey[i + 1] = rotw(a + 2 * b, 9);
5878 }
5879 for (i = 0; i < 256; i++) {
5880 a = b = c = d = i;
5881 switch (kLen) {
5882 case 4:
5883 a = q[1][a] ^ getB(sKey[3], 0);
5884 b = q[0][b] ^ getB(sKey[3], 1);
5885 c = q[0][c] ^ getB(sKey[3], 2);
5886 d = q[1][d] ^ getB(sKey[3], 3);
5887 case 3:
5888 a = q[1][a] ^ getB(sKey[2], 0);
5889 b = q[1][b] ^ getB(sKey[2], 1);
5890 c = q[0][c] ^ getB(sKey[2], 2);
5891 d = q[0][d] ^ getB(sKey[2], 3);
5892 case 2:
5893 tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];
5894 tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];
5895 tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];
5896 tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];
5897 }
5898 }
5899 }
5900
5901 function tfsG0(x) {
5902 return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];
5903 }
5904
5905 function tfsG1(x) {
5906 return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];
5907 }
5908
5909 function tfsFrnd(r, blk) {
5910 let a = tfsG0(blk[0]);
5911 let b = tfsG1(blk[1]);
5912 blk[2] = rotw(blk[2] ^ (a + b + tfsKey[4 * r + 8]) & MAXINT, 31);
5913 blk[3] = rotw(blk[3], 1) ^ (a + 2 * b + tfsKey[4 * r + 9]) & MAXINT;
5914 a = tfsG0(blk[2]);
5915 b = tfsG1(blk[3]);
5916 blk[0] = rotw(blk[0] ^ (a + b + tfsKey[4 * r + 10]) & MAXINT, 31);
5917 blk[1] = rotw(blk[1], 1) ^ (a + 2 * b + tfsKey[4 * r + 11]) & MAXINT;
5918 }
5919
5920 function tfsIrnd(i, blk) {
5921 let a = tfsG0(blk[0]);
5922 let b = tfsG1(blk[1]);
5923 blk[2] = rotw(blk[2], 1) ^ (a + b + tfsKey[4 * i + 10]) & MAXINT;
5924 blk[3] = rotw(blk[3] ^ (a + 2 * b + tfsKey[4 * i + 11]) & MAXINT, 31);
5925 a = tfsG0(blk[2]);
5926 b = tfsG1(blk[3]);
5927 blk[0] = rotw(blk[0], 1) ^ (a + b + tfsKey[4 * i + 8]) & MAXINT;
5928 blk[1] = rotw(blk[1] ^ (a + 2 * b + tfsKey[4 * i + 9]) & MAXINT, 31);
5929 }
5930
5931 function tfsClose() {
5932 tfsKey = [];
5933 tfsM = [
5934 [],
5935 [],
5936 [],
5937 []
5938 ];
5939 }
5940
5941 function tfsEncrypt(data, offset) {
5942 dataBytes = data;
5943 dataOffset = offset;
5944 const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0],
5945 getW(dataBytes, dataOffset + 4) ^ tfsKey[1],
5946 getW(dataBytes, dataOffset + 8) ^ tfsKey[2],
5947 getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];
5948 for (let j = 0; j < 8; j++) {
5949 tfsFrnd(j, blk);
5950 }
5951 setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);
5952 setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);
5953 setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);
5954 setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);
5955 dataOffset += 16;
5956 return dataBytes;
5957 }
5958
5959 function tfsDecrypt(data, offset) {
5960 dataBytes = data;
5961 dataOffset = offset;
5962 const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4],
5963 getW(dataBytes, dataOffset + 4) ^ tfsKey[5],
5964 getW(dataBytes, dataOffset + 8) ^ tfsKey[6],
5965 getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];
5966 for (let j = 7; j >= 0; j--) {
5967 tfsIrnd(j, blk);
5968 }
5969 setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);
5970 setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);
5971 setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);
5972 setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);
5973 dataOffset += 16;
5974 }
5975
5976 // added by Recurity Labs
5977
5978 function tfsFinal() {
5979 return dataBytes;
5980 }
5981
5982 return {
5983 name: 'twofish',
5984 blocksize: 128 / 8,
5985 open: tfsInit,
5986 close: tfsClose,
5987 encrypt: tfsEncrypt,
5988 decrypt: tfsDecrypt,
5989 // added by Recurity Labs
5990 finalize: tfsFinal
5991 };
5992 }
5993
5994 // added by Recurity Labs
5995
5996 function TF(key) {
5997 this.tf = createTwofish();
5998 this.tf.open(Array.from(key), 0);
5999
6000 this.encrypt = function(block) {
6001 return this.tf.encrypt(Array.from(block), 0);
6002 };
6003 }
6004
6005 TF.keySize = TF.prototype.keySize = 32;
6006 TF.blockSize = TF.prototype.blockSize = 16;
6007
6008 /* Modified by Recurity Labs GmbH
6009 *
6010 * Originally written by nklein software (nklein.com)
6011 */
6012
6013 /*
6014 * Javascript implementation based on Bruce Schneier's reference implementation.
6015 *
6016 *
6017 * The constructor doesn't do much of anything. It's just here
6018 * so we can start defining properties and methods and such.
6019 */
6020 function Blowfish() {}
6021
6022 /*
6023 * Declare the block size so that protocols know what size
6024 * Initialization Vector (IV) they will need.
6025 */
6026 Blowfish.prototype.BLOCKSIZE = 8;
6027
6028 /*
6029 * These are the default SBOXES.
6030 */
6031 Blowfish.prototype.SBOXES = [
6032 [
6033 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
6034 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
6035 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,
6036 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
6037 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
6038 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
6039 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,
6040 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
6041 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,
6042 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
6043 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,
6044 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
6045 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
6046 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
6047 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
6048 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
6049 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,
6050 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
6051 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,
6052 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
6053 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,
6054 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
6055 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,
6056 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
6057 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
6058 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
6059 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,
6060 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
6061 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,
6062 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
6063 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,
6064 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
6065 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,
6066 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
6067 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
6068 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
6069 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,
6070 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
6071 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,
6072 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
6073 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,
6074 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
6075 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a
6076 ],
6077 [
6078 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,
6079 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
6080 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,
6081 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
6082 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
6083 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
6084 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
6085 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
6086 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
6087 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
6088 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,
6089 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
6090 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,
6091 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
6092 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,
6093 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
6094 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,
6095 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
6096 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
6097 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
6098 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,
6099 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
6100 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,
6101 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
6102 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,
6103 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
6104 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
6105 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
6106 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
6107 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
6108 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,
6109 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
6110 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,
6111 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
6112 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,
6113 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
6114 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,
6115 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
6116 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
6117 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
6118 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,
6119 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
6120 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7
6121 ],
6122 [
6123 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,
6124 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
6125 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,
6126 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
6127 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,
6128 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
6129 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,
6130 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
6131 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,
6132 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
6133 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,
6134 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
6135 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,
6136 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
6137 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,
6138 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
6139 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,
6140 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
6141 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,
6142 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
6143 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,
6144 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
6145 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,
6146 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
6147 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,
6148 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
6149 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,
6150 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
6151 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,
6152 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
6153 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,
6154 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
6155 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,
6156 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
6157 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,
6158 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
6159 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,
6160 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
6161 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,
6162 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
6163 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,
6164 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
6165 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0
6166 ],
6167 [
6168 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,
6169 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
6170 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,
6171 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
6172 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
6173 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
6174 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
6175 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
6176 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,
6177 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
6178 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,
6179 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
6180 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,
6181 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
6182 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
6183 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
6184 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
6185 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
6186 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,
6187 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
6188 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,
6189 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
6190 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,
6191 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
6192 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,
6193 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
6194 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
6195 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
6196 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,
6197 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
6198 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,
6199 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
6200 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,
6201 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
6202 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,
6203 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
6204 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
6205 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
6206 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,
6207 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
6208 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
6209 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
6210 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
6211 ]
6212 ];
6213
6214 //*
6215 //* This is the default PARRAY
6216 //*
6217 Blowfish.prototype.PARRAY = [
6218 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
6219 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
6220 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b
6221 ];
6222
6223 //*
6224 //* This is the number of rounds the cipher will go
6225 //*
6226 Blowfish.prototype.NN = 16;
6227
6228 //*
6229 //* This function is needed to get rid of problems
6230 //* with the high-bit getting set. If we don't do
6231 //* this, then sometimes ( aa & 0x00FFFFFFFF ) is not
6232 //* equal to ( bb & 0x00FFFFFFFF ) even when they
6233 //* agree bit-for-bit for the first 32 bits.
6234 //*
6235 Blowfish.prototype._clean = function(xx) {
6236 if (xx < 0) {
6237 const yy = xx & 0x7FFFFFFF;
6238 xx = yy + 0x80000000;
6239 }
6240 return xx;
6241 };
6242
6243 //*
6244 //* This is the mixing function that uses the sboxes
6245 //*
6246 Blowfish.prototype._F = function(xx) {
6247 let yy;
6248
6249 const dd = xx & 0x00FF;
6250 xx >>>= 8;
6251 const cc = xx & 0x00FF;
6252 xx >>>= 8;
6253 const bb = xx & 0x00FF;
6254 xx >>>= 8;
6255 const aa = xx & 0x00FF;
6256
6257 yy = this.sboxes[0][aa] + this.sboxes[1][bb];
6258 yy ^= this.sboxes[2][cc];
6259 yy += this.sboxes[3][dd];
6260
6261 return yy;
6262 };
6263
6264 //*
6265 //* This method takes an array with two values, left and right
6266 //* and does NN rounds of Blowfish on them.
6267 //*
6268 Blowfish.prototype._encryptBlock = function(vals) {
6269 let dataL = vals[0];
6270 let dataR = vals[1];
6271
6272 let ii;
6273
6274 for (ii = 0; ii < this.NN; ++ii) {
6275 dataL ^= this.parray[ii];
6276 dataR = this._F(dataL) ^ dataR;
6277
6278 const tmp = dataL;
6279 dataL = dataR;
6280 dataR = tmp;
6281 }
6282
6283 dataL ^= this.parray[this.NN + 0];
6284 dataR ^= this.parray[this.NN + 1];
6285
6286 vals[0] = this._clean(dataR);
6287 vals[1] = this._clean(dataL);
6288 };
6289
6290 //*
6291 //* This method takes a vector of numbers and turns them
6292 //* into long words so that they can be processed by the
6293 //* real algorithm.
6294 //*
6295 //* Maybe I should make the real algorithm above take a vector
6296 //* instead. That will involve more looping, but it won't require
6297 //* the F() method to deconstruct the vector.
6298 //*
6299 Blowfish.prototype.encryptBlock = function(vector) {
6300 let ii;
6301 const vals = [0, 0];
6302 const off = this.BLOCKSIZE / 2;
6303 for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
6304 vals[0] = (vals[0] << 8) | (vector[ii + 0] & 0x00FF);
6305 vals[1] = (vals[1] << 8) | (vector[ii + off] & 0x00FF);
6306 }
6307
6308 this._encryptBlock(vals);
6309
6310 const ret = [];
6311 for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
6312 ret[ii + 0] = ((vals[0] >>> (24 - 8 * (ii))) & 0x00FF);
6313 ret[ii + off] = ((vals[1] >>> (24 - 8 * (ii))) & 0x00FF);
6314 // vals[ 0 ] = ( vals[ 0 ] >>> 8 );
6315 // vals[ 1 ] = ( vals[ 1 ] >>> 8 );
6316 }
6317
6318 return ret;
6319 };
6320
6321 //*
6322 //* This method takes an array with two values, left and right
6323 //* and undoes NN rounds of Blowfish on them.
6324 //*
6325 Blowfish.prototype._decryptBlock = function(vals) {
6326 let dataL = vals[0];
6327 let dataR = vals[1];
6328
6329 let ii;
6330
6331 for (ii = this.NN + 1; ii > 1; --ii) {
6332 dataL ^= this.parray[ii];
6333 dataR = this._F(dataL) ^ dataR;
6334
6335 const tmp = dataL;
6336 dataL = dataR;
6337 dataR = tmp;
6338 }
6339
6340 dataL ^= this.parray[1];
6341 dataR ^= this.parray[0];
6342
6343 vals[0] = this._clean(dataR);
6344 vals[1] = this._clean(dataL);
6345 };
6346
6347 //*
6348 //* This method takes a key array and initializes the
6349 //* sboxes and parray for this encryption.
6350 //*
6351 Blowfish.prototype.init = function(key) {
6352 let ii;
6353 let jj = 0;
6354
6355 this.parray = [];
6356 for (ii = 0; ii < this.NN + 2; ++ii) {
6357 let data = 0x00000000;
6358 for (let kk = 0; kk < 4; ++kk) {
6359 data = (data << 8) | (key[jj] & 0x00FF);
6360 if (++jj >= key.length) {
6361 jj = 0;
6362 }
6363 }
6364 this.parray[ii] = this.PARRAY[ii] ^ data;
6365 }
6366
6367 this.sboxes = [];
6368 for (ii = 0; ii < 4; ++ii) {
6369 this.sboxes[ii] = [];
6370 for (jj = 0; jj < 256; ++jj) {
6371 this.sboxes[ii][jj] = this.SBOXES[ii][jj];
6372 }
6373 }
6374
6375 const vals = [0x00000000, 0x00000000];
6376
6377 for (ii = 0; ii < this.NN + 2; ii += 2) {
6378 this._encryptBlock(vals);
6379 this.parray[ii + 0] = vals[0];
6380 this.parray[ii + 1] = vals[1];
6381 }
6382
6383 for (ii = 0; ii < 4; ++ii) {
6384 for (jj = 0; jj < 256; jj += 2) {
6385 this._encryptBlock(vals);
6386 this.sboxes[ii][jj + 0] = vals[0];
6387 this.sboxes[ii][jj + 1] = vals[1];
6388 }
6389 }
6390 };
6391
6392 // added by Recurity Labs
6393 function BF(key) {
6394 this.bf = new Blowfish();
6395 this.bf.init(key);
6396
6397 this.encrypt = function(block) {
6398 return this.bf.encryptBlock(block);
6399 };
6400 }
6401
6402 BF.keySize = BF.prototype.keySize = 16;
6403 BF.blockSize = BF.prototype.blockSize = 8;
6404
6405 /**
6406 * @fileoverview Symmetric cryptography functions
6407 * @module crypto/cipher
6408 * @private
6409 */
6410
6411 /**
6412 * AES-128 encryption and decryption (ID 7)
6413 * @function
6414 * @param {String} key - 128-bit key
6415 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
6416 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
6417 * @returns {Object}
6418 */
6419 const aes128 = aes(128);
6420 /**
6421 * AES-128 Block Cipher (ID 8)
6422 * @function
6423 * @param {String} key - 192-bit key
6424 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
6425 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
6426 * @returns {Object}
6427 */
6428 const aes192 = aes(192);
6429 /**
6430 * AES-128 Block Cipher (ID 9)
6431 * @function
6432 * @param {String} key - 256-bit key
6433 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
6434 * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
6435 * @returns {Object}
6436 */
6437 const aes256 = aes(256);
6438 // Not in OpenPGP specifications
6439 const des$1 = DES;
6440 /**
6441 * Triple DES Block Cipher (ID 2)
6442 * @function
6443 * @param {String} key - 192-bit key
6444 * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67}
6445 * @returns {Object}
6446 */
6447 const tripledes = TripleDES;
6448 /**
6449 * CAST-128 Block Cipher (ID 3)
6450 * @function
6451 * @param {String} key - 128-bit key
6452 * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm}
6453 * @returns {Object}
6454 */
6455 const cast5 = CAST5;
6456 /**
6457 * Twofish Block Cipher (ID 10)
6458 * @function
6459 * @param {String} key - 256-bit key
6460 * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH}
6461 * @returns {Object}
6462 */
6463 const twofish = TF;
6464 /**
6465 * Blowfish Block Cipher (ID 4)
6466 * @function
6467 * @param {String} key - 128-bit key
6468 * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH}
6469 * @returns {Object}
6470 */
6471 const blowfish = BF;
6472 /**
6473 * Not implemented
6474 * @function
6475 * @throws {Error}
6476 */
6477 const idea = function() {
6478 throw new Error('IDEA symmetric-key algorithm not implemented');
6479 };
6480
6481 var cipher = /*#__PURE__*/Object.freeze({
6482 __proto__: null,
6483 aes128: aes128,
6484 aes192: aes192,
6485 aes256: aes256,
6486 des: des$1,
6487 tripledes: tripledes,
6488 cast5: cast5,
6489 twofish: twofish,
6490 blowfish: blowfish,
6491 idea: idea
6492 });
6493
6494 var sha1_asm = function ( stdlib, foreign, buffer ) {
6495 "use asm";
6496
6497 // SHA256 state
6498 var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0,
6499 TOTAL0 = 0, TOTAL1 = 0;
6500
6501 // HMAC state
6502 var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0,
6503 O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0;
6504
6505 // I/O buffer
6506 var HEAP = new stdlib.Uint8Array(buffer);
6507
6508 function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {
6509 w0 = w0|0;
6510 w1 = w1|0;
6511 w2 = w2|0;
6512 w3 = w3|0;
6513 w4 = w4|0;
6514 w5 = w5|0;
6515 w6 = w6|0;
6516 w7 = w7|0;
6517 w8 = w8|0;
6518 w9 = w9|0;
6519 w10 = w10|0;
6520 w11 = w11|0;
6521 w12 = w12|0;
6522 w13 = w13|0;
6523 w14 = w14|0;
6524 w15 = w15|0;
6525
6526 var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0,
6527 w16 = 0, w17 = 0, w18 = 0, w19 = 0,
6528 w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0,
6529 w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0,
6530 w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0,
6531 w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0,
6532 w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0,
6533 w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0;
6534
6535 a = H0;
6536 b = H1;
6537 c = H2;
6538 d = H3;
6539 e = H4;
6540
6541 // 0
6542 t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6543 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6544
6545 // 1
6546 t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6547 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6548
6549 // 2
6550 t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6551 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6552
6553 // 3
6554 t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6555 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6556
6557 // 4
6558 t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6559 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6560
6561 // 5
6562 t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6563 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6564
6565 // 6
6566 t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6567 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6568
6569 // 7
6570 t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6571 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6572
6573 // 8
6574 t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6575 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6576
6577 // 9
6578 t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6579 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6580
6581 // 10
6582 t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6583 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6584
6585 // 11
6586 t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6587 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6588
6589 // 12
6590 t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6591 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6592
6593 // 13
6594 t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6595 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6596
6597 // 14
6598 t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6599 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6600
6601 // 15
6602 t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6603 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6604
6605 // 16
6606 n = w13 ^ w8 ^ w2 ^ w0;
6607 w16 = (n << 1) | (n >>> 31);
6608 t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6609 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6610
6611 // 17
6612 n = w14 ^ w9 ^ w3 ^ w1;
6613 w17 = (n << 1) | (n >>> 31);
6614 t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6615 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6616
6617 // 18
6618 n = w15 ^ w10 ^ w4 ^ w2;
6619 w18 = (n << 1) | (n >>> 31);
6620 t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6621 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6622
6623 // 19
6624 n = w16 ^ w11 ^ w5 ^ w3;
6625 w19 = (n << 1) | (n >>> 31);
6626 t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
6627 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6628
6629 // 20
6630 n = w17 ^ w12 ^ w6 ^ w4;
6631 w20 = (n << 1) | (n >>> 31);
6632 t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6633 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6634
6635 // 21
6636 n = w18 ^ w13 ^ w7 ^ w5;
6637 w21 = (n << 1) | (n >>> 31);
6638 t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6639 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6640
6641 // 22
6642 n = w19 ^ w14 ^ w8 ^ w6;
6643 w22 = (n << 1) | (n >>> 31);
6644 t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6645 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6646
6647 // 23
6648 n = w20 ^ w15 ^ w9 ^ w7;
6649 w23 = (n << 1) | (n >>> 31);
6650 t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6651 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6652
6653 // 24
6654 n = w21 ^ w16 ^ w10 ^ w8;
6655 w24 = (n << 1) | (n >>> 31);
6656 t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6657 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6658
6659 // 25
6660 n = w22 ^ w17 ^ w11 ^ w9;
6661 w25 = (n << 1) | (n >>> 31);
6662 t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6663 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6664
6665 // 26
6666 n = w23 ^ w18 ^ w12 ^ w10;
6667 w26 = (n << 1) | (n >>> 31);
6668 t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6669 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6670
6671 // 27
6672 n = w24 ^ w19 ^ w13 ^ w11;
6673 w27 = (n << 1) | (n >>> 31);
6674 t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6675 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6676
6677 // 28
6678 n = w25 ^ w20 ^ w14 ^ w12;
6679 w28 = (n << 1) | (n >>> 31);
6680 t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6681 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6682
6683 // 29
6684 n = w26 ^ w21 ^ w15 ^ w13;
6685 w29 = (n << 1) | (n >>> 31);
6686 t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6687 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6688
6689 // 30
6690 n = w27 ^ w22 ^ w16 ^ w14;
6691 w30 = (n << 1) | (n >>> 31);
6692 t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6693 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6694
6695 // 31
6696 n = w28 ^ w23 ^ w17 ^ w15;
6697 w31 = (n << 1) | (n >>> 31);
6698 t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6699 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6700
6701 // 32
6702 n = w29 ^ w24 ^ w18 ^ w16;
6703 w32 = (n << 1) | (n >>> 31);
6704 t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6705 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6706
6707 // 33
6708 n = w30 ^ w25 ^ w19 ^ w17;
6709 w33 = (n << 1) | (n >>> 31);
6710 t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6711 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6712
6713 // 34
6714 n = w31 ^ w26 ^ w20 ^ w18;
6715 w34 = (n << 1) | (n >>> 31);
6716 t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6717 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6718
6719 // 35
6720 n = w32 ^ w27 ^ w21 ^ w19;
6721 w35 = (n << 1) | (n >>> 31);
6722 t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6723 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6724
6725 // 36
6726 n = w33 ^ w28 ^ w22 ^ w20;
6727 w36 = (n << 1) | (n >>> 31);
6728 t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6729 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6730
6731 // 37
6732 n = w34 ^ w29 ^ w23 ^ w21;
6733 w37 = (n << 1) | (n >>> 31);
6734 t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6735 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6736
6737 // 38
6738 n = w35 ^ w30 ^ w24 ^ w22;
6739 w38 = (n << 1) | (n >>> 31);
6740 t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6741 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6742
6743 // 39
6744 n = w36 ^ w31 ^ w25 ^ w23;
6745 w39 = (n << 1) | (n >>> 31);
6746 t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
6747 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6748
6749 // 40
6750 n = w37 ^ w32 ^ w26 ^ w24;
6751 w40 = (n << 1) | (n >>> 31);
6752 t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6753 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6754
6755 // 41
6756 n = w38 ^ w33 ^ w27 ^ w25;
6757 w41 = (n << 1) | (n >>> 31);
6758 t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6759 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6760
6761 // 42
6762 n = w39 ^ w34 ^ w28 ^ w26;
6763 w42 = (n << 1) | (n >>> 31);
6764 t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6765 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6766
6767 // 43
6768 n = w40 ^ w35 ^ w29 ^ w27;
6769 w43 = (n << 1) | (n >>> 31);
6770 t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6771 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6772
6773 // 44
6774 n = w41 ^ w36 ^ w30 ^ w28;
6775 w44 = (n << 1) | (n >>> 31);
6776 t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6777 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6778
6779 // 45
6780 n = w42 ^ w37 ^ w31 ^ w29;
6781 w45 = (n << 1) | (n >>> 31);
6782 t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6783 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6784
6785 // 46
6786 n = w43 ^ w38 ^ w32 ^ w30;
6787 w46 = (n << 1) | (n >>> 31);
6788 t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6789 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6790
6791 // 47
6792 n = w44 ^ w39 ^ w33 ^ w31;
6793 w47 = (n << 1) | (n >>> 31);
6794 t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6795 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6796
6797 // 48
6798 n = w45 ^ w40 ^ w34 ^ w32;
6799 w48 = (n << 1) | (n >>> 31);
6800 t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6801 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6802
6803 // 49
6804 n = w46 ^ w41 ^ w35 ^ w33;
6805 w49 = (n << 1) | (n >>> 31);
6806 t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6807 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6808
6809 // 50
6810 n = w47 ^ w42 ^ w36 ^ w34;
6811 w50 = (n << 1) | (n >>> 31);
6812 t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6813 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6814
6815 // 51
6816 n = w48 ^ w43 ^ w37 ^ w35;
6817 w51 = (n << 1) | (n >>> 31);
6818 t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6819 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6820
6821 // 52
6822 n = w49 ^ w44 ^ w38 ^ w36;
6823 w52 = (n << 1) | (n >>> 31);
6824 t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6825 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6826
6827 // 53
6828 n = w50 ^ w45 ^ w39 ^ w37;
6829 w53 = (n << 1) | (n >>> 31);
6830 t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6831 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6832
6833 // 54
6834 n = w51 ^ w46 ^ w40 ^ w38;
6835 w54 = (n << 1) | (n >>> 31);
6836 t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6837 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6838
6839 // 55
6840 n = w52 ^ w47 ^ w41 ^ w39;
6841 w55 = (n << 1) | (n >>> 31);
6842 t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6843 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6844
6845 // 56
6846 n = w53 ^ w48 ^ w42 ^ w40;
6847 w56 = (n << 1) | (n >>> 31);
6848 t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6849 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6850
6851 // 57
6852 n = w54 ^ w49 ^ w43 ^ w41;
6853 w57 = (n << 1) | (n >>> 31);
6854 t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6855 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6856
6857 // 58
6858 n = w55 ^ w50 ^ w44 ^ w42;
6859 w58 = (n << 1) | (n >>> 31);
6860 t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6861 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6862
6863 // 59
6864 n = w56 ^ w51 ^ w45 ^ w43;
6865 w59 = (n << 1) | (n >>> 31);
6866 t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
6867 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6868
6869 // 60
6870 n = w57 ^ w52 ^ w46 ^ w44;
6871 w60 = (n << 1) | (n >>> 31);
6872 t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6873 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6874
6875 // 61
6876 n = w58 ^ w53 ^ w47 ^ w45;
6877 w61 = (n << 1) | (n >>> 31);
6878 t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6879 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6880
6881 // 62
6882 n = w59 ^ w54 ^ w48 ^ w46;
6883 w62 = (n << 1) | (n >>> 31);
6884 t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6885 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6886
6887 // 63
6888 n = w60 ^ w55 ^ w49 ^ w47;
6889 w63 = (n << 1) | (n >>> 31);
6890 t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6891 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6892
6893 // 64
6894 n = w61 ^ w56 ^ w50 ^ w48;
6895 w64 = (n << 1) | (n >>> 31);
6896 t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6897 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6898
6899 // 65
6900 n = w62 ^ w57 ^ w51 ^ w49;
6901 w65 = (n << 1) | (n >>> 31);
6902 t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6903 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6904
6905 // 66
6906 n = w63 ^ w58 ^ w52 ^ w50;
6907 w66 = (n << 1) | (n >>> 31);
6908 t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6909 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6910
6911 // 67
6912 n = w64 ^ w59 ^ w53 ^ w51;
6913 w67 = (n << 1) | (n >>> 31);
6914 t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6915 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6916
6917 // 68
6918 n = w65 ^ w60 ^ w54 ^ w52;
6919 w68 = (n << 1) | (n >>> 31);
6920 t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6921 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6922
6923 // 69
6924 n = w66 ^ w61 ^ w55 ^ w53;
6925 w69 = (n << 1) | (n >>> 31);
6926 t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6927 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6928
6929 // 70
6930 n = w67 ^ w62 ^ w56 ^ w54;
6931 w70 = (n << 1) | (n >>> 31);
6932 t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6933 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6934
6935 // 71
6936 n = w68 ^ w63 ^ w57 ^ w55;
6937 w71 = (n << 1) | (n >>> 31);
6938 t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6939 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6940
6941 // 72
6942 n = w69 ^ w64 ^ w58 ^ w56;
6943 w72 = (n << 1) | (n >>> 31);
6944 t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6945 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6946
6947 // 73
6948 n = w70 ^ w65 ^ w59 ^ w57;
6949 w73 = (n << 1) | (n >>> 31);
6950 t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6951 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6952
6953 // 74
6954 n = w71 ^ w66 ^ w60 ^ w58;
6955 w74 = (n << 1) | (n >>> 31);
6956 t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6957 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6958
6959 // 75
6960 n = w72 ^ w67 ^ w61 ^ w59;
6961 w75 = (n << 1) | (n >>> 31);
6962 t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6963 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6964
6965 // 76
6966 n = w73 ^ w68 ^ w62 ^ w60;
6967 w76 = (n << 1) | (n >>> 31);
6968 t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6969 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6970
6971 // 77
6972 n = w74 ^ w69 ^ w63 ^ w61;
6973 w77 = (n << 1) | (n >>> 31);
6974 t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6975 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6976
6977 // 78
6978 n = w75 ^ w70 ^ w64 ^ w62;
6979 w78 = (n << 1) | (n >>> 31);
6980 t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6981 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6982
6983 // 79
6984 n = w76 ^ w71 ^ w65 ^ w63;
6985 w79 = (n << 1) | (n >>> 31);
6986 t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
6987 e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
6988
6989 H0 = ( H0 + a )|0;
6990 H1 = ( H1 + b )|0;
6991 H2 = ( H2 + c )|0;
6992 H3 = ( H3 + d )|0;
6993 H4 = ( H4 + e )|0;
6994
6995 }
6996
6997 function _core_heap ( offset ) {
6998 offset = offset|0;
6999
7000 _core(
7001 HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],
7002 HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],
7003 HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],
7004 HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],
7005 HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],
7006 HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],
7007 HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],
7008 HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],
7009 HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],
7010 HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],
7011 HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],
7012 HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],
7013 HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],
7014 HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],
7015 HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],
7016 HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]
7017 );
7018 }
7019
7020 // offset — multiple of 32
7021 function _state_to_heap ( output ) {
7022 output = output|0;
7023
7024 HEAP[output|0] = H0>>>24;
7025 HEAP[output|1] = H0>>>16&255;
7026 HEAP[output|2] = H0>>>8&255;
7027 HEAP[output|3] = H0&255;
7028 HEAP[output|4] = H1>>>24;
7029 HEAP[output|5] = H1>>>16&255;
7030 HEAP[output|6] = H1>>>8&255;
7031 HEAP[output|7] = H1&255;
7032 HEAP[output|8] = H2>>>24;
7033 HEAP[output|9] = H2>>>16&255;
7034 HEAP[output|10] = H2>>>8&255;
7035 HEAP[output|11] = H2&255;
7036 HEAP[output|12] = H3>>>24;
7037 HEAP[output|13] = H3>>>16&255;
7038 HEAP[output|14] = H3>>>8&255;
7039 HEAP[output|15] = H3&255;
7040 HEAP[output|16] = H4>>>24;
7041 HEAP[output|17] = H4>>>16&255;
7042 HEAP[output|18] = H4>>>8&255;
7043 HEAP[output|19] = H4&255;
7044 }
7045
7046 function reset () {
7047 H0 = 0x67452301;
7048 H1 = 0xefcdab89;
7049 H2 = 0x98badcfe;
7050 H3 = 0x10325476;
7051 H4 = 0xc3d2e1f0;
7052 TOTAL0 = TOTAL1 = 0;
7053 }
7054
7055 function init ( h0, h1, h2, h3, h4, total0, total1 ) {
7056 h0 = h0|0;
7057 h1 = h1|0;
7058 h2 = h2|0;
7059 h3 = h3|0;
7060 h4 = h4|0;
7061 total0 = total0|0;
7062 total1 = total1|0;
7063
7064 H0 = h0;
7065 H1 = h1;
7066 H2 = h2;
7067 H3 = h3;
7068 H4 = h4;
7069 TOTAL0 = total0;
7070 TOTAL1 = total1;
7071 }
7072
7073 // offset — multiple of 64
7074 function process ( offset, length ) {
7075 offset = offset|0;
7076 length = length|0;
7077
7078 var hashed = 0;
7079
7080 if ( offset & 63 )
7081 return -1;
7082
7083 while ( (length|0) >= 64 ) {
7084 _core_heap(offset);
7085
7086 offset = ( offset + 64 )|0;
7087 length = ( length - 64 )|0;
7088
7089 hashed = ( hashed + 64 )|0;
7090 }
7091
7092 TOTAL0 = ( TOTAL0 + hashed )|0;
7093 if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
7094
7095 return hashed|0;
7096 }
7097
7098 // offset — multiple of 64
7099 // output — multiple of 32
7100 function finish ( offset, length, output ) {
7101 offset = offset|0;
7102 length = length|0;
7103 output = output|0;
7104
7105 var hashed = 0,
7106 i = 0;
7107
7108 if ( offset & 63 )
7109 return -1;
7110
7111 if ( ~output )
7112 if ( output & 31 )
7113 return -1;
7114
7115 if ( (length|0) >= 64 ) {
7116 hashed = process( offset, length )|0;
7117 if ( (hashed|0) == -1 )
7118 return -1;
7119
7120 offset = ( offset + hashed )|0;
7121 length = ( length - hashed )|0;
7122 }
7123
7124 hashed = ( hashed + length )|0;
7125 TOTAL0 = ( TOTAL0 + length )|0;
7126 if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0;
7127
7128 HEAP[offset|length] = 0x80;
7129
7130 if ( (length|0) >= 56 ) {
7131 for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )
7132 HEAP[offset|i] = 0x00;
7133 _core_heap(offset);
7134
7135 length = 0;
7136
7137 HEAP[offset|0] = 0;
7138 }
7139
7140 for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )
7141 HEAP[offset|i] = 0;
7142
7143 HEAP[offset|56] = TOTAL1>>>21&255;
7144 HEAP[offset|57] = TOTAL1>>>13&255;
7145 HEAP[offset|58] = TOTAL1>>>5&255;
7146 HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;
7147 HEAP[offset|60] = TOTAL0>>>21&255;
7148 HEAP[offset|61] = TOTAL0>>>13&255;
7149 HEAP[offset|62] = TOTAL0>>>5&255;
7150 HEAP[offset|63] = TOTAL0<<3&255;
7151 _core_heap(offset);
7152
7153 if ( ~output )
7154 _state_to_heap(output);
7155
7156 return hashed|0;
7157 }
7158
7159 function hmac_reset () {
7160 H0 = I0;
7161 H1 = I1;
7162 H2 = I2;
7163 H3 = I3;
7164 H4 = I4;
7165 TOTAL0 = 64;
7166 TOTAL1 = 0;
7167 }
7168
7169 function _hmac_opad () {
7170 H0 = O0;
7171 H1 = O1;
7172 H2 = O2;
7173 H3 = O3;
7174 H4 = O4;
7175 TOTAL0 = 64;
7176 TOTAL1 = 0;
7177 }
7178
7179 function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {
7180 p0 = p0|0;
7181 p1 = p1|0;
7182 p2 = p2|0;
7183 p3 = p3|0;
7184 p4 = p4|0;
7185 p5 = p5|0;
7186 p6 = p6|0;
7187 p7 = p7|0;
7188 p8 = p8|0;
7189 p9 = p9|0;
7190 p10 = p10|0;
7191 p11 = p11|0;
7192 p12 = p12|0;
7193 p13 = p13|0;
7194 p14 = p14|0;
7195 p15 = p15|0;
7196
7197 // opad
7198 reset();
7199 _core(
7200 p0 ^ 0x5c5c5c5c,
7201 p1 ^ 0x5c5c5c5c,
7202 p2 ^ 0x5c5c5c5c,
7203 p3 ^ 0x5c5c5c5c,
7204 p4 ^ 0x5c5c5c5c,
7205 p5 ^ 0x5c5c5c5c,
7206 p6 ^ 0x5c5c5c5c,
7207 p7 ^ 0x5c5c5c5c,
7208 p8 ^ 0x5c5c5c5c,
7209 p9 ^ 0x5c5c5c5c,
7210 p10 ^ 0x5c5c5c5c,
7211 p11 ^ 0x5c5c5c5c,
7212 p12 ^ 0x5c5c5c5c,
7213 p13 ^ 0x5c5c5c5c,
7214 p14 ^ 0x5c5c5c5c,
7215 p15 ^ 0x5c5c5c5c
7216 );
7217 O0 = H0;
7218 O1 = H1;
7219 O2 = H2;
7220 O3 = H3;
7221 O4 = H4;
7222
7223 // ipad
7224 reset();
7225 _core(
7226 p0 ^ 0x36363636,
7227 p1 ^ 0x36363636,
7228 p2 ^ 0x36363636,
7229 p3 ^ 0x36363636,
7230 p4 ^ 0x36363636,
7231 p5 ^ 0x36363636,
7232 p6 ^ 0x36363636,
7233 p7 ^ 0x36363636,
7234 p8 ^ 0x36363636,
7235 p9 ^ 0x36363636,
7236 p10 ^ 0x36363636,
7237 p11 ^ 0x36363636,
7238 p12 ^ 0x36363636,
7239 p13 ^ 0x36363636,
7240 p14 ^ 0x36363636,
7241 p15 ^ 0x36363636
7242 );
7243 I0 = H0;
7244 I1 = H1;
7245 I2 = H2;
7246 I3 = H3;
7247 I4 = H4;
7248
7249 TOTAL0 = 64;
7250 TOTAL1 = 0;
7251 }
7252
7253 // offset — multiple of 64
7254 // output — multiple of 32
7255 function hmac_finish ( offset, length, output ) {
7256 offset = offset|0;
7257 length = length|0;
7258 output = output|0;
7259
7260 var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0;
7261
7262 if ( offset & 63 )
7263 return -1;
7264
7265 if ( ~output )
7266 if ( output & 31 )
7267 return -1;
7268
7269 hashed = finish( offset, length, -1 )|0;
7270 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
7271
7272 _hmac_opad();
7273 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
7274
7275 if ( ~output )
7276 _state_to_heap(output);
7277
7278 return hashed|0;
7279 }
7280
7281 // salt is assumed to be already processed
7282 // offset — multiple of 64
7283 // output — multiple of 32
7284 function pbkdf2_generate_block ( offset, length, block, count, output ) {
7285 offset = offset|0;
7286 length = length|0;
7287 block = block|0;
7288 count = count|0;
7289 output = output|0;
7290
7291 var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0,
7292 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
7293
7294 if ( offset & 63 )
7295 return -1;
7296
7297 if ( ~output )
7298 if ( output & 31 )
7299 return -1;
7300
7301 // pad block number into heap
7302 // FIXME probable OOB write
7303 HEAP[(offset+length)|0] = block>>>24;
7304 HEAP[(offset+length+1)|0] = block>>>16&255;
7305 HEAP[(offset+length+2)|0] = block>>>8&255;
7306 HEAP[(offset+length+3)|0] = block&255;
7307
7308 // finish first iteration
7309 hmac_finish( offset, (length+4)|0, -1 )|0;
7310 h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4;
7311 count = (count-1)|0;
7312
7313 // perform the rest iterations
7314 while ( (count|0) > 0 ) {
7315 hmac_reset();
7316 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
7317 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
7318
7319 _hmac_opad();
7320 _core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
7321 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
7322
7323 h0 = h0 ^ H0;
7324 h1 = h1 ^ H1;
7325 h2 = h2 ^ H2;
7326 h3 = h3 ^ H3;
7327 h4 = h4 ^ H4;
7328
7329 count = (count-1)|0;
7330 }
7331
7332 H0 = h0;
7333 H1 = h1;
7334 H2 = h2;
7335 H3 = h3;
7336 H4 = h4;
7337
7338 if ( ~output )
7339 _state_to_heap(output);
7340
7341 return 0;
7342 }
7343
7344 return {
7345 // SHA1
7346 reset: reset,
7347 init: init,
7348 process: process,
7349 finish: finish,
7350
7351 // HMAC-SHA1
7352 hmac_reset: hmac_reset,
7353 hmac_init: hmac_init,
7354 hmac_finish: hmac_finish,
7355
7356 // PBKDF2-HMAC-SHA1
7357 pbkdf2_generate_block: pbkdf2_generate_block
7358 }
7359 };
7360
7361 class Hash {
7362 constructor() {
7363 this.pos = 0;
7364 this.len = 0;
7365 }
7366 reset() {
7367 const { asm } = this.acquire_asm();
7368 this.result = null;
7369 this.pos = 0;
7370 this.len = 0;
7371 asm.reset();
7372 return this;
7373 }
7374 process(data) {
7375 if (this.result !== null)
7376 throw new IllegalStateError('state must be reset before processing new data');
7377 const { asm, heap } = this.acquire_asm();
7378 let hpos = this.pos;
7379 let hlen = this.len;
7380 let dpos = 0;
7381 let dlen = data.length;
7382 let wlen = 0;
7383 while (dlen > 0) {
7384 wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen);
7385 hlen += wlen;
7386 dpos += wlen;
7387 dlen -= wlen;
7388 wlen = asm.process(hpos, hlen);
7389 hpos += wlen;
7390 hlen -= wlen;
7391 if (!hlen)
7392 hpos = 0;
7393 }
7394 this.pos = hpos;
7395 this.len = hlen;
7396 return this;
7397 }
7398 finish() {
7399 if (this.result !== null)
7400 throw new IllegalStateError('state must be reset before processing new data');
7401 const { asm, heap } = this.acquire_asm();
7402 asm.finish(this.pos, this.len, 0);
7403 this.result = new Uint8Array(this.HASH_SIZE);
7404 this.result.set(heap.subarray(0, this.HASH_SIZE));
7405 this.pos = 0;
7406 this.len = 0;
7407 this.release_asm();
7408 return this;
7409 }
7410 }
7411
7412 const _sha1_block_size = 64;
7413 const _sha1_hash_size = 20;
7414 const heap_pool$1 = [];
7415 const asm_pool$1 = [];
7416 class Sha1 extends Hash {
7417 constructor() {
7418 super();
7419 this.NAME = 'sha1';
7420 this.BLOCK_SIZE = _sha1_block_size;
7421 this.HASH_SIZE = _sha1_hash_size;
7422 this.acquire_asm();
7423 }
7424 acquire_asm() {
7425 if (this.heap === undefined || this.asm === undefined) {
7426 this.heap = heap_pool$1.pop() || _heap_init();
7427 this.asm = asm_pool$1.pop() || sha1_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);
7428 this.reset();
7429 }
7430 return { heap: this.heap, asm: this.asm };
7431 }
7432 release_asm() {
7433 if (this.heap !== undefined && this.asm !== undefined) {
7434 heap_pool$1.push(this.heap);
7435 asm_pool$1.push(this.asm);
7436 }
7437 this.heap = undefined;
7438 this.asm = undefined;
7439 }
7440 static bytes(data) {
7441 return new Sha1().process(data).finish().result;
7442 }
7443 }
7444 Sha1.NAME = 'sha1';
7445 Sha1.heap_pool = [];
7446 Sha1.asm_pool = [];
7447 Sha1.asm_function = sha1_asm;
7448
7449 var sha256_asm = function ( stdlib, foreign, buffer ) {
7450 "use asm";
7451
7452 // SHA256 state
7453 var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0,
7454 TOTAL0 = 0, TOTAL1 = 0;
7455
7456 // HMAC state
7457 var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0,
7458 O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0;
7459
7460 // I/O buffer
7461 var HEAP = new stdlib.Uint8Array(buffer);
7462
7463 function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {
7464 w0 = w0|0;
7465 w1 = w1|0;
7466 w2 = w2|0;
7467 w3 = w3|0;
7468 w4 = w4|0;
7469 w5 = w5|0;
7470 w6 = w6|0;
7471 w7 = w7|0;
7472 w8 = w8|0;
7473 w9 = w9|0;
7474 w10 = w10|0;
7475 w11 = w11|0;
7476 w12 = w12|0;
7477 w13 = w13|0;
7478 w14 = w14|0;
7479 w15 = w15|0;
7480
7481 var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0;
7482
7483 a = H0;
7484 b = H1;
7485 c = H2;
7486 d = H3;
7487 e = H4;
7488 f = H5;
7489 g = H6;
7490 h = H7;
7491
7492 // 0
7493 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0;
7494 d = ( d + h )|0;
7495 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7496
7497 // 1
7498 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0;
7499 c = ( c + g )|0;
7500 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7501
7502 // 2
7503 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0;
7504 b = ( b + f )|0;
7505 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7506
7507 // 3
7508 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0;
7509 a = ( a + e )|0;
7510 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7511
7512 // 4
7513 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0;
7514 h = ( h + d )|0;
7515 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7516
7517 // 5
7518 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0;
7519 g = ( g + c )|0;
7520 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7521
7522 // 6
7523 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0;
7524 f = ( f + b )|0;
7525 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7526
7527 // 7
7528 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0;
7529 e = ( e + a )|0;
7530 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7531
7532 // 8
7533 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0;
7534 d = ( d + h )|0;
7535 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7536
7537 // 9
7538 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0;
7539 c = ( c + g )|0;
7540 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7541
7542 // 10
7543 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0;
7544 b = ( b + f )|0;
7545 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7546
7547 // 11
7548 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0;
7549 a = ( a + e )|0;
7550 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7551
7552 // 12
7553 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0;
7554 h = ( h + d )|0;
7555 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7556
7557 // 13
7558 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0;
7559 g = ( g + c )|0;
7560 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7561
7562 // 14
7563 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0;
7564 f = ( f + b )|0;
7565 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7566
7567 // 15
7568 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0;
7569 e = ( e + a )|0;
7570 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7571
7572 // 16
7573 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
7574 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0;
7575 d = ( d + h )|0;
7576 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7577
7578 // 17
7579 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
7580 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0;
7581 c = ( c + g )|0;
7582 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7583
7584 // 18
7585 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
7586 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0;
7587 b = ( b + f )|0;
7588 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7589
7590 // 19
7591 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
7592 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0;
7593 a = ( a + e )|0;
7594 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7595
7596 // 20
7597 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
7598 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0;
7599 h = ( h + d )|0;
7600 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7601
7602 // 21
7603 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
7604 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0;
7605 g = ( g + c )|0;
7606 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7607
7608 // 22
7609 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
7610 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0;
7611 f = ( f + b )|0;
7612 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7613
7614 // 23
7615 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
7616 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0;
7617 e = ( e + a )|0;
7618 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7619
7620 // 24
7621 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
7622 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0;
7623 d = ( d + h )|0;
7624 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7625
7626 // 25
7627 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
7628 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0;
7629 c = ( c + g )|0;
7630 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7631
7632 // 26
7633 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
7634 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0;
7635 b = ( b + f )|0;
7636 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7637
7638 // 27
7639 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
7640 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0;
7641 a = ( a + e )|0;
7642 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7643
7644 // 28
7645 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
7646 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0;
7647 h = ( h + d )|0;
7648 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7649
7650 // 29
7651 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
7652 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0;
7653 g = ( g + c )|0;
7654 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7655
7656 // 30
7657 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
7658 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0;
7659 f = ( f + b )|0;
7660 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7661
7662 // 31
7663 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
7664 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0;
7665 e = ( e + a )|0;
7666 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7667
7668 // 32
7669 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
7670 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0;
7671 d = ( d + h )|0;
7672 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7673
7674 // 33
7675 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
7676 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0;
7677 c = ( c + g )|0;
7678 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7679
7680 // 34
7681 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
7682 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0;
7683 b = ( b + f )|0;
7684 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7685
7686 // 35
7687 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
7688 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0;
7689 a = ( a + e )|0;
7690 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7691
7692 // 36
7693 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
7694 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0;
7695 h = ( h + d )|0;
7696 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7697
7698 // 37
7699 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
7700 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0;
7701 g = ( g + c )|0;
7702 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7703
7704 // 38
7705 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
7706 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0;
7707 f = ( f + b )|0;
7708 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7709
7710 // 39
7711 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
7712 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0;
7713 e = ( e + a )|0;
7714 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7715
7716 // 40
7717 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
7718 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0;
7719 d = ( d + h )|0;
7720 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7721
7722 // 41
7723 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
7724 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0;
7725 c = ( c + g )|0;
7726 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7727
7728 // 42
7729 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
7730 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0;
7731 b = ( b + f )|0;
7732 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7733
7734 // 43
7735 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
7736 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0;
7737 a = ( a + e )|0;
7738 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7739
7740 // 44
7741 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
7742 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0;
7743 h = ( h + d )|0;
7744 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7745
7746 // 45
7747 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
7748 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0;
7749 g = ( g + c )|0;
7750 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7751
7752 // 46
7753 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
7754 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0;
7755 f = ( f + b )|0;
7756 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7757
7758 // 47
7759 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
7760 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0;
7761 e = ( e + a )|0;
7762 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7763
7764 // 48
7765 w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
7766 h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0;
7767 d = ( d + h )|0;
7768 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7769
7770 // 49
7771 w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
7772 g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0;
7773 c = ( c + g )|0;
7774 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7775
7776 // 50
7777 w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
7778 f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0;
7779 b = ( b + f )|0;
7780 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7781
7782 // 51
7783 w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
7784 e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0;
7785 a = ( a + e )|0;
7786 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7787
7788 // 52
7789 w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
7790 d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0;
7791 h = ( h + d )|0;
7792 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7793
7794 // 53
7795 w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
7796 c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0;
7797 g = ( g + c )|0;
7798 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7799
7800 // 54
7801 w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
7802 b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0;
7803 f = ( f + b )|0;
7804 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7805
7806 // 55
7807 w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
7808 a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0;
7809 e = ( e + a )|0;
7810 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7811
7812 // 56
7813 w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
7814 h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0;
7815 d = ( d + h )|0;
7816 h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
7817
7818 // 57
7819 w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
7820 g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0;
7821 c = ( c + g )|0;
7822 g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
7823
7824 // 58
7825 w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
7826 f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0;
7827 b = ( b + f )|0;
7828 f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
7829
7830 // 59
7831 w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
7832 e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0;
7833 a = ( a + e )|0;
7834 e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
7835
7836 // 60
7837 w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
7838 d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0;
7839 h = ( h + d )|0;
7840 d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
7841
7842 // 61
7843 w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
7844 c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0;
7845 g = ( g + c )|0;
7846 c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
7847
7848 // 62
7849 w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
7850 b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0;
7851 f = ( f + b )|0;
7852 b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
7853
7854 // 63
7855 w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
7856 a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0;
7857 e = ( e + a )|0;
7858 a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
7859
7860 H0 = ( H0 + a )|0;
7861 H1 = ( H1 + b )|0;
7862 H2 = ( H2 + c )|0;
7863 H3 = ( H3 + d )|0;
7864 H4 = ( H4 + e )|0;
7865 H5 = ( H5 + f )|0;
7866 H6 = ( H6 + g )|0;
7867 H7 = ( H7 + h )|0;
7868 }
7869
7870 function _core_heap ( offset ) {
7871 offset = offset|0;
7872
7873 _core(
7874 HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],
7875 HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],
7876 HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],
7877 HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],
7878 HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],
7879 HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],
7880 HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],
7881 HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],
7882 HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],
7883 HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],
7884 HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],
7885 HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],
7886 HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],
7887 HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],
7888 HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],
7889 HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]
7890 );
7891 }
7892
7893 // offset — multiple of 32
7894 function _state_to_heap ( output ) {
7895 output = output|0;
7896
7897 HEAP[output|0] = H0>>>24;
7898 HEAP[output|1] = H0>>>16&255;
7899 HEAP[output|2] = H0>>>8&255;
7900 HEAP[output|3] = H0&255;
7901 HEAP[output|4] = H1>>>24;
7902 HEAP[output|5] = H1>>>16&255;
7903 HEAP[output|6] = H1>>>8&255;
7904 HEAP[output|7] = H1&255;
7905 HEAP[output|8] = H2>>>24;
7906 HEAP[output|9] = H2>>>16&255;
7907 HEAP[output|10] = H2>>>8&255;
7908 HEAP[output|11] = H2&255;
7909 HEAP[output|12] = H3>>>24;
7910 HEAP[output|13] = H3>>>16&255;
7911 HEAP[output|14] = H3>>>8&255;
7912 HEAP[output|15] = H3&255;
7913 HEAP[output|16] = H4>>>24;
7914 HEAP[output|17] = H4>>>16&255;
7915 HEAP[output|18] = H4>>>8&255;
7916 HEAP[output|19] = H4&255;
7917 HEAP[output|20] = H5>>>24;
7918 HEAP[output|21] = H5>>>16&255;
7919 HEAP[output|22] = H5>>>8&255;
7920 HEAP[output|23] = H5&255;
7921 HEAP[output|24] = H6>>>24;
7922 HEAP[output|25] = H6>>>16&255;
7923 HEAP[output|26] = H6>>>8&255;
7924 HEAP[output|27] = H6&255;
7925 HEAP[output|28] = H7>>>24;
7926 HEAP[output|29] = H7>>>16&255;
7927 HEAP[output|30] = H7>>>8&255;
7928 HEAP[output|31] = H7&255;
7929 }
7930
7931 function reset () {
7932 H0 = 0x6a09e667;
7933 H1 = 0xbb67ae85;
7934 H2 = 0x3c6ef372;
7935 H3 = 0xa54ff53a;
7936 H4 = 0x510e527f;
7937 H5 = 0x9b05688c;
7938 H6 = 0x1f83d9ab;
7939 H7 = 0x5be0cd19;
7940 TOTAL0 = TOTAL1 = 0;
7941 }
7942
7943 function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) {
7944 h0 = h0|0;
7945 h1 = h1|0;
7946 h2 = h2|0;
7947 h3 = h3|0;
7948 h4 = h4|0;
7949 h5 = h5|0;
7950 h6 = h6|0;
7951 h7 = h7|0;
7952 total0 = total0|0;
7953 total1 = total1|0;
7954
7955 H0 = h0;
7956 H1 = h1;
7957 H2 = h2;
7958 H3 = h3;
7959 H4 = h4;
7960 H5 = h5;
7961 H6 = h6;
7962 H7 = h7;
7963 TOTAL0 = total0;
7964 TOTAL1 = total1;
7965 }
7966
7967 // offset — multiple of 64
7968 function process ( offset, length ) {
7969 offset = offset|0;
7970 length = length|0;
7971
7972 var hashed = 0;
7973
7974 if ( offset & 63 )
7975 return -1;
7976
7977 while ( (length|0) >= 64 ) {
7978 _core_heap(offset);
7979
7980 offset = ( offset + 64 )|0;
7981 length = ( length - 64 )|0;
7982
7983 hashed = ( hashed + 64 )|0;
7984 }
7985
7986 TOTAL0 = ( TOTAL0 + hashed )|0;
7987 if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
7988
7989 return hashed|0;
7990 }
7991
7992 // offset — multiple of 64
7993 // output — multiple of 32
7994 function finish ( offset, length, output ) {
7995 offset = offset|0;
7996 length = length|0;
7997 output = output|0;
7998
7999 var hashed = 0,
8000 i = 0;
8001
8002 if ( offset & 63 )
8003 return -1;
8004
8005 if ( ~output )
8006 if ( output & 31 )
8007 return -1;
8008
8009 if ( (length|0) >= 64 ) {
8010 hashed = process( offset, length )|0;
8011 if ( (hashed|0) == -1 )
8012 return -1;
8013
8014 offset = ( offset + hashed )|0;
8015 length = ( length - hashed )|0;
8016 }
8017
8018 hashed = ( hashed + length )|0;
8019 TOTAL0 = ( TOTAL0 + length )|0;
8020 if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
8021
8022 HEAP[offset|length] = 0x80;
8023
8024 if ( (length|0) >= 56 ) {
8025 for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )
8026 HEAP[offset|i] = 0x00;
8027
8028 _core_heap(offset);
8029
8030 length = 0;
8031
8032 HEAP[offset|0] = 0;
8033 }
8034
8035 for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )
8036 HEAP[offset|i] = 0;
8037
8038 HEAP[offset|56] = TOTAL1>>>21&255;
8039 HEAP[offset|57] = TOTAL1>>>13&255;
8040 HEAP[offset|58] = TOTAL1>>>5&255;
8041 HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;
8042 HEAP[offset|60] = TOTAL0>>>21&255;
8043 HEAP[offset|61] = TOTAL0>>>13&255;
8044 HEAP[offset|62] = TOTAL0>>>5&255;
8045 HEAP[offset|63] = TOTAL0<<3&255;
8046 _core_heap(offset);
8047
8048 if ( ~output )
8049 _state_to_heap(output);
8050
8051 return hashed|0;
8052 }
8053
8054 function hmac_reset () {
8055 H0 = I0;
8056 H1 = I1;
8057 H2 = I2;
8058 H3 = I3;
8059 H4 = I4;
8060 H5 = I5;
8061 H6 = I6;
8062 H7 = I7;
8063 TOTAL0 = 64;
8064 TOTAL1 = 0;
8065 }
8066
8067 function _hmac_opad () {
8068 H0 = O0;
8069 H1 = O1;
8070 H2 = O2;
8071 H3 = O3;
8072 H4 = O4;
8073 H5 = O5;
8074 H6 = O6;
8075 H7 = O7;
8076 TOTAL0 = 64;
8077 TOTAL1 = 0;
8078 }
8079
8080 function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {
8081 p0 = p0|0;
8082 p1 = p1|0;
8083 p2 = p2|0;
8084 p3 = p3|0;
8085 p4 = p4|0;
8086 p5 = p5|0;
8087 p6 = p6|0;
8088 p7 = p7|0;
8089 p8 = p8|0;
8090 p9 = p9|0;
8091 p10 = p10|0;
8092 p11 = p11|0;
8093 p12 = p12|0;
8094 p13 = p13|0;
8095 p14 = p14|0;
8096 p15 = p15|0;
8097
8098 // opad
8099 reset();
8100 _core(
8101 p0 ^ 0x5c5c5c5c,
8102 p1 ^ 0x5c5c5c5c,
8103 p2 ^ 0x5c5c5c5c,
8104 p3 ^ 0x5c5c5c5c,
8105 p4 ^ 0x5c5c5c5c,
8106 p5 ^ 0x5c5c5c5c,
8107 p6 ^ 0x5c5c5c5c,
8108 p7 ^ 0x5c5c5c5c,
8109 p8 ^ 0x5c5c5c5c,
8110 p9 ^ 0x5c5c5c5c,
8111 p10 ^ 0x5c5c5c5c,
8112 p11 ^ 0x5c5c5c5c,
8113 p12 ^ 0x5c5c5c5c,
8114 p13 ^ 0x5c5c5c5c,
8115 p14 ^ 0x5c5c5c5c,
8116 p15 ^ 0x5c5c5c5c
8117 );
8118 O0 = H0;
8119 O1 = H1;
8120 O2 = H2;
8121 O3 = H3;
8122 O4 = H4;
8123 O5 = H5;
8124 O6 = H6;
8125 O7 = H7;
8126
8127 // ipad
8128 reset();
8129 _core(
8130 p0 ^ 0x36363636,
8131 p1 ^ 0x36363636,
8132 p2 ^ 0x36363636,
8133 p3 ^ 0x36363636,
8134 p4 ^ 0x36363636,
8135 p5 ^ 0x36363636,
8136 p6 ^ 0x36363636,
8137 p7 ^ 0x36363636,
8138 p8 ^ 0x36363636,
8139 p9 ^ 0x36363636,
8140 p10 ^ 0x36363636,
8141 p11 ^ 0x36363636,
8142 p12 ^ 0x36363636,
8143 p13 ^ 0x36363636,
8144 p14 ^ 0x36363636,
8145 p15 ^ 0x36363636
8146 );
8147 I0 = H0;
8148 I1 = H1;
8149 I2 = H2;
8150 I3 = H3;
8151 I4 = H4;
8152 I5 = H5;
8153 I6 = H6;
8154 I7 = H7;
8155
8156 TOTAL0 = 64;
8157 TOTAL1 = 0;
8158 }
8159
8160 // offset — multiple of 64
8161 // output — multiple of 32
8162 function hmac_finish ( offset, length, output ) {
8163 offset = offset|0;
8164 length = length|0;
8165 output = output|0;
8166
8167 var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
8168 hashed = 0;
8169
8170 if ( offset & 63 )
8171 return -1;
8172
8173 if ( ~output )
8174 if ( output & 31 )
8175 return -1;
8176
8177 hashed = finish( offset, length, -1 )|0;
8178 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
8179
8180 _hmac_opad();
8181 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
8182
8183 if ( ~output )
8184 _state_to_heap(output);
8185
8186 return hashed|0;
8187 }
8188
8189 // salt is assumed to be already processed
8190 // offset — multiple of 64
8191 // output — multiple of 32
8192 function pbkdf2_generate_block ( offset, length, block, count, output ) {
8193 offset = offset|0;
8194 length = length|0;
8195 block = block|0;
8196 count = count|0;
8197 output = output|0;
8198
8199 var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0,
8200 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0;
8201
8202 if ( offset & 63 )
8203 return -1;
8204
8205 if ( ~output )
8206 if ( output & 31 )
8207 return -1;
8208
8209 // pad block number into heap
8210 // FIXME probable OOB write
8211 HEAP[(offset+length)|0] = block>>>24;
8212 HEAP[(offset+length+1)|0] = block>>>16&255;
8213 HEAP[(offset+length+2)|0] = block>>>8&255;
8214 HEAP[(offset+length+3)|0] = block&255;
8215
8216 // finish first iteration
8217 hmac_finish( offset, (length+4)|0, -1 )|0;
8218 h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7;
8219 count = (count-1)|0;
8220
8221 // perform the rest iterations
8222 while ( (count|0) > 0 ) {
8223 hmac_reset();
8224 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
8225 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
8226
8227 _hmac_opad();
8228 _core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
8229 t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
8230
8231 h0 = h0 ^ H0;
8232 h1 = h1 ^ H1;
8233 h2 = h2 ^ H2;
8234 h3 = h3 ^ H3;
8235 h4 = h4 ^ H4;
8236 h5 = h5 ^ H5;
8237 h6 = h6 ^ H6;
8238 h7 = h7 ^ H7;
8239
8240 count = (count-1)|0;
8241 }
8242
8243 H0 = h0;
8244 H1 = h1;
8245 H2 = h2;
8246 H3 = h3;
8247 H4 = h4;
8248 H5 = h5;
8249 H6 = h6;
8250 H7 = h7;
8251
8252 if ( ~output )
8253 _state_to_heap(output);
8254
8255 return 0;
8256 }
8257
8258 return {
8259 // SHA256
8260 reset: reset,
8261 init: init,
8262 process: process,
8263 finish: finish,
8264
8265 // HMAC-SHA256
8266 hmac_reset: hmac_reset,
8267 hmac_init: hmac_init,
8268 hmac_finish: hmac_finish,
8269
8270 // PBKDF2-HMAC-SHA256
8271 pbkdf2_generate_block: pbkdf2_generate_block
8272 }
8273 };
8274
8275 const _sha256_block_size = 64;
8276 const _sha256_hash_size = 32;
8277 const heap_pool$2 = [];
8278 const asm_pool$2 = [];
8279 class Sha256 extends Hash {
8280 constructor() {
8281 super();
8282 this.NAME = 'sha256';
8283 this.BLOCK_SIZE = _sha256_block_size;
8284 this.HASH_SIZE = _sha256_hash_size;
8285 this.acquire_asm();
8286 }
8287 acquire_asm() {
8288 if (this.heap === undefined || this.asm === undefined) {
8289 this.heap = heap_pool$2.pop() || _heap_init();
8290 this.asm = asm_pool$2.pop() || sha256_asm({ Uint8Array: Uint8Array }, null, this.heap.buffer);
8291 this.reset();
8292 }
8293 return { heap: this.heap, asm: this.asm };
8294 }
8295 release_asm() {
8296 if (this.heap !== undefined && this.asm !== undefined) {
8297 heap_pool$2.push(this.heap);
8298 asm_pool$2.push(this.asm);
8299 }
8300 this.heap = undefined;
8301 this.asm = undefined;
8302 }
8303 static bytes(data) {
8304 return new Sha256().process(data).finish().result;
8305 }
8306 }
8307 Sha256.NAME = 'sha256';
8308
8309 var minimalisticAssert = assert;
8310
8311 function assert(val, msg) {
8312 if (!val)
8313 throw new Error(msg || 'Assertion failed');
8314 }
8315
8316 assert.equal = function assertEqual(l, r, msg) {
8317 if (l != r)
8318 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
8319 };
8320
8321 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
8322
8323 function createCommonjsModule(fn, module) {
8324 return module = { exports: {} }, fn(module, module.exports), module.exports;
8325 }
8326
8327 function commonjsRequire () {
8328 throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
8329 }
8330
8331 var inherits_browser = createCommonjsModule(function (module) {
8332 if (typeof Object.create === 'function') {
8333 // implementation from standard node.js 'util' module
8334 module.exports = function inherits(ctor, superCtor) {
8335 ctor.super_ = superCtor;
8336 ctor.prototype = Object.create(superCtor.prototype, {
8337 constructor: {
8338 value: ctor,
8339 enumerable: false,
8340 writable: true,
8341 configurable: true
8342 }
8343 });
8344 };
8345 } else {
8346 // old school shim for old browsers
8347 module.exports = function inherits(ctor, superCtor) {
8348 ctor.super_ = superCtor;
8349 var TempCtor = function () {};
8350 TempCtor.prototype = superCtor.prototype;
8351 ctor.prototype = new TempCtor();
8352 ctor.prototype.constructor = ctor;
8353 };
8354 }
8355 });
8356
8357 var inherits_1 = inherits_browser;
8358
8359 function toArray(msg, enc) {
8360 if (Array.isArray(msg))
8361 return msg.slice();
8362 if (!msg)
8363 return [];
8364 var res = [];
8365 if (typeof msg === 'string') {
8366 if (!enc) {
8367 for (var i = 0; i < msg.length; i++) {
8368 var c = msg.charCodeAt(i);
8369 var hi = c >> 8;
8370 var lo = c & 0xff;
8371 if (hi)
8372 res.push(hi, lo);
8373 else
8374 res.push(lo);
8375 }
8376 } else if (enc === 'hex') {
8377 msg = msg.replace(/[^a-z0-9]+/ig, '');
8378 if (msg.length % 2 !== 0)
8379 msg = '0' + msg;
8380 for (i = 0; i < msg.length; i += 2)
8381 res.push(parseInt(msg[i] + msg[i + 1], 16));
8382 }
8383 } else {
8384 for (i = 0; i < msg.length; i++)
8385 res[i] = msg[i] | 0;
8386 }
8387 return res;
8388 }
8389 var toArray_1 = toArray;
8390
8391 function toHex(msg) {
8392 var res = '';
8393 for (var i = 0; i < msg.length; i++)
8394 res += zero2(msg[i].toString(16));
8395 return res;
8396 }
8397 var toHex_1 = toHex;
8398
8399 function htonl(w) {
8400 var res = (w >>> 24) |
8401 ((w >>> 8) & 0xff00) |
8402 ((w << 8) & 0xff0000) |
8403 ((w & 0xff) << 24);
8404 return res >>> 0;
8405 }
8406 var htonl_1 = htonl;
8407
8408 function toHex32(msg, endian) {
8409 var res = '';
8410 for (var i = 0; i < msg.length; i++) {
8411 var w = msg[i];
8412 if (endian === 'little')
8413 w = htonl(w);
8414 res += zero8(w.toString(16));
8415 }
8416 return res;
8417 }
8418 var toHex32_1 = toHex32;
8419
8420 function zero2(word) {
8421 if (word.length === 1)
8422 return '0' + word;
8423 else
8424 return word;
8425 }
8426 var zero2_1 = zero2;
8427
8428 function zero8(word) {
8429 if (word.length === 7)
8430 return '0' + word;
8431 else if (word.length === 6)
8432 return '00' + word;
8433 else if (word.length === 5)
8434 return '000' + word;
8435 else if (word.length === 4)
8436 return '0000' + word;
8437 else if (word.length === 3)
8438 return '00000' + word;
8439 else if (word.length === 2)
8440 return '000000' + word;
8441 else if (word.length === 1)
8442 return '0000000' + word;
8443 else
8444 return word;
8445 }
8446 var zero8_1 = zero8;
8447
8448 function join32(msg, start, end, endian) {
8449 var len = end - start;
8450 minimalisticAssert(len % 4 === 0);
8451 var res = new Array(len / 4);
8452 for (var i = 0, k = start; i < res.length; i++, k += 4) {
8453 var w;
8454 if (endian === 'big')
8455 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
8456 else
8457 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
8458 res[i] = w >>> 0;
8459 }
8460 return res;
8461 }
8462 var join32_1 = join32;
8463
8464 function split32(msg, endian) {
8465 var res = new Array(msg.length * 4);
8466 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
8467 var m = msg[i];
8468 if (endian === 'big') {
8469 res[k] = m >>> 24;
8470 res[k + 1] = (m >>> 16) & 0xff;
8471 res[k + 2] = (m >>> 8) & 0xff;
8472 res[k + 3] = m & 0xff;
8473 } else {
8474 res[k + 3] = m >>> 24;
8475 res[k + 2] = (m >>> 16) & 0xff;
8476 res[k + 1] = (m >>> 8) & 0xff;
8477 res[k] = m & 0xff;
8478 }
8479 }
8480 return res;
8481 }
8482 var split32_1 = split32;
8483
8484 function rotr32(w, b) {
8485 return (w >>> b) | (w << (32 - b));
8486 }
8487 var rotr32_1 = rotr32;
8488
8489 function rotl32(w, b) {
8490 return (w << b) | (w >>> (32 - b));
8491 }
8492 var rotl32_1 = rotl32;
8493
8494 function sum32(a, b) {
8495 return (a + b) >>> 0;
8496 }
8497 var sum32_1 = sum32;
8498
8499 function sum32_3(a, b, c) {
8500 return (a + b + c) >>> 0;
8501 }
8502 var sum32_3_1 = sum32_3;
8503
8504 function sum32_4(a, b, c, d) {
8505 return (a + b + c + d) >>> 0;
8506 }
8507 var sum32_4_1 = sum32_4;
8508
8509 function sum32_5(a, b, c, d, e) {
8510 return (a + b + c + d + e) >>> 0;
8511 }
8512 var sum32_5_1 = sum32_5;
8513
8514 function sum64(buf, pos, ah, al) {
8515 var bh = buf[pos];
8516 var bl = buf[pos + 1];
8517
8518 var lo = (al + bl) >>> 0;
8519 var hi = (lo < al ? 1 : 0) + ah + bh;
8520 buf[pos] = hi >>> 0;
8521 buf[pos + 1] = lo;
8522 }
8523 var sum64_1 = sum64;
8524
8525 function sum64_hi(ah, al, bh, bl) {
8526 var lo = (al + bl) >>> 0;
8527 var hi = (lo < al ? 1 : 0) + ah + bh;
8528 return hi >>> 0;
8529 }
8530 var sum64_hi_1 = sum64_hi;
8531
8532 function sum64_lo(ah, al, bh, bl) {
8533 var lo = al + bl;
8534 return lo >>> 0;
8535 }
8536 var sum64_lo_1 = sum64_lo;
8537
8538 function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
8539 var carry = 0;
8540 var lo = al;
8541 lo = (lo + bl) >>> 0;
8542 carry += lo < al ? 1 : 0;
8543 lo = (lo + cl) >>> 0;
8544 carry += lo < cl ? 1 : 0;
8545 lo = (lo + dl) >>> 0;
8546 carry += lo < dl ? 1 : 0;
8547
8548 var hi = ah + bh + ch + dh + carry;
8549 return hi >>> 0;
8550 }
8551 var sum64_4_hi_1 = sum64_4_hi;
8552
8553 function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
8554 var lo = al + bl + cl + dl;
8555 return lo >>> 0;
8556 }
8557 var sum64_4_lo_1 = sum64_4_lo;
8558
8559 function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
8560 var carry = 0;
8561 var lo = al;
8562 lo = (lo + bl) >>> 0;
8563 carry += lo < al ? 1 : 0;
8564 lo = (lo + cl) >>> 0;
8565 carry += lo < cl ? 1 : 0;
8566 lo = (lo + dl) >>> 0;
8567 carry += lo < dl ? 1 : 0;
8568 lo = (lo + el) >>> 0;
8569 carry += lo < el ? 1 : 0;
8570
8571 var hi = ah + bh + ch + dh + eh + carry;
8572 return hi >>> 0;
8573 }
8574 var sum64_5_hi_1 = sum64_5_hi;
8575
8576 function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
8577 var lo = al + bl + cl + dl + el;
8578
8579 return lo >>> 0;
8580 }
8581 var sum64_5_lo_1 = sum64_5_lo;
8582
8583 function rotr64_hi(ah, al, num) {
8584 var r = (al << (32 - num)) | (ah >>> num);
8585 return r >>> 0;
8586 }
8587 var rotr64_hi_1 = rotr64_hi;
8588
8589 function rotr64_lo(ah, al, num) {
8590 var r = (ah << (32 - num)) | (al >>> num);
8591 return r >>> 0;
8592 }
8593 var rotr64_lo_1 = rotr64_lo;
8594
8595 function shr64_hi(ah, al, num) {
8596 return ah >>> num;
8597 }
8598 var shr64_hi_1 = shr64_hi;
8599
8600 function shr64_lo(ah, al, num) {
8601 var r = (ah << (32 - num)) | (al >>> num);
8602 return r >>> 0;
8603 }
8604 var shr64_lo_1 = shr64_lo;
8605
8606 var utils = {
8607 inherits: inherits_1,
8608 toArray: toArray_1,
8609 toHex: toHex_1,
8610 htonl: htonl_1,
8611 toHex32: toHex32_1,
8612 zero2: zero2_1,
8613 zero8: zero8_1,
8614 join32: join32_1,
8615 split32: split32_1,
8616 rotr32: rotr32_1,
8617 rotl32: rotl32_1,
8618 sum32: sum32_1,
8619 sum32_3: sum32_3_1,
8620 sum32_4: sum32_4_1,
8621 sum32_5: sum32_5_1,
8622 sum64: sum64_1,
8623 sum64_hi: sum64_hi_1,
8624 sum64_lo: sum64_lo_1,
8625 sum64_4_hi: sum64_4_hi_1,
8626 sum64_4_lo: sum64_4_lo_1,
8627 sum64_5_hi: sum64_5_hi_1,
8628 sum64_5_lo: sum64_5_lo_1,
8629 rotr64_hi: rotr64_hi_1,
8630 rotr64_lo: rotr64_lo_1,
8631 shr64_hi: shr64_hi_1,
8632 shr64_lo: shr64_lo_1
8633 };
8634
8635 function BlockHash() {
8636 this.pending = null;
8637 this.pendingTotal = 0;
8638 this.blockSize = this.constructor.blockSize;
8639 this.outSize = this.constructor.outSize;
8640 this.hmacStrength = this.constructor.hmacStrength;
8641 this.padLength = this.constructor.padLength / 8;
8642 this.endian = 'big';
8643
8644 this._delta8 = this.blockSize / 8;
8645 this._delta32 = this.blockSize / 32;
8646 }
8647 var BlockHash_1 = BlockHash;
8648
8649 BlockHash.prototype.update = function update(msg, enc) {
8650 // Convert message to array, pad it, and join into 32bit blocks
8651 msg = utils.toArray(msg, enc);
8652 if (!this.pending)
8653 this.pending = msg;
8654 else
8655 this.pending = this.pending.concat(msg);
8656 this.pendingTotal += msg.length;
8657
8658 // Enough data, try updating
8659 if (this.pending.length >= this._delta8) {
8660 msg = this.pending;
8661
8662 // Process pending data in blocks
8663 var r = msg.length % this._delta8;
8664 this.pending = msg.slice(msg.length - r, msg.length);
8665 if (this.pending.length === 0)
8666 this.pending = null;
8667
8668 msg = utils.join32(msg, 0, msg.length - r, this.endian);
8669 for (var i = 0; i < msg.length; i += this._delta32)
8670 this._update(msg, i, i + this._delta32);
8671 }
8672
8673 return this;
8674 };
8675
8676 BlockHash.prototype.digest = function digest(enc) {
8677 this.update(this._pad());
8678 minimalisticAssert(this.pending === null);
8679
8680 return this._digest(enc);
8681 };
8682
8683 BlockHash.prototype._pad = function pad() {
8684 var len = this.pendingTotal;
8685 var bytes = this._delta8;
8686 var k = bytes - ((len + this.padLength) % bytes);
8687 var res = new Array(k + this.padLength);
8688 res[0] = 0x80;
8689 for (var i = 1; i < k; i++)
8690 res[i] = 0;
8691
8692 // Append length
8693 len <<= 3;
8694 if (this.endian === 'big') {
8695 for (var t = 8; t < this.padLength; t++)
8696 res[i++] = 0;
8697
8698 res[i++] = 0;
8699 res[i++] = 0;
8700 res[i++] = 0;
8701 res[i++] = 0;
8702 res[i++] = (len >>> 24) & 0xff;
8703 res[i++] = (len >>> 16) & 0xff;
8704 res[i++] = (len >>> 8) & 0xff;
8705 res[i++] = len & 0xff;
8706 } else {
8707 res[i++] = len & 0xff;
8708 res[i++] = (len >>> 8) & 0xff;
8709 res[i++] = (len >>> 16) & 0xff;
8710 res[i++] = (len >>> 24) & 0xff;
8711 res[i++] = 0;
8712 res[i++] = 0;
8713 res[i++] = 0;
8714 res[i++] = 0;
8715
8716 for (t = 8; t < this.padLength; t++)
8717 res[i++] = 0;
8718 }
8719
8720 return res;
8721 };
8722
8723 var common = {
8724 BlockHash: BlockHash_1
8725 };
8726
8727 var rotr32$1 = utils.rotr32;
8728
8729 function ft_1(s, x, y, z) {
8730 if (s === 0)
8731 return ch32(x, y, z);
8732 if (s === 1 || s === 3)
8733 return p32(x, y, z);
8734 if (s === 2)
8735 return maj32(x, y, z);
8736 }
8737 var ft_1_1 = ft_1;
8738
8739 function ch32(x, y, z) {
8740 return (x & y) ^ ((~x) & z);
8741 }
8742 var ch32_1 = ch32;
8743
8744 function maj32(x, y, z) {
8745 return (x & y) ^ (x & z) ^ (y & z);
8746 }
8747 var maj32_1 = maj32;
8748
8749 function p32(x, y, z) {
8750 return x ^ y ^ z;
8751 }
8752 var p32_1 = p32;
8753
8754 function s0_256(x) {
8755 return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22);
8756 }
8757 var s0_256_1 = s0_256;
8758
8759 function s1_256(x) {
8760 return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25);
8761 }
8762 var s1_256_1 = s1_256;
8763
8764 function g0_256(x) {
8765 return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3);
8766 }
8767 var g0_256_1 = g0_256;
8768
8769 function g1_256(x) {
8770 return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10);
8771 }
8772 var g1_256_1 = g1_256;
8773
8774 var common$1 = {
8775 ft_1: ft_1_1,
8776 ch32: ch32_1,
8777 maj32: maj32_1,
8778 p32: p32_1,
8779 s0_256: s0_256_1,
8780 s1_256: s1_256_1,
8781 g0_256: g0_256_1,
8782 g1_256: g1_256_1
8783 };
8784
8785 var sum32$1 = utils.sum32;
8786 var sum32_4$1 = utils.sum32_4;
8787 var sum32_5$1 = utils.sum32_5;
8788 var ch32$1 = common$1.ch32;
8789 var maj32$1 = common$1.maj32;
8790 var s0_256$1 = common$1.s0_256;
8791 var s1_256$1 = common$1.s1_256;
8792 var g0_256$1 = common$1.g0_256;
8793 var g1_256$1 = common$1.g1_256;
8794
8795 var BlockHash$1 = common.BlockHash;
8796
8797 var sha256_K = [
8798 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
8799 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
8800 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
8801 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
8802 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
8803 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
8804 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
8805 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
8806 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
8807 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
8808 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
8809 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
8810 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
8811 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
8812 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
8813 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
8814 ];
8815
8816 function SHA256() {
8817 if (!(this instanceof SHA256))
8818 return new SHA256();
8819
8820 BlockHash$1.call(this);
8821 this.h = [
8822 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
8823 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
8824 ];
8825 this.k = sha256_K;
8826 this.W = new Array(64);
8827 }
8828 utils.inherits(SHA256, BlockHash$1);
8829 var _256 = SHA256;
8830
8831 SHA256.blockSize = 512;
8832 SHA256.outSize = 256;
8833 SHA256.hmacStrength = 192;
8834 SHA256.padLength = 64;
8835
8836 SHA256.prototype._update = function _update(msg, start) {
8837 var W = this.W;
8838
8839 for (var i = 0; i < 16; i++)
8840 W[i] = msg[start + i];
8841 for (; i < W.length; i++)
8842 W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]);
8843
8844 var a = this.h[0];
8845 var b = this.h[1];
8846 var c = this.h[2];
8847 var d = this.h[3];
8848 var e = this.h[4];
8849 var f = this.h[5];
8850 var g = this.h[6];
8851 var h = this.h[7];
8852
8853 minimalisticAssert(this.k.length === W.length);
8854 for (i = 0; i < W.length; i++) {
8855 var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]);
8856 var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c));
8857 h = g;
8858 g = f;
8859 f = e;
8860 e = sum32$1(d, T1);
8861 d = c;
8862 c = b;
8863 b = a;
8864 a = sum32$1(T1, T2);
8865 }
8866
8867 this.h[0] = sum32$1(this.h[0], a);
8868 this.h[1] = sum32$1(this.h[1], b);
8869 this.h[2] = sum32$1(this.h[2], c);
8870 this.h[3] = sum32$1(this.h[3], d);
8871 this.h[4] = sum32$1(this.h[4], e);
8872 this.h[5] = sum32$1(this.h[5], f);
8873 this.h[6] = sum32$1(this.h[6], g);
8874 this.h[7] = sum32$1(this.h[7], h);
8875 };
8876
8877 SHA256.prototype._digest = function digest(enc) {
8878 if (enc === 'hex')
8879 return utils.toHex32(this.h, 'big');
8880 else
8881 return utils.split32(this.h, 'big');
8882 };
8883
8884 function SHA224() {
8885 if (!(this instanceof SHA224))
8886 return new SHA224();
8887
8888 _256.call(this);
8889 this.h = [
8890 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
8891 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
8892 }
8893 utils.inherits(SHA224, _256);
8894 var _224 = SHA224;
8895
8896 SHA224.blockSize = 512;
8897 SHA224.outSize = 224;
8898 SHA224.hmacStrength = 192;
8899 SHA224.padLength = 64;
8900
8901 SHA224.prototype._digest = function digest(enc) {
8902 // Just truncate output
8903 if (enc === 'hex')
8904 return utils.toHex32(this.h.slice(0, 7), 'big');
8905 else
8906 return utils.split32(this.h.slice(0, 7), 'big');
8907 };
8908
8909 var rotr64_hi$1 = utils.rotr64_hi;
8910 var rotr64_lo$1 = utils.rotr64_lo;
8911 var shr64_hi$1 = utils.shr64_hi;
8912 var shr64_lo$1 = utils.shr64_lo;
8913 var sum64$1 = utils.sum64;
8914 var sum64_hi$1 = utils.sum64_hi;
8915 var sum64_lo$1 = utils.sum64_lo;
8916 var sum64_4_hi$1 = utils.sum64_4_hi;
8917 var sum64_4_lo$1 = utils.sum64_4_lo;
8918 var sum64_5_hi$1 = utils.sum64_5_hi;
8919 var sum64_5_lo$1 = utils.sum64_5_lo;
8920
8921 var BlockHash$2 = common.BlockHash;
8922
8923 var sha512_K = [
8924 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
8925 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
8926 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
8927 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
8928 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
8929 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
8930 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
8931 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
8932 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
8933 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
8934 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
8935 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
8936 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
8937 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
8938 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
8939 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
8940 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
8941 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
8942 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
8943 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
8944 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
8945 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
8946 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
8947 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
8948 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
8949 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
8950 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
8951 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
8952 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
8953 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
8954 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
8955 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
8956 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
8957 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
8958 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
8959 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
8960 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
8961 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
8962 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
8963 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
8964 ];
8965
8966 function SHA512() {
8967 if (!(this instanceof SHA512))
8968 return new SHA512();
8969
8970 BlockHash$2.call(this);
8971 this.h = [
8972 0x6a09e667, 0xf3bcc908,
8973 0xbb67ae85, 0x84caa73b,
8974 0x3c6ef372, 0xfe94f82b,
8975 0xa54ff53a, 0x5f1d36f1,
8976 0x510e527f, 0xade682d1,
8977 0x9b05688c, 0x2b3e6c1f,
8978 0x1f83d9ab, 0xfb41bd6b,
8979 0x5be0cd19, 0x137e2179 ];
8980 this.k = sha512_K;
8981 this.W = new Array(160);
8982 }
8983 utils.inherits(SHA512, BlockHash$2);
8984 var _512 = SHA512;
8985
8986 SHA512.blockSize = 1024;
8987 SHA512.outSize = 512;
8988 SHA512.hmacStrength = 192;
8989 SHA512.padLength = 128;
8990
8991 SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
8992 var W = this.W;
8993
8994 // 32 x 32bit words
8995 for (var i = 0; i < 32; i++)
8996 W[i] = msg[start + i];
8997 for (; i < W.length; i += 2) {
8998 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
8999 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
9000 var c1_hi = W[i - 14]; // i - 7
9001 var c1_lo = W[i - 13];
9002 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
9003 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
9004 var c3_hi = W[i - 32]; // i - 16
9005 var c3_lo = W[i - 31];
9006
9007 W[i] = sum64_4_hi$1(
9008 c0_hi, c0_lo,
9009 c1_hi, c1_lo,
9010 c2_hi, c2_lo,
9011 c3_hi, c3_lo);
9012 W[i + 1] = sum64_4_lo$1(
9013 c0_hi, c0_lo,
9014 c1_hi, c1_lo,
9015 c2_hi, c2_lo,
9016 c3_hi, c3_lo);
9017 }
9018 };
9019
9020 SHA512.prototype._update = function _update(msg, start) {
9021 this._prepareBlock(msg, start);
9022
9023 var W = this.W;
9024
9025 var ah = this.h[0];
9026 var al = this.h[1];
9027 var bh = this.h[2];
9028 var bl = this.h[3];
9029 var ch = this.h[4];
9030 var cl = this.h[5];
9031 var dh = this.h[6];
9032 var dl = this.h[7];
9033 var eh = this.h[8];
9034 var el = this.h[9];
9035 var fh = this.h[10];
9036 var fl = this.h[11];
9037 var gh = this.h[12];
9038 var gl = this.h[13];
9039 var hh = this.h[14];
9040 var hl = this.h[15];
9041
9042 minimalisticAssert(this.k.length === W.length);
9043 for (var i = 0; i < W.length; i += 2) {
9044 var c0_hi = hh;
9045 var c0_lo = hl;
9046 var c1_hi = s1_512_hi(eh, el);
9047 var c1_lo = s1_512_lo(eh, el);
9048 var c2_hi = ch64_hi(eh, el, fh, fl, gh);
9049 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
9050 var c3_hi = this.k[i];
9051 var c3_lo = this.k[i + 1];
9052 var c4_hi = W[i];
9053 var c4_lo = W[i + 1];
9054
9055 var T1_hi = sum64_5_hi$1(
9056 c0_hi, c0_lo,
9057 c1_hi, c1_lo,
9058 c2_hi, c2_lo,
9059 c3_hi, c3_lo,
9060 c4_hi, c4_lo);
9061 var T1_lo = sum64_5_lo$1(
9062 c0_hi, c0_lo,
9063 c1_hi, c1_lo,
9064 c2_hi, c2_lo,
9065 c3_hi, c3_lo,
9066 c4_hi, c4_lo);
9067
9068 c0_hi = s0_512_hi(ah, al);
9069 c0_lo = s0_512_lo(ah, al);
9070 c1_hi = maj64_hi(ah, al, bh, bl, ch);
9071 c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
9072
9073 var T2_hi = sum64_hi$1(c0_hi, c0_lo, c1_hi, c1_lo);
9074 var T2_lo = sum64_lo$1(c0_hi, c0_lo, c1_hi, c1_lo);
9075
9076 hh = gh;
9077 hl = gl;
9078
9079 gh = fh;
9080 gl = fl;
9081
9082 fh = eh;
9083 fl = el;
9084
9085 eh = sum64_hi$1(dh, dl, T1_hi, T1_lo);
9086 el = sum64_lo$1(dl, dl, T1_hi, T1_lo);
9087
9088 dh = ch;
9089 dl = cl;
9090
9091 ch = bh;
9092 cl = bl;
9093
9094 bh = ah;
9095 bl = al;
9096
9097 ah = sum64_hi$1(T1_hi, T1_lo, T2_hi, T2_lo);
9098 al = sum64_lo$1(T1_hi, T1_lo, T2_hi, T2_lo);
9099 }
9100
9101 sum64$1(this.h, 0, ah, al);
9102 sum64$1(this.h, 2, bh, bl);
9103 sum64$1(this.h, 4, ch, cl);
9104 sum64$1(this.h, 6, dh, dl);
9105 sum64$1(this.h, 8, eh, el);
9106 sum64$1(this.h, 10, fh, fl);
9107 sum64$1(this.h, 12, gh, gl);
9108 sum64$1(this.h, 14, hh, hl);
9109 };
9110
9111 SHA512.prototype._digest = function digest(enc) {
9112 if (enc === 'hex')
9113 return utils.toHex32(this.h, 'big');
9114 else
9115 return utils.split32(this.h, 'big');
9116 };
9117
9118 function ch64_hi(xh, xl, yh, yl, zh) {
9119 var r = (xh & yh) ^ ((~xh) & zh);
9120 if (r < 0)
9121 r += 0x100000000;
9122 return r;
9123 }
9124
9125 function ch64_lo(xh, xl, yh, yl, zh, zl) {
9126 var r = (xl & yl) ^ ((~xl) & zl);
9127 if (r < 0)
9128 r += 0x100000000;
9129 return r;
9130 }
9131
9132 function maj64_hi(xh, xl, yh, yl, zh) {
9133 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
9134 if (r < 0)
9135 r += 0x100000000;
9136 return r;
9137 }
9138
9139 function maj64_lo(xh, xl, yh, yl, zh, zl) {
9140 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
9141 if (r < 0)
9142 r += 0x100000000;
9143 return r;
9144 }
9145
9146 function s0_512_hi(xh, xl) {
9147 var c0_hi = rotr64_hi$1(xh, xl, 28);
9148 var c1_hi = rotr64_hi$1(xl, xh, 2); // 34
9149 var c2_hi = rotr64_hi$1(xl, xh, 7); // 39
9150
9151 var r = c0_hi ^ c1_hi ^ c2_hi;
9152 if (r < 0)
9153 r += 0x100000000;
9154 return r;
9155 }
9156
9157 function s0_512_lo(xh, xl) {
9158 var c0_lo = rotr64_lo$1(xh, xl, 28);
9159 var c1_lo = rotr64_lo$1(xl, xh, 2); // 34
9160 var c2_lo = rotr64_lo$1(xl, xh, 7); // 39
9161
9162 var r = c0_lo ^ c1_lo ^ c2_lo;
9163 if (r < 0)
9164 r += 0x100000000;
9165 return r;
9166 }
9167
9168 function s1_512_hi(xh, xl) {
9169 var c0_hi = rotr64_hi$1(xh, xl, 14);
9170 var c1_hi = rotr64_hi$1(xh, xl, 18);
9171 var c2_hi = rotr64_hi$1(xl, xh, 9); // 41
9172
9173 var r = c0_hi ^ c1_hi ^ c2_hi;
9174 if (r < 0)
9175 r += 0x100000000;
9176 return r;
9177 }
9178
9179 function s1_512_lo(xh, xl) {
9180 var c0_lo = rotr64_lo$1(xh, xl, 14);
9181 var c1_lo = rotr64_lo$1(xh, xl, 18);
9182 var c2_lo = rotr64_lo$1(xl, xh, 9); // 41
9183
9184 var r = c0_lo ^ c1_lo ^ c2_lo;
9185 if (r < 0)
9186 r += 0x100000000;
9187 return r;
9188 }
9189
9190 function g0_512_hi(xh, xl) {
9191 var c0_hi = rotr64_hi$1(xh, xl, 1);
9192 var c1_hi = rotr64_hi$1(xh, xl, 8);
9193 var c2_hi = shr64_hi$1(xh, xl, 7);
9194
9195 var r = c0_hi ^ c1_hi ^ c2_hi;
9196 if (r < 0)
9197 r += 0x100000000;
9198 return r;
9199 }
9200
9201 function g0_512_lo(xh, xl) {
9202 var c0_lo = rotr64_lo$1(xh, xl, 1);
9203 var c1_lo = rotr64_lo$1(xh, xl, 8);
9204 var c2_lo = shr64_lo$1(xh, xl, 7);
9205
9206 var r = c0_lo ^ c1_lo ^ c2_lo;
9207 if (r < 0)
9208 r += 0x100000000;
9209 return r;
9210 }
9211
9212 function g1_512_hi(xh, xl) {
9213 var c0_hi = rotr64_hi$1(xh, xl, 19);
9214 var c1_hi = rotr64_hi$1(xl, xh, 29); // 61
9215 var c2_hi = shr64_hi$1(xh, xl, 6);
9216
9217 var r = c0_hi ^ c1_hi ^ c2_hi;
9218 if (r < 0)
9219 r += 0x100000000;
9220 return r;
9221 }
9222
9223 function g1_512_lo(xh, xl) {
9224 var c0_lo = rotr64_lo$1(xh, xl, 19);
9225 var c1_lo = rotr64_lo$1(xl, xh, 29); // 61
9226 var c2_lo = shr64_lo$1(xh, xl, 6);
9227
9228 var r = c0_lo ^ c1_lo ^ c2_lo;
9229 if (r < 0)
9230 r += 0x100000000;
9231 return r;
9232 }
9233
9234 function SHA384() {
9235 if (!(this instanceof SHA384))
9236 return new SHA384();
9237
9238 _512.call(this);
9239 this.h = [
9240 0xcbbb9d5d, 0xc1059ed8,
9241 0x629a292a, 0x367cd507,
9242 0x9159015a, 0x3070dd17,
9243 0x152fecd8, 0xf70e5939,
9244 0x67332667, 0xffc00b31,
9245 0x8eb44a87, 0x68581511,
9246 0xdb0c2e0d, 0x64f98fa7,
9247 0x47b5481d, 0xbefa4fa4 ];
9248 }
9249 utils.inherits(SHA384, _512);
9250 var _384 = SHA384;
9251
9252 SHA384.blockSize = 1024;
9253 SHA384.outSize = 384;
9254 SHA384.hmacStrength = 192;
9255 SHA384.padLength = 128;
9256
9257 SHA384.prototype._digest = function digest(enc) {
9258 if (enc === 'hex')
9259 return utils.toHex32(this.h.slice(0, 12), 'big');
9260 else
9261 return utils.split32(this.h.slice(0, 12), 'big');
9262 };
9263
9264 var rotl32$1 = utils.rotl32;
9265 var sum32$2 = utils.sum32;
9266 var sum32_3$1 = utils.sum32_3;
9267 var sum32_4$2 = utils.sum32_4;
9268 var BlockHash$3 = common.BlockHash;
9269
9270 function RIPEMD160() {
9271 if (!(this instanceof RIPEMD160))
9272 return new RIPEMD160();
9273
9274 BlockHash$3.call(this);
9275
9276 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
9277 this.endian = 'little';
9278 }
9279 utils.inherits(RIPEMD160, BlockHash$3);
9280 var ripemd160 = RIPEMD160;
9281
9282 RIPEMD160.blockSize = 512;
9283 RIPEMD160.outSize = 160;
9284 RIPEMD160.hmacStrength = 192;
9285 RIPEMD160.padLength = 64;
9286
9287 RIPEMD160.prototype._update = function update(msg, start) {
9288 var A = this.h[0];
9289 var B = this.h[1];
9290 var C = this.h[2];
9291 var D = this.h[3];
9292 var E = this.h[4];
9293 var Ah = A;
9294 var Bh = B;
9295 var Ch = C;
9296 var Dh = D;
9297 var Eh = E;
9298 for (var j = 0; j < 80; j++) {
9299 var T = sum32$2(
9300 rotl32$1(
9301 sum32_4$2(A, f(j, B, C, D), msg[r[j] + start], K(j)),
9302 s[j]),
9303 E);
9304 A = E;
9305 E = D;
9306 D = rotl32$1(C, 10);
9307 C = B;
9308 B = T;
9309 T = sum32$2(
9310 rotl32$1(
9311 sum32_4$2(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
9312 sh[j]),
9313 Eh);
9314 Ah = Eh;
9315 Eh = Dh;
9316 Dh = rotl32$1(Ch, 10);
9317 Ch = Bh;
9318 Bh = T;
9319 }
9320 T = sum32_3$1(this.h[1], C, Dh);
9321 this.h[1] = sum32_3$1(this.h[2], D, Eh);
9322 this.h[2] = sum32_3$1(this.h[3], E, Ah);
9323 this.h[3] = sum32_3$1(this.h[4], A, Bh);
9324 this.h[4] = sum32_3$1(this.h[0], B, Ch);
9325 this.h[0] = T;
9326 };
9327
9328 RIPEMD160.prototype._digest = function digest(enc) {
9329 if (enc === 'hex')
9330 return utils.toHex32(this.h, 'little');
9331 else
9332 return utils.split32(this.h, 'little');
9333 };
9334
9335 function f(j, x, y, z) {
9336 if (j <= 15)
9337 return x ^ y ^ z;
9338 else if (j <= 31)
9339 return (x & y) | ((~x) & z);
9340 else if (j <= 47)
9341 return (x | (~y)) ^ z;
9342 else if (j <= 63)
9343 return (x & z) | (y & (~z));
9344 else
9345 return x ^ (y | (~z));
9346 }
9347
9348 function K(j) {
9349 if (j <= 15)
9350 return 0x00000000;
9351 else if (j <= 31)
9352 return 0x5a827999;
9353 else if (j <= 47)
9354 return 0x6ed9eba1;
9355 else if (j <= 63)
9356 return 0x8f1bbcdc;
9357 else
9358 return 0xa953fd4e;
9359 }
9360
9361 function Kh(j) {
9362 if (j <= 15)
9363 return 0x50a28be6;
9364 else if (j <= 31)
9365 return 0x5c4dd124;
9366 else if (j <= 47)
9367 return 0x6d703ef3;
9368 else if (j <= 63)
9369 return 0x7a6d76e9;
9370 else
9371 return 0x00000000;
9372 }
9373
9374 var r = [
9375 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
9376 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
9377 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
9378 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
9379 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
9380 ];
9381
9382 var rh = [
9383 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
9384 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
9385 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
9386 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
9387 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
9388 ];
9389
9390 var s = [
9391 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
9392 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
9393 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
9394 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9395 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
9396 ];
9397
9398 var sh = [
9399 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9400 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9401 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
9402 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
9403 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
9404 ];
9405
9406 var ripemd = {
9407 ripemd160: ripemd160
9408 };
9409
9410 /**
9411 * A fast MD5 JavaScript implementation
9412 * Copyright (c) 2012 Joseph Myers
9413 * http://www.myersdaily.org/joseph/javascript/md5-text.html
9414 *
9415 * Permission to use, copy, modify, and distribute this software
9416 * and its documentation for any purposes and without
9417 * fee is hereby granted provided that this copyright notice
9418 * appears in all copies.
9419 *
9420 * Of course, this soft is provided "as is" without express or implied
9421 * warranty of any kind.
9422 */
9423
9424 // MD5 Digest
9425 async function md5(entree) {
9426 const digest = md51(util.uint8ArrayToString(entree));
9427 return util.hexToUint8Array(hex(digest));
9428 }
9429
9430 function md5cycle(x, k) {
9431 let a = x[0];
9432 let b = x[1];
9433 let c = x[2];
9434 let d = x[3];
9435
9436 a = ff(a, b, c, d, k[0], 7, -680876936);
9437 d = ff(d, a, b, c, k[1], 12, -389564586);
9438 c = ff(c, d, a, b, k[2], 17, 606105819);
9439 b = ff(b, c, d, a, k[3], 22, -1044525330);
9440 a = ff(a, b, c, d, k[4], 7, -176418897);
9441 d = ff(d, a, b, c, k[5], 12, 1200080426);
9442 c = ff(c, d, a, b, k[6], 17, -1473231341);
9443 b = ff(b, c, d, a, k[7], 22, -45705983);
9444 a = ff(a, b, c, d, k[8], 7, 1770035416);
9445 d = ff(d, a, b, c, k[9], 12, -1958414417);
9446 c = ff(c, d, a, b, k[10], 17, -42063);
9447 b = ff(b, c, d, a, k[11], 22, -1990404162);
9448 a = ff(a, b, c, d, k[12], 7, 1804603682);
9449 d = ff(d, a, b, c, k[13], 12, -40341101);
9450 c = ff(c, d, a, b, k[14], 17, -1502002290);
9451 b = ff(b, c, d, a, k[15], 22, 1236535329);
9452
9453 a = gg(a, b, c, d, k[1], 5, -165796510);
9454 d = gg(d, a, b, c, k[6], 9, -1069501632);
9455 c = gg(c, d, a, b, k[11], 14, 643717713);
9456 b = gg(b, c, d, a, k[0], 20, -373897302);
9457 a = gg(a, b, c, d, k[5], 5, -701558691);
9458 d = gg(d, a, b, c, k[10], 9, 38016083);
9459 c = gg(c, d, a, b, k[15], 14, -660478335);
9460 b = gg(b, c, d, a, k[4], 20, -405537848);
9461 a = gg(a, b, c, d, k[9], 5, 568446438);
9462 d = gg(d, a, b, c, k[14], 9, -1019803690);
9463 c = gg(c, d, a, b, k[3], 14, -187363961);
9464 b = gg(b, c, d, a, k[8], 20, 1163531501);
9465 a = gg(a, b, c, d, k[13], 5, -1444681467);
9466 d = gg(d, a, b, c, k[2], 9, -51403784);
9467 c = gg(c, d, a, b, k[7], 14, 1735328473);
9468 b = gg(b, c, d, a, k[12], 20, -1926607734);
9469
9470 a = hh(a, b, c, d, k[5], 4, -378558);
9471 d = hh(d, a, b, c, k[8], 11, -2022574463);
9472 c = hh(c, d, a, b, k[11], 16, 1839030562);
9473 b = hh(b, c, d, a, k[14], 23, -35309556);
9474 a = hh(a, b, c, d, k[1], 4, -1530992060);
9475 d = hh(d, a, b, c, k[4], 11, 1272893353);
9476 c = hh(c, d, a, b, k[7], 16, -155497632);
9477 b = hh(b, c, d, a, k[10], 23, -1094730640);
9478 a = hh(a, b, c, d, k[13], 4, 681279174);
9479 d = hh(d, a, b, c, k[0], 11, -358537222);
9480 c = hh(c, d, a, b, k[3], 16, -722521979);
9481 b = hh(b, c, d, a, k[6], 23, 76029189);
9482 a = hh(a, b, c, d, k[9], 4, -640364487);
9483 d = hh(d, a, b, c, k[12], 11, -421815835);
9484 c = hh(c, d, a, b, k[15], 16, 530742520);
9485 b = hh(b, c, d, a, k[2], 23, -995338651);
9486
9487 a = ii(a, b, c, d, k[0], 6, -198630844);
9488 d = ii(d, a, b, c, k[7], 10, 1126891415);
9489 c = ii(c, d, a, b, k[14], 15, -1416354905);
9490 b = ii(b, c, d, a, k[5], 21, -57434055);
9491 a = ii(a, b, c, d, k[12], 6, 1700485571);
9492 d = ii(d, a, b, c, k[3], 10, -1894986606);
9493 c = ii(c, d, a, b, k[10], 15, -1051523);
9494 b = ii(b, c, d, a, k[1], 21, -2054922799);
9495 a = ii(a, b, c, d, k[8], 6, 1873313359);
9496 d = ii(d, a, b, c, k[15], 10, -30611744);
9497 c = ii(c, d, a, b, k[6], 15, -1560198380);
9498 b = ii(b, c, d, a, k[13], 21, 1309151649);
9499 a = ii(a, b, c, d, k[4], 6, -145523070);
9500 d = ii(d, a, b, c, k[11], 10, -1120210379);
9501 c = ii(c, d, a, b, k[2], 15, 718787259);
9502 b = ii(b, c, d, a, k[9], 21, -343485551);
9503
9504 x[0] = add32(a, x[0]);
9505 x[1] = add32(b, x[1]);
9506 x[2] = add32(c, x[2]);
9507 x[3] = add32(d, x[3]);
9508 }
9509
9510 function cmn(q, a, b, x, s, t) {
9511 a = add32(add32(a, q), add32(x, t));
9512 return add32((a << s) | (a >>> (32 - s)), b);
9513 }
9514
9515 function ff(a, b, c, d, x, s, t) {
9516 return cmn((b & c) | ((~b) & d), a, b, x, s, t);
9517 }
9518
9519 function gg(a, b, c, d, x, s, t) {
9520 return cmn((b & d) | (c & (~d)), a, b, x, s, t);
9521 }
9522
9523 function hh(a, b, c, d, x, s, t) {
9524 return cmn(b ^ c ^ d, a, b, x, s, t);
9525 }
9526
9527 function ii(a, b, c, d, x, s, t) {
9528 return cmn(c ^ (b | (~d)), a, b, x, s, t);
9529 }
9530
9531 function md51(s) {
9532 const n = s.length;
9533 const state = [1732584193, -271733879, -1732584194, 271733878];
9534 let i;
9535 for (i = 64; i <= s.length; i += 64) {
9536 md5cycle(state, md5blk(s.substring(i - 64, i)));
9537 }
9538 s = s.substring(i - 64);
9539 const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
9540 for (i = 0; i < s.length; i++) {
9541 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
9542 }
9543 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
9544 if (i > 55) {
9545 md5cycle(state, tail);
9546 for (i = 0; i < 16; i++) {
9547 tail[i] = 0;
9548 }
9549 }
9550 tail[14] = n * 8;
9551 md5cycle(state, tail);
9552 return state;
9553 }
9554
9555 /* there needs to be support for Unicode here,
9556 * unless we pretend that we can redefine the MD-5
9557 * algorithm for multi-byte characters (perhaps
9558 * by adding every four 16-bit characters and
9559 * shortening the sum to 32 bits). Otherwise
9560 * I suggest performing MD-5 as if every character
9561 * was two bytes--e.g., 0040 0025 = @%--but then
9562 * how will an ordinary MD-5 sum be matched?
9563 * There is no way to standardize text to something
9564 * like UTF-8 before transformation; speed cost is
9565 * utterly prohibitive. The JavaScript standard
9566 * itself needs to look at this: it should start
9567 * providing access to strings as preformed UTF-8
9568 * 8-bit unsigned value arrays.
9569 */
9570 function md5blk(s) { /* I figured global was faster. */
9571 const md5blks = [];
9572 let i; /* Andy King said do it this way. */
9573 for (i = 0; i < 64; i += 4) {
9574 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) <<
9575 24);
9576 }
9577 return md5blks;
9578 }
9579
9580 const hex_chr = '0123456789abcdef'.split('');
9581
9582 function rhex(n) {
9583 let s = '';
9584 let j = 0;
9585 for (; j < 4; j++) {
9586 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
9587 }
9588 return s;
9589 }
9590
9591 function hex(x) {
9592 for (let i = 0; i < x.length; i++) {
9593 x[i] = rhex(x[i]);
9594 }
9595 return x.join('');
9596 }
9597
9598 /* this function is much faster,
9599 so if possible we use it. Some IEs
9600 are the only ones I know of that
9601 need the idiotic second function,
9602 generated by an if clause. */
9603
9604 function add32(a, b) {
9605 return (a + b) & 0xFFFFFFFF;
9606 }
9607
9608 /**
9609 * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.
9610 * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
9611 * @see {@link https://github.com/indutny/hash.js|hash.js}
9612 * @module crypto/hash
9613 * @private
9614 */
9615
9616 const webCrypto = util.getWebCrypto();
9617 const nodeCrypto = util.getNodeCrypto();
9618
9619 function nodeHash(type) {
9620 return async function (data) {
9621 const shasum = nodeCrypto.createHash(type);
9622 return transform(data, value => {
9623 shasum.update(value);
9624 }, () => new Uint8Array(shasum.digest()));
9625 };
9626 }
9627
9628 function hashjsHash(hash, webCryptoHash) {
9629 return async function(data, config = defaultConfig) {
9630 if (isArrayStream(data)) {
9631 data = await readToEnd(data);
9632 }
9633 if (!util.isStream(data) && webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {
9634 return new Uint8Array(await webCrypto.digest(webCryptoHash, data));
9635 }
9636 const hashInstance = hash();
9637 return transform(data, value => {
9638 hashInstance.update(value);
9639 }, () => new Uint8Array(hashInstance.digest()));
9640 };
9641 }
9642
9643 function asmcryptoHash(hash, webCryptoHash) {
9644 return async function(data, config = defaultConfig) {
9645 if (isArrayStream(data)) {
9646 data = await readToEnd(data);
9647 }
9648 if (util.isStream(data)) {
9649 const hashInstance = new hash();
9650 return transform(data, value => {
9651 hashInstance.process(value);
9652 }, () => hashInstance.finish().result);
9653 } else if (webCrypto && webCryptoHash && data.length >= config.minBytesForWebCrypto) {
9654 return new Uint8Array(await webCrypto.digest(webCryptoHash, data));
9655 } else {
9656 return hash.bytes(data);
9657 }
9658 };
9659 }
9660
9661 let hashFunctions;
9662 if (nodeCrypto) { // Use Node native crypto for all hash functions
9663 hashFunctions = {
9664 md5: nodeHash('md5'),
9665 sha1: nodeHash('sha1'),
9666 sha224: nodeHash('sha224'),
9667 sha256: nodeHash('sha256'),
9668 sha384: nodeHash('sha384'),
9669 sha512: nodeHash('sha512'),
9670 ripemd: nodeHash('ripemd160')
9671 };
9672 } else { // Use JS fallbacks
9673 hashFunctions = {
9674 md5: md5,
9675 sha1: asmcryptoHash(Sha1, navigator.userAgent.indexOf('Edge') === -1 && 'SHA-1'),
9676 sha224: hashjsHash(_224),
9677 sha256: asmcryptoHash(Sha256, 'SHA-256'),
9678 sha384: hashjsHash(_384, 'SHA-384'),
9679 sha512: hashjsHash(_512, 'SHA-512'), // asmcrypto sha512 is huge.
9680 ripemd: hashjsHash(ripemd160)
9681 };
9682 }
9683
9684 var hash = {
9685
9686 /** @see module:md5 */
9687 md5: hashFunctions.md5,
9688 /** @see asmCrypto */
9689 sha1: hashFunctions.sha1,
9690 /** @see hash.js */
9691 sha224: hashFunctions.sha224,
9692 /** @see asmCrypto */
9693 sha256: hashFunctions.sha256,
9694 /** @see hash.js */
9695 sha384: hashFunctions.sha384,
9696 /** @see asmCrypto */
9697 sha512: hashFunctions.sha512,
9698 /** @see hash.js */
9699 ripemd: hashFunctions.ripemd,
9700
9701 /**
9702 * Create a hash on the specified data using the specified algorithm
9703 * @param {module:enums.hash} algo - Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
9704 * @param {Uint8Array} data - Data to be hashed
9705 * @returns {Promise<Uint8Array>} Hash value.
9706 */
9707 digest: function(algo, data) {
9708 switch (algo) {
9709 case 1:
9710 // - MD5 [HAC]
9711 return this.md5(data);
9712 case 2:
9713 // - SHA-1 [FIPS180]
9714 return this.sha1(data);
9715 case 3:
9716 // - RIPE-MD/160 [HAC]
9717 return this.ripemd(data);
9718 case 8:
9719 // - SHA256 [FIPS180]
9720 return this.sha256(data);
9721 case 9:
9722 // - SHA384 [FIPS180]
9723 return this.sha384(data);
9724 case 10:
9725 // - SHA512 [FIPS180]
9726 return this.sha512(data);
9727 case 11:
9728 // - SHA224 [FIPS180]
9729 return this.sha224(data);
9730 default:
9731 throw new Error('Invalid hash function.');
9732 }
9733 },
9734
9735 /**
9736 * Returns the hash size in bytes of the specified hash algorithm type
9737 * @param {module:enums.hash} algo - Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
9738 * @returns {Integer} Size in bytes of the resulting hash.
9739 */
9740 getHashByteLength: function(algo) {
9741 switch (algo) {
9742 case 1: // - MD5 [HAC]
9743 return 16;
9744 case 2: // - SHA-1 [FIPS180]
9745 case 3: // - RIPE-MD/160 [HAC]
9746 return 20;
9747 case 8: // - SHA256 [FIPS180]
9748 return 32;
9749 case 9: // - SHA384 [FIPS180]
9750 return 48;
9751 case 10: // - SHA512 [FIPS180]
9752 return 64;
9753 case 11: // - SHA224 [FIPS180]
9754 return 28;
9755 default:
9756 throw new Error('Invalid hash algorithm.');
9757 }
9758 }
9759 };
9760
9761 class AES_CFB {
9762 static encrypt(data, key, iv) {
9763 return new AES_CFB(key, iv).encrypt(data);
9764 }
9765 static decrypt(data, key, iv) {
9766 return new AES_CFB(key, iv).decrypt(data);
9767 }
9768 constructor(key, iv, aes) {
9769 this.aes = aes ? aes : new AES(key, iv, true, 'CFB');
9770 delete this.aes.padding;
9771 }
9772 encrypt(data) {
9773 const r1 = this.aes.AES_Encrypt_process(data);
9774 const r2 = this.aes.AES_Encrypt_finish();
9775 return joinBytes(r1, r2);
9776 }
9777 decrypt(data) {
9778 const r1 = this.aes.AES_Decrypt_process(data);
9779 const r2 = this.aes.AES_Decrypt_finish();
9780 return joinBytes(r1, r2);
9781 }
9782 }
9783
9784 // Modified by ProtonTech AG
9785
9786 const webCrypto$1 = util.getWebCrypto();
9787 const nodeCrypto$1 = util.getNodeCrypto();
9788
9789 const knownAlgos = nodeCrypto$1 ? nodeCrypto$1.getCiphers() : [];
9790 const nodeAlgos = {
9791 idea: knownAlgos.includes('idea-cfb') ? 'idea-cfb' : undefined, /* Unused, not implemented */
9792 tripledes: knownAlgos.includes('des-ede3-cfb') ? 'des-ede3-cfb' : undefined,
9793 cast5: knownAlgos.includes('cast5-cfb') ? 'cast5-cfb' : undefined,
9794 blowfish: knownAlgos.includes('bf-cfb') ? 'bf-cfb' : undefined,
9795 aes128: knownAlgos.includes('aes-128-cfb') ? 'aes-128-cfb' : undefined,
9796 aes192: knownAlgos.includes('aes-192-cfb') ? 'aes-192-cfb' : undefined,
9797 aes256: knownAlgos.includes('aes-256-cfb') ? 'aes-256-cfb' : undefined
9798 /* twofish is not implemented in OpenSSL */
9799 };
9800
9801 async function encrypt(algo, key, plaintext, iv, config) {
9802 if (util.getNodeCrypto() && nodeAlgos[algo]) { // Node crypto library.
9803 return nodeEncrypt(algo, key, plaintext, iv);
9804 }
9805 if (algo.substr(0, 3) === 'aes') {
9806 return aesEncrypt(algo, key, plaintext, iv, config);
9807 }
9808
9809 const cipherfn = new cipher[algo](key);
9810 const block_size = cipherfn.blockSize;
9811
9812 const blockc = iv.slice();
9813 let pt = new Uint8Array();
9814 const process = chunk => {
9815 if (chunk) {
9816 pt = util.concatUint8Array([pt, chunk]);
9817 }
9818 const ciphertext = new Uint8Array(pt.length);
9819 let i;
9820 let j = 0;
9821 while (chunk ? pt.length >= block_size : pt.length) {
9822 const encblock = cipherfn.encrypt(blockc);
9823 for (i = 0; i < block_size; i++) {
9824 blockc[i] = pt[i] ^ encblock[i];
9825 ciphertext[j++] = blockc[i];
9826 }
9827 pt = pt.subarray(block_size);
9828 }
9829 return ciphertext.subarray(0, j);
9830 };
9831 return transform(plaintext, process, process);
9832 }
9833
9834 async function decrypt(algo, key, ciphertext, iv) {
9835 if (util.getNodeCrypto() && nodeAlgos[algo]) { // Node crypto library.
9836 return nodeDecrypt(algo, key, ciphertext, iv);
9837 }
9838 if (algo.substr(0, 3) === 'aes') {
9839 return aesDecrypt(algo, key, ciphertext, iv);
9840 }
9841
9842 const cipherfn = new cipher[algo](key);
9843 const block_size = cipherfn.blockSize;
9844
9845 let blockp = iv;
9846 let ct = new Uint8Array();
9847 const process = chunk => {
9848 if (chunk) {
9849 ct = util.concatUint8Array([ct, chunk]);
9850 }
9851 const plaintext = new Uint8Array(ct.length);
9852 let i;
9853 let j = 0;
9854 while (chunk ? ct.length >= block_size : ct.length) {
9855 const decblock = cipherfn.encrypt(blockp);
9856 blockp = ct;
9857 for (i = 0; i < block_size; i++) {
9858 plaintext[j++] = blockp[i] ^ decblock[i];
9859 }
9860 ct = ct.subarray(block_size);
9861 }
9862 return plaintext.subarray(0, j);
9863 };
9864 return transform(ciphertext, process, process);
9865 }
9866
9867 function aesEncrypt(algo, key, pt, iv, config) {
9868 if (
9869 util.getWebCrypto() &&
9870 key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support
9871 !util.isStream(pt) &&
9872 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
9873 ) { // Web Crypto
9874 return webEncrypt(algo, key, pt, iv);
9875 }
9876 // asm.js fallback
9877 const cfb = new AES_CFB(key, iv);
9878 return transform(pt, value => cfb.aes.AES_Encrypt_process(value), () => cfb.aes.AES_Encrypt_finish());
9879 }
9880
9881 function aesDecrypt(algo, key, ct, iv) {
9882 if (util.isStream(ct)) {
9883 const cfb = new AES_CFB(key, iv);
9884 return transform(ct, value => cfb.aes.AES_Decrypt_process(value), () => cfb.aes.AES_Decrypt_finish());
9885 }
9886 return AES_CFB.decrypt(ct, key, iv);
9887 }
9888
9889 function xorMut(a, b) {
9890 for (let i = 0; i < a.length; i++) {
9891 a[i] = a[i] ^ b[i];
9892 }
9893 }
9894
9895 async function webEncrypt(algo, key, pt, iv) {
9896 const ALGO = 'AES-CBC';
9897 const _key = await webCrypto$1.importKey('raw', key, { name: ALGO }, false, ['encrypt']);
9898 const { blockSize } = cipher[algo];
9899 const cbc_pt = util.concatUint8Array([new Uint8Array(blockSize), pt]);
9900 const ct = new Uint8Array(await webCrypto$1.encrypt({ name: ALGO, iv }, _key, cbc_pt)).subarray(0, pt.length);
9901 xorMut(ct, pt);
9902 return ct;
9903 }
9904
9905 function nodeEncrypt(algo, key, pt, iv) {
9906 const cipherObj = new nodeCrypto$1.createCipheriv(nodeAlgos[algo], key, iv);
9907 return transform(pt, value => new Uint8Array(cipherObj.update(value)));
9908 }
9909
9910 function nodeDecrypt(algo, key, ct, iv) {
9911 const decipherObj = new nodeCrypto$1.createDecipheriv(nodeAlgos[algo], key, iv);
9912 return transform(ct, value => new Uint8Array(decipherObj.update(value)));
9913 }
9914
9915 var cfb = /*#__PURE__*/Object.freeze({
9916 __proto__: null,
9917 encrypt: encrypt,
9918 decrypt: decrypt
9919 });
9920
9921 class AES_CTR {
9922 static encrypt(data, key, nonce) {
9923 return new AES_CTR(key, nonce).encrypt(data);
9924 }
9925 static decrypt(data, key, nonce) {
9926 return new AES_CTR(key, nonce).encrypt(data);
9927 }
9928 constructor(key, nonce, aes) {
9929 this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');
9930 delete this.aes.padding;
9931 this.AES_CTR_set_options(nonce);
9932 }
9933 encrypt(data) {
9934 const r1 = this.aes.AES_Encrypt_process(data);
9935 const r2 = this.aes.AES_Encrypt_finish();
9936 return joinBytes(r1, r2);
9937 }
9938 decrypt(data) {
9939 const r1 = this.aes.AES_Encrypt_process(data);
9940 const r2 = this.aes.AES_Encrypt_finish();
9941 return joinBytes(r1, r2);
9942 }
9943 AES_CTR_set_options(nonce, counter, size) {
9944 let { asm } = this.aes.acquire_asm();
9945 if (size !== undefined) {
9946 if (size < 8 || size > 48)
9947 throw new IllegalArgumentError('illegal counter size');
9948 let mask = Math.pow(2, size) - 1;
9949 asm.set_mask(0, 0, (mask / 0x100000000) | 0, mask | 0);
9950 }
9951 else {
9952 size = 48;
9953 asm.set_mask(0, 0, 0xffff, 0xffffffff);
9954 }
9955 if (nonce !== undefined) {
9956 let len = nonce.length;
9957 if (!len || len > 16)
9958 throw new IllegalArgumentError('illegal nonce size');
9959 let view = new DataView(new ArrayBuffer(16));
9960 new Uint8Array(view.buffer).set(nonce);
9961 asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12));
9962 }
9963 else {
9964 throw new Error('nonce is required');
9965 }
9966 if (counter !== undefined) {
9967 if (counter < 0 || counter >= Math.pow(2, size))
9968 throw new IllegalArgumentError('illegal counter value');
9969 asm.set_counter(0, 0, (counter / 0x100000000) | 0, counter | 0);
9970 }
9971 }
9972 }
9973
9974 class AES_CBC {
9975 static encrypt(data, key, padding = true, iv) {
9976 return new AES_CBC(key, iv, padding).encrypt(data);
9977 }
9978 static decrypt(data, key, padding = true, iv) {
9979 return new AES_CBC(key, iv, padding).decrypt(data);
9980 }
9981 constructor(key, iv, padding = true, aes) {
9982 this.aes = aes ? aes : new AES(key, iv, padding, 'CBC');
9983 }
9984 encrypt(data) {
9985 const r1 = this.aes.AES_Encrypt_process(data);
9986 const r2 = this.aes.AES_Encrypt_finish();
9987 return joinBytes(r1, r2);
9988 }
9989 decrypt(data) {
9990 const r1 = this.aes.AES_Decrypt_process(data);
9991 const r2 = this.aes.AES_Decrypt_finish();
9992 return joinBytes(r1, r2);
9993 }
9994 }
9995
9996 /**
9997 * @fileoverview This module implements AES-CMAC on top of
9998 * native AES-CBC using either the WebCrypto API or Node.js' crypto API.
9999 * @module crypto/cmac
10000 * @private
10001 */
10002
10003 const webCrypto$2 = util.getWebCrypto();
10004 const nodeCrypto$2 = util.getNodeCrypto();
10005
10006
10007 /**
10008 * This implementation of CMAC is based on the description of OMAC in
10009 * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that
10010 * document:
10011 *
10012 * We have made a small modification to the OMAC algorithm as it was
10013 * originally presented, changing one of its two constants.
10014 * Specifically, the constant 4 at line 85 was the constant 1/2 (the
10015 * multiplicative inverse of 2) in the original definition of OMAC [14].
10016 * The OMAC authors indicate that they will promulgate this modification
10017 * [15], which slightly simplifies implementations.
10018 */
10019
10020 const blockLength = 16;
10021
10022
10023 /**
10024 * xor `padding` into the end of `data`. This function implements "the
10025 * operation xor→ [which] xors the shorter string into the end of longer
10026 * one". Since data is always as least as long as padding, we can
10027 * simplify the implementation.
10028 * @param {Uint8Array} data
10029 * @param {Uint8Array} padding
10030 */
10031 function rightXORMut(data, padding) {
10032 const offset = data.length - blockLength;
10033 for (let i = 0; i < blockLength; i++) {
10034 data[i + offset] ^= padding[i];
10035 }
10036 return data;
10037 }
10038
10039 function pad(data, padding, padding2) {
10040 // if |M| in {n, 2n, 3n, ...}
10041 if (data.length && data.length % blockLength === 0) {
10042 // then return M xor→ B,
10043 return rightXORMut(data, padding);
10044 }
10045 // else return (M || 10^(n−1−(|M| mod n))) xor→ P
10046 const padded = new Uint8Array(data.length + (blockLength - data.length % blockLength));
10047 padded.set(data);
10048 padded[data.length] = 0b10000000;
10049 return rightXORMut(padded, padding2);
10050 }
10051
10052 const zeroBlock = new Uint8Array(blockLength);
10053
10054 async function CMAC(key) {
10055 const cbc = await CBC(key);
10056
10057 // L ← E_K(0^n); B ← 2L; P ← 4L
10058 const padding = util.double(await cbc(zeroBlock));
10059 const padding2 = util.double(padding);
10060
10061 return async function(data) {
10062 // return CBC_K(pad(M; B, P))
10063 return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);
10064 };
10065 }
10066
10067 async function CBC(key) {
10068 if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
10069 key = await webCrypto$2.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);
10070 return async function(pt) {
10071 const ct = await webCrypto$2.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);
10072 return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);
10073 };
10074 }
10075 if (util.getNodeCrypto()) { // Node crypto library
10076 return async function(pt) {
10077 const en = new nodeCrypto$2.createCipheriv('aes-' + (key.length * 8) + '-cbc', key, zeroBlock);
10078 const ct = en.update(pt);
10079 return new Uint8Array(ct);
10080 };
10081 }
10082 // asm.js fallback
10083 return async function(pt) {
10084 return AES_CBC.encrypt(pt, key, false, zeroBlock);
10085 };
10086 }
10087
10088 // OpenPGP.js - An OpenPGP implementation in javascript
10089
10090 const webCrypto$3 = util.getWebCrypto();
10091 const nodeCrypto$3 = util.getNodeCrypto();
10092 const Buffer$1 = util.getNodeBuffer();
10093
10094
10095 const blockLength$1 = 16;
10096 const ivLength = blockLength$1;
10097 const tagLength = blockLength$1;
10098
10099 const zero = new Uint8Array(blockLength$1);
10100 const one = new Uint8Array(blockLength$1); one[blockLength$1 - 1] = 1;
10101 const two = new Uint8Array(blockLength$1); two[blockLength$1 - 1] = 2;
10102
10103 async function OMAC(key) {
10104 const cmac = await CMAC(key);
10105 return function(t, message) {
10106 return cmac(util.concatUint8Array([t, message]));
10107 };
10108 }
10109
10110 async function CTR(key) {
10111 if (
10112 util.getWebCrypto() &&
10113 key.length !== 24 && // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
10114 navigator.userAgent.indexOf('Edge') === -1
10115 ) {
10116 key = await webCrypto$3.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);
10117 return async function(pt, iv) {
10118 const ct = await webCrypto$3.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength$1 * 8 }, key, pt);
10119 return new Uint8Array(ct);
10120 };
10121 }
10122 if (util.getNodeCrypto()) { // Node crypto library
10123 return async function(pt, iv) {
10124 const en = new nodeCrypto$3.createCipheriv('aes-' + (key.length * 8) + '-ctr', key, iv);
10125 const ct = Buffer$1.concat([en.update(pt), en.final()]);
10126 return new Uint8Array(ct);
10127 };
10128 }
10129 // asm.js fallback
10130 return async function(pt, iv) {
10131 return AES_CTR.encrypt(pt, key, iv);
10132 };
10133 }
10134
10135
10136 /**
10137 * Class to en/decrypt using EAX mode.
10138 * @param {String} cipher - The symmetric cipher algorithm to use e.g. 'aes128'
10139 * @param {Uint8Array} key - The encryption key
10140 */
10141 async function EAX(cipher, key) {
10142 if (cipher.substr(0, 3) !== 'aes') {
10143 throw new Error('EAX mode supports only AES cipher');
10144 }
10145
10146 const [
10147 omac,
10148 ctr
10149 ] = await Promise.all([
10150 OMAC(key),
10151 CTR(key)
10152 ]);
10153
10154 return {
10155 /**
10156 * Encrypt plaintext input.
10157 * @param {Uint8Array} plaintext - The cleartext input to be encrypted
10158 * @param {Uint8Array} nonce - The nonce (16 bytes)
10159 * @param {Uint8Array} adata - Associated data to sign
10160 * @returns {Promise<Uint8Array>} The ciphertext output.
10161 */
10162 encrypt: async function(plaintext, nonce, adata) {
10163 const [
10164 omacNonce,
10165 omacAdata
10166 ] = await Promise.all([
10167 omac(zero, nonce),
10168 omac(one, adata)
10169 ]);
10170 const ciphered = await ctr(plaintext, omacNonce);
10171 const omacCiphered = await omac(two, ciphered);
10172 const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
10173 for (let i = 0; i < tagLength; i++) {
10174 tag[i] ^= omacAdata[i] ^ omacNonce[i];
10175 }
10176 return util.concatUint8Array([ciphered, tag]);
10177 },
10178
10179 /**
10180 * Decrypt ciphertext input.
10181 * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted
10182 * @param {Uint8Array} nonce - The nonce (16 bytes)
10183 * @param {Uint8Array} adata - Associated data to verify
10184 * @returns {Promise<Uint8Array>} The plaintext output.
10185 */
10186 decrypt: async function(ciphertext, nonce, adata) {
10187 if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');
10188 const ciphered = ciphertext.subarray(0, -tagLength);
10189 const ctTag = ciphertext.subarray(-tagLength);
10190 const [
10191 omacNonce,
10192 omacAdata,
10193 omacCiphered
10194 ] = await Promise.all([
10195 omac(zero, nonce),
10196 omac(one, adata),
10197 omac(two, ciphered)
10198 ]);
10199 const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
10200 for (let i = 0; i < tagLength; i++) {
10201 tag[i] ^= omacAdata[i] ^ omacNonce[i];
10202 }
10203 if (!util.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');
10204 const plaintext = await ctr(ciphered, omacNonce);
10205 return plaintext;
10206 }
10207 };
10208 }
10209
10210
10211 /**
10212 * 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}.
10213 * @param {Uint8Array} iv - The initialization vector (16 bytes)
10214 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
10215 */
10216 EAX.getNonce = function(iv, chunkIndex) {
10217 const nonce = iv.slice();
10218 for (let i = 0; i < chunkIndex.length; i++) {
10219 nonce[8 + i] ^= chunkIndex[i];
10220 }
10221 return nonce;
10222 };
10223
10224 EAX.blockLength = blockLength$1;
10225 EAX.ivLength = ivLength;
10226 EAX.tagLength = tagLength;
10227
10228 // OpenPGP.js - An OpenPGP implementation in javascript
10229
10230
10231 const blockLength$2 = 16;
10232 const ivLength$1 = 15;
10233
10234 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:
10235 // While OCB [RFC7253] allows the authentication tag length to be of any
10236 // number up to 128 bits long, this document requires a fixed
10237 // authentication tag length of 128 bits (16 octets) for simplicity.
10238 const tagLength$1 = 16;
10239
10240
10241 function ntz(n) {
10242 let ntz = 0;
10243 for (let i = 1; (n & i) === 0; i <<= 1) {
10244 ntz++;
10245 }
10246 return ntz;
10247 }
10248
10249 function xorMut$1(S, T) {
10250 for (let i = 0; i < S.length; i++) {
10251 S[i] ^= T[i];
10252 }
10253 return S;
10254 }
10255
10256 function xor(S, T) {
10257 return xorMut$1(S.slice(), T);
10258 }
10259
10260 const zeroBlock$1 = new Uint8Array(blockLength$2);
10261 const one$1 = new Uint8Array([1]);
10262
10263 /**
10264 * Class to en/decrypt using OCB mode.
10265 * @param {String} cipher - The symmetric cipher algorithm to use e.g. 'aes128'
10266 * @param {Uint8Array} key - The encryption key
10267 */
10268 async function OCB(cipher$1, key) {
10269
10270 let maxNtz = 0;
10271 let encipher;
10272 let decipher;
10273 let mask;
10274
10275 constructKeyVariables(cipher$1, key);
10276
10277 function constructKeyVariables(cipher$1, key) {
10278 const aes = new cipher[cipher$1](key);
10279 encipher = aes.encrypt.bind(aes);
10280 decipher = aes.decrypt.bind(aes);
10281
10282 const mask_x = encipher(zeroBlock$1);
10283 const mask_$ = util.double(mask_x);
10284 mask = [];
10285 mask[0] = util.double(mask_$);
10286
10287
10288 mask.x = mask_x;
10289 mask.$ = mask_$;
10290 }
10291
10292 function extendKeyVariables(text, adata) {
10293 const newMaxNtz = util.nbits(Math.max(text.length, adata.length) / blockLength$2 | 0) - 1;
10294 for (let i = maxNtz + 1; i <= newMaxNtz; i++) {
10295 mask[i] = util.double(mask[i - 1]);
10296 }
10297 maxNtz = newMaxNtz;
10298 }
10299
10300 function hash(adata) {
10301 if (!adata.length) {
10302 // Fast path
10303 return zeroBlock$1;
10304 }
10305
10306 //
10307 // Consider A as a sequence of 128-bit blocks
10308 //
10309 const m = adata.length / blockLength$2 | 0;
10310
10311 const offset = new Uint8Array(blockLength$2);
10312 const sum = new Uint8Array(blockLength$2);
10313 for (let i = 0; i < m; i++) {
10314 xorMut$1(offset, mask[ntz(i + 1)]);
10315 xorMut$1(sum, encipher(xor(offset, adata)));
10316 adata = adata.subarray(blockLength$2);
10317 }
10318
10319 //
10320 // Process any final partial block; compute final hash value
10321 //
10322 if (adata.length) {
10323 xorMut$1(offset, mask.x);
10324
10325 const cipherInput = new Uint8Array(blockLength$2);
10326 cipherInput.set(adata, 0);
10327 cipherInput[adata.length] = 0b10000000;
10328 xorMut$1(cipherInput, offset);
10329
10330 xorMut$1(sum, encipher(cipherInput));
10331 }
10332
10333 return sum;
10334 }
10335
10336 /**
10337 * Encrypt/decrypt data.
10338 * @param {encipher|decipher} fn - Encryption/decryption block cipher function
10339 * @param {Uint8Array} text - The cleartext or ciphertext (without tag) input
10340 * @param {Uint8Array} nonce - The nonce (15 bytes)
10341 * @param {Uint8Array} adata - Associated data to sign
10342 * @returns {Promise<Uint8Array>} The ciphertext or plaintext output, with tag appended in both cases.
10343 */
10344 function crypt(fn, text, nonce, adata) {
10345 //
10346 // Consider P as a sequence of 128-bit blocks
10347 //
10348 const m = text.length / blockLength$2 | 0;
10349
10350 //
10351 // Key-dependent variables
10352 //
10353 extendKeyVariables(text, adata);
10354
10355 //
10356 // Nonce-dependent and per-encryption variables
10357 //
10358 // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N
10359 // Note: We assume here that tagLength mod 16 == 0.
10360 const paddedNonce = util.concatUint8Array([zeroBlock$1.subarray(0, ivLength$1 - nonce.length), one$1, nonce]);
10361 // bottom = str2num(Nonce[123..128])
10362 const bottom = paddedNonce[blockLength$2 - 1] & 0b111111;
10363 // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))
10364 paddedNonce[blockLength$2 - 1] &= 0b11000000;
10365 const kTop = encipher(paddedNonce);
10366 // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])
10367 const stretched = util.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);
10368 // Offset_0 = Stretch[1+bottom..128+bottom]
10369 const offset = util.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);
10370 // Checksum_0 = zeros(128)
10371 const checksum = new Uint8Array(blockLength$2);
10372
10373 const ct = new Uint8Array(text.length + tagLength$1);
10374
10375 //
10376 // Process any whole blocks
10377 //
10378 let i;
10379 let pos = 0;
10380 for (i = 0; i < m; i++) {
10381 // Offset_i = Offset_{i-1} xor L_{ntz(i)}
10382 xorMut$1(offset, mask[ntz(i + 1)]);
10383 // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)
10384 // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)
10385 ct.set(xorMut$1(fn(xor(offset, text)), offset), pos);
10386 // Checksum_i = Checksum_{i-1} xor P_i
10387 xorMut$1(checksum, fn === encipher ? text : ct.subarray(pos));
10388
10389 text = text.subarray(blockLength$2);
10390 pos += blockLength$2;
10391 }
10392
10393 //
10394 // Process any final partial block and compute raw tag
10395 //
10396 if (text.length) {
10397 // Offset_* = Offset_m xor L_*
10398 xorMut$1(offset, mask.x);
10399 // Pad = ENCIPHER(K, Offset_*)
10400 const padding = encipher(offset);
10401 // C_* = P_* xor Pad[1..bitlen(P_*)]
10402 ct.set(xor(text, padding), pos);
10403
10404 // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))
10405 const xorInput = new Uint8Array(blockLength$2);
10406 xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength$1), 0);
10407 xorInput[text.length] = 0b10000000;
10408 xorMut$1(checksum, xorInput);
10409 pos += text.length;
10410 }
10411 // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)
10412 const tag = xorMut$1(encipher(xorMut$1(xorMut$1(checksum, offset), mask.$)), hash(adata));
10413
10414 //
10415 // Assemble ciphertext
10416 //
10417 // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]
10418 ct.set(tag, pos);
10419 return ct;
10420 }
10421
10422
10423 return {
10424 /**
10425 * Encrypt plaintext input.
10426 * @param {Uint8Array} plaintext - The cleartext input to be encrypted
10427 * @param {Uint8Array} nonce - The nonce (15 bytes)
10428 * @param {Uint8Array} adata - Associated data to sign
10429 * @returns {Promise<Uint8Array>} The ciphertext output.
10430 */
10431 encrypt: async function(plaintext, nonce, adata) {
10432 return crypt(encipher, plaintext, nonce, adata);
10433 },
10434
10435 /**
10436 * Decrypt ciphertext input.
10437 * @param {Uint8Array} ciphertext - The ciphertext input to be decrypted
10438 * @param {Uint8Array} nonce - The nonce (15 bytes)
10439 * @param {Uint8Array} adata - Associated data to sign
10440 * @returns {Promise<Uint8Array>} The ciphertext output.
10441 */
10442 decrypt: async function(ciphertext, nonce, adata) {
10443 if (ciphertext.length < tagLength$1) throw new Error('Invalid OCB ciphertext');
10444
10445 const tag = ciphertext.subarray(-tagLength$1);
10446 ciphertext = ciphertext.subarray(0, -tagLength$1);
10447
10448 const crypted = crypt(decipher, ciphertext, nonce, adata);
10449 // if (Tag[1..TAGLEN] == T)
10450 if (util.equalsUint8Array(tag, crypted.subarray(-tagLength$1))) {
10451 return crypted.subarray(0, -tagLength$1);
10452 }
10453 throw new Error('Authentication tag mismatch');
10454 }
10455 };
10456 }
10457
10458
10459 /**
10460 * 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}.
10461 * @param {Uint8Array} iv - The initialization vector (15 bytes)
10462 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
10463 */
10464 OCB.getNonce = function(iv, chunkIndex) {
10465 const nonce = iv.slice();
10466 for (let i = 0; i < chunkIndex.length; i++) {
10467 nonce[7 + i] ^= chunkIndex[i];
10468 }
10469 return nonce;
10470 };
10471
10472 OCB.blockLength = blockLength$2;
10473 OCB.ivLength = ivLength$1;
10474 OCB.tagLength = tagLength$1;
10475
10476 const _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5
10477 class AES_GCM {
10478 constructor(key, nonce, adata, tagSize = 16, aes) {
10479 this.tagSize = tagSize;
10480 this.gamma0 = 0;
10481 this.counter = 1;
10482 this.aes = aes ? aes : new AES(key, undefined, false, 'CTR');
10483 let { asm, heap } = this.aes.acquire_asm();
10484 // Init GCM
10485 asm.gcm_init();
10486 // Tag size
10487 if (this.tagSize < 4 || this.tagSize > 16)
10488 throw new IllegalArgumentError('illegal tagSize value');
10489 // Nonce
10490 const noncelen = nonce.length || 0;
10491 const noncebuf = new Uint8Array(16);
10492 if (noncelen !== 12) {
10493 this._gcm_mac_process(nonce);
10494 heap[0] = 0;
10495 heap[1] = 0;
10496 heap[2] = 0;
10497 heap[3] = 0;
10498 heap[4] = 0;
10499 heap[5] = 0;
10500 heap[6] = 0;
10501 heap[7] = 0;
10502 heap[8] = 0;
10503 heap[9] = 0;
10504 heap[10] = 0;
10505 heap[11] = noncelen >>> 29;
10506 heap[12] = (noncelen >>> 21) & 255;
10507 heap[13] = (noncelen >>> 13) & 255;
10508 heap[14] = (noncelen >>> 5) & 255;
10509 heap[15] = (noncelen << 3) & 255;
10510 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
10511 asm.get_iv(AES_asm.HEAP_DATA);
10512 asm.set_iv(0, 0, 0, 0);
10513 noncebuf.set(heap.subarray(0, 16));
10514 }
10515 else {
10516 noncebuf.set(nonce);
10517 noncebuf[15] = 1;
10518 }
10519 const nonceview = new DataView(noncebuf.buffer);
10520 this.gamma0 = nonceview.getUint32(12);
10521 asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0);
10522 asm.set_mask(0, 0, 0, 0xffffffff);
10523 // Associated data
10524 if (adata !== undefined) {
10525 if (adata.length > _AES_GCM_data_maxLength)
10526 throw new IllegalArgumentError('illegal adata length');
10527 if (adata.length) {
10528 this.adata = adata;
10529 this._gcm_mac_process(adata);
10530 }
10531 else {
10532 this.adata = undefined;
10533 }
10534 }
10535 else {
10536 this.adata = undefined;
10537 }
10538 // Counter
10539 if (this.counter < 1 || this.counter > 0xffffffff)
10540 throw new RangeError('counter must be a positive 32-bit integer');
10541 asm.set_counter(0, 0, 0, (this.gamma0 + this.counter) | 0);
10542 }
10543 static encrypt(cleartext, key, nonce, adata, tagsize) {
10544 return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext);
10545 }
10546 static decrypt(ciphertext, key, nonce, adata, tagsize) {
10547 return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext);
10548 }
10549 encrypt(data) {
10550 return this.AES_GCM_encrypt(data);
10551 }
10552 decrypt(data) {
10553 return this.AES_GCM_decrypt(data);
10554 }
10555 AES_GCM_Encrypt_process(data) {
10556 let dpos = 0;
10557 let dlen = data.length || 0;
10558 let { asm, heap } = this.aes.acquire_asm();
10559 let counter = this.counter;
10560 let pos = this.aes.pos;
10561 let len = this.aes.len;
10562 let rpos = 0;
10563 let rlen = (len + dlen) & -16;
10564 let wlen = 0;
10565 if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)
10566 throw new RangeError('counter overflow');
10567 const result = new Uint8Array(rlen);
10568 while (dlen > 0) {
10569 wlen = _heap_write(heap, pos + len, data, dpos, dlen);
10570 len += wlen;
10571 dpos += wlen;
10572 dlen -= wlen;
10573 wlen = asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len);
10574 wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);
10575 if (wlen)
10576 result.set(heap.subarray(pos, pos + wlen), rpos);
10577 counter += wlen >>> 4;
10578 rpos += wlen;
10579 if (wlen < len) {
10580 pos += wlen;
10581 len -= wlen;
10582 }
10583 else {
10584 pos = 0;
10585 len = 0;
10586 }
10587 }
10588 this.counter = counter;
10589 this.aes.pos = pos;
10590 this.aes.len = len;
10591 return result;
10592 }
10593 AES_GCM_Encrypt_finish() {
10594 let { asm, heap } = this.aes.acquire_asm();
10595 let counter = this.counter;
10596 let tagSize = this.tagSize;
10597 let adata = this.adata;
10598 let pos = this.aes.pos;
10599 let len = this.aes.len;
10600 const result = new Uint8Array(len + tagSize);
10601 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16);
10602 if (len)
10603 result.set(heap.subarray(pos, pos + len));
10604 let i = len;
10605 for (; i & 15; i++)
10606 heap[pos + i] = 0;
10607 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);
10608 const alen = adata !== undefined ? adata.length : 0;
10609 const clen = ((counter - 1) << 4) + len;
10610 heap[0] = 0;
10611 heap[1] = 0;
10612 heap[2] = 0;
10613 heap[3] = alen >>> 29;
10614 heap[4] = alen >>> 21;
10615 heap[5] = (alen >>> 13) & 255;
10616 heap[6] = (alen >>> 5) & 255;
10617 heap[7] = (alen << 3) & 255;
10618 heap[8] = heap[9] = heap[10] = 0;
10619 heap[11] = clen >>> 29;
10620 heap[12] = (clen >>> 21) & 255;
10621 heap[13] = (clen >>> 13) & 255;
10622 heap[14] = (clen >>> 5) & 255;
10623 heap[15] = (clen << 3) & 255;
10624 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
10625 asm.get_iv(AES_asm.HEAP_DATA);
10626 asm.set_counter(0, 0, 0, this.gamma0);
10627 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);
10628 result.set(heap.subarray(0, tagSize), len);
10629 this.counter = 1;
10630 this.aes.pos = 0;
10631 this.aes.len = 0;
10632 return result;
10633 }
10634 AES_GCM_Decrypt_process(data) {
10635 let dpos = 0;
10636 let dlen = data.length || 0;
10637 let { asm, heap } = this.aes.acquire_asm();
10638 let counter = this.counter;
10639 let tagSize = this.tagSize;
10640 let pos = this.aes.pos;
10641 let len = this.aes.len;
10642 let rpos = 0;
10643 let rlen = len + dlen > tagSize ? (len + dlen - tagSize) & -16 : 0;
10644 let tlen = len + dlen - rlen;
10645 let wlen = 0;
10646 if (((counter - 1) << 4) + len + dlen > _AES_GCM_data_maxLength)
10647 throw new RangeError('counter overflow');
10648 const result = new Uint8Array(rlen);
10649 while (dlen > tlen) {
10650 wlen = _heap_write(heap, pos + len, data, dpos, dlen - tlen);
10651 len += wlen;
10652 dpos += wlen;
10653 dlen -= wlen;
10654 wlen = asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen);
10655 wlen = asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen);
10656 if (wlen)
10657 result.set(heap.subarray(pos, pos + wlen), rpos);
10658 counter += wlen >>> 4;
10659 rpos += wlen;
10660 pos = 0;
10661 len = 0;
10662 }
10663 if (dlen > 0) {
10664 len += _heap_write(heap, 0, data, dpos, dlen);
10665 }
10666 this.counter = counter;
10667 this.aes.pos = pos;
10668 this.aes.len = len;
10669 return result;
10670 }
10671 AES_GCM_Decrypt_finish() {
10672 let { asm, heap } = this.aes.acquire_asm();
10673 let tagSize = this.tagSize;
10674 let adata = this.adata;
10675 let counter = this.counter;
10676 let pos = this.aes.pos;
10677 let len = this.aes.len;
10678 let rlen = len - tagSize;
10679 if (len < tagSize)
10680 throw new IllegalStateError('authentication tag not found');
10681 const result = new Uint8Array(rlen);
10682 const atag = new Uint8Array(heap.subarray(pos + rlen, pos + len));
10683 let i = rlen;
10684 for (; i & 15; i++)
10685 heap[pos + i] = 0;
10686 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i);
10687 asm.cipher(AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i);
10688 if (rlen)
10689 result.set(heap.subarray(pos, pos + rlen));
10690 const alen = adata !== undefined ? adata.length : 0;
10691 const clen = ((counter - 1) << 4) + len - tagSize;
10692 heap[0] = 0;
10693 heap[1] = 0;
10694 heap[2] = 0;
10695 heap[3] = alen >>> 29;
10696 heap[4] = alen >>> 21;
10697 heap[5] = (alen >>> 13) & 255;
10698 heap[6] = (alen >>> 5) & 255;
10699 heap[7] = (alen << 3) & 255;
10700 heap[8] = heap[9] = heap[10] = 0;
10701 heap[11] = clen >>> 29;
10702 heap[12] = (clen >>> 21) & 255;
10703 heap[13] = (clen >>> 13) & 255;
10704 heap[14] = (clen >>> 5) & 255;
10705 heap[15] = (clen << 3) & 255;
10706 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16);
10707 asm.get_iv(AES_asm.HEAP_DATA);
10708 asm.set_counter(0, 0, 0, this.gamma0);
10709 asm.cipher(AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16);
10710 let acheck = 0;
10711 for (let i = 0; i < tagSize; ++i)
10712 acheck |= atag[i] ^ heap[i];
10713 if (acheck)
10714 throw new SecurityError('data integrity check failed');
10715 this.counter = 1;
10716 this.aes.pos = 0;
10717 this.aes.len = 0;
10718 return result;
10719 }
10720 AES_GCM_decrypt(data) {
10721 const result1 = this.AES_GCM_Decrypt_process(data);
10722 const result2 = this.AES_GCM_Decrypt_finish();
10723 const result = new Uint8Array(result1.length + result2.length);
10724 if (result1.length)
10725 result.set(result1);
10726 if (result2.length)
10727 result.set(result2, result1.length);
10728 return result;
10729 }
10730 AES_GCM_encrypt(data) {
10731 const result1 = this.AES_GCM_Encrypt_process(data);
10732 const result2 = this.AES_GCM_Encrypt_finish();
10733 const result = new Uint8Array(result1.length + result2.length);
10734 if (result1.length)
10735 result.set(result1);
10736 if (result2.length)
10737 result.set(result2, result1.length);
10738 return result;
10739 }
10740 _gcm_mac_process(data) {
10741 let { asm, heap } = this.aes.acquire_asm();
10742 let dpos = 0;
10743 let dlen = data.length || 0;
10744 let wlen = 0;
10745 while (dlen > 0) {
10746 wlen = _heap_write(heap, 0, data, dpos, dlen);
10747 dpos += wlen;
10748 dlen -= wlen;
10749 while (wlen & 15)
10750 heap[wlen++] = 0;
10751 asm.mac(AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen);
10752 }
10753 }
10754 }
10755
10756 // OpenPGP.js - An OpenPGP implementation in javascript
10757
10758 const webCrypto$4 = util.getWebCrypto();
10759 const nodeCrypto$4 = util.getNodeCrypto();
10760 const Buffer$2 = util.getNodeBuffer();
10761
10762 const blockLength$3 = 16;
10763 const ivLength$2 = 12; // size of the IV in bytes
10764 const tagLength$2 = 16; // size of the tag in bytes
10765 const ALGO = 'AES-GCM';
10766
10767 /**
10768 * Class to en/decrypt using GCM mode.
10769 * @param {String} cipher - The symmetric cipher algorithm to use e.g. 'aes128'
10770 * @param {Uint8Array} key - The encryption key
10771 */
10772 async function GCM(cipher, key) {
10773 if (cipher.substr(0, 3) !== 'aes') {
10774 throw new Error('GCM mode supports only AES cipher');
10775 }
10776
10777 if (util.getWebCrypto() && key.length !== 24) { // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
10778 const _key = await webCrypto$4.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);
10779
10780 return {
10781 encrypt: async function(pt, iv, adata = new Uint8Array()) {
10782 if (
10783 !pt.length ||
10784 // iOS does not support GCM-en/decrypting empty messages
10785 // Also, synchronous en/decryption might be faster in this case.
10786 (!adata.length && navigator.userAgent.indexOf('Edge') !== -1)
10787 // Edge does not support GCM-en/decrypting without ADATA
10788 ) {
10789 return AES_GCM.encrypt(pt, key, iv, adata);
10790 }
10791 const ct = await webCrypto$4.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, pt);
10792 return new Uint8Array(ct);
10793 },
10794
10795 decrypt: async function(ct, iv, adata = new Uint8Array()) {
10796 if (
10797 ct.length === tagLength$2 ||
10798 // iOS does not support GCM-en/decrypting empty messages
10799 // Also, synchronous en/decryption might be faster in this case.
10800 (!adata.length && navigator.userAgent.indexOf('Edge') !== -1)
10801 // Edge does not support GCM-en/decrypting without ADATA
10802 ) {
10803 return AES_GCM.decrypt(ct, key, iv, adata);
10804 }
10805 const pt = await webCrypto$4.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength$2 * 8 }, _key, ct);
10806 return new Uint8Array(pt);
10807 }
10808 };
10809 }
10810
10811 if (util.getNodeCrypto()) { // Node crypto library
10812 return {
10813 encrypt: async function(pt, iv, adata = new Uint8Array()) {
10814 const en = new nodeCrypto$4.createCipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);
10815 en.setAAD(adata);
10816 const ct = Buffer$2.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext
10817 return new Uint8Array(ct);
10818 },
10819
10820 decrypt: async function(ct, iv, adata = new Uint8Array()) {
10821 const de = new nodeCrypto$4.createDecipheriv('aes-' + (key.length * 8) + '-gcm', key, iv);
10822 de.setAAD(adata);
10823 de.setAuthTag(ct.slice(ct.length - tagLength$2, ct.length)); // read auth tag at end of ciphertext
10824 const pt = Buffer$2.concat([de.update(ct.slice(0, ct.length - tagLength$2)), de.final()]);
10825 return new Uint8Array(pt);
10826 }
10827 };
10828 }
10829
10830 return {
10831 encrypt: async function(pt, iv, adata) {
10832 return AES_GCM.encrypt(pt, key, iv, adata);
10833 },
10834
10835 decrypt: async function(ct, iv, adata) {
10836 return AES_GCM.decrypt(ct, key, iv, adata);
10837 }
10838 };
10839 }
10840
10841
10842 /**
10843 * Get GCM nonce. Note: this operation is not defined by the standard.
10844 * A future version of the standard may define GCM mode differently,
10845 * hopefully under a different ID (we use Private/Experimental algorithm
10846 * ID 100) so that we can maintain backwards compatibility.
10847 * @param {Uint8Array} iv - The initialization vector (12 bytes)
10848 * @param {Uint8Array} chunkIndex - The chunk index (8 bytes)
10849 */
10850 GCM.getNonce = function(iv, chunkIndex) {
10851 const nonce = iv.slice();
10852 for (let i = 0; i < chunkIndex.length; i++) {
10853 nonce[4 + i] ^= chunkIndex[i];
10854 }
10855 return nonce;
10856 };
10857
10858 GCM.blockLength = blockLength$3;
10859 GCM.ivLength = ivLength$2;
10860 GCM.tagLength = tagLength$2;
10861
10862 /**
10863 * @fileoverview Cipher modes
10864 * @module crypto/mode
10865 * @private
10866 */
10867
10868 var mode = {
10869 /** @see module:crypto/mode/cfb */
10870 cfb: cfb,
10871 /** @see module:crypto/mode/gcm */
10872 gcm: GCM,
10873 experimentalGCM: GCM,
10874 /** @see module:crypto/mode/eax */
10875 eax: EAX,
10876 /** @see module:crypto/mode/ocb */
10877 ocb: OCB
10878 };
10879
10880 var naclFastLight = createCommonjsModule(function (module) {
10881 /*jshint bitwise: false*/
10882
10883 (function(nacl) {
10884
10885 // Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
10886 // Public domain.
10887 //
10888 // Implementation derived from TweetNaCl version 20140427.
10889 // See for details: http://tweetnacl.cr.yp.to/
10890
10891 var gf = function(init) {
10892 var i, r = new Float64Array(16);
10893 if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
10894 return r;
10895 };
10896
10897 // Pluggable, initialized in high-level API below.
10898 var randombytes = function(/* x, n */) { throw new Error('no PRNG'); };
10899
10900 var _9 = new Uint8Array(32); _9[0] = 9;
10901
10902 var gf0 = gf(),
10903 gf1 = gf([1]),
10904 _121665 = gf([0xdb41, 1]),
10905 D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
10906 D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
10907 X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
10908 Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
10909 I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
10910
10911 function vn(x, xi, y, yi, n) {
10912 var i,d = 0;
10913 for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];
10914 return (1 & ((d - 1) >>> 8)) - 1;
10915 }
10916
10917 function crypto_verify_32(x, xi, y, yi) {
10918 return vn(x,xi,y,yi,32);
10919 }
10920
10921 function set25519(r, a) {
10922 var i;
10923 for (i = 0; i < 16; i++) r[i] = a[i]|0;
10924 }
10925
10926 function car25519(o) {
10927 var i, v, c = 1;
10928 for (i = 0; i < 16; i++) {
10929 v = o[i] + c + 65535;
10930 c = Math.floor(v / 65536);
10931 o[i] = v - c * 65536;
10932 }
10933 o[0] += c-1 + 37 * (c-1);
10934 }
10935
10936 function sel25519(p, q, b) {
10937 var t, c = ~(b-1);
10938 for (var i = 0; i < 16; i++) {
10939 t = c & (p[i] ^ q[i]);
10940 p[i] ^= t;
10941 q[i] ^= t;
10942 }
10943 }
10944
10945 function pack25519(o, n) {
10946 var i, j, b;
10947 var m = gf(), t = gf();
10948 for (i = 0; i < 16; i++) t[i] = n[i];
10949 car25519(t);
10950 car25519(t);
10951 car25519(t);
10952 for (j = 0; j < 2; j++) {
10953 m[0] = t[0] - 0xffed;
10954 for (i = 1; i < 15; i++) {
10955 m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
10956 m[i-1] &= 0xffff;
10957 }
10958 m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
10959 b = (m[15]>>16) & 1;
10960 m[14] &= 0xffff;
10961 sel25519(t, m, 1-b);
10962 }
10963 for (i = 0; i < 16; i++) {
10964 o[2*i] = t[i] & 0xff;
10965 o[2*i+1] = t[i]>>8;
10966 }
10967 }
10968
10969 function neq25519(a, b) {
10970 var c = new Uint8Array(32), d = new Uint8Array(32);
10971 pack25519(c, a);
10972 pack25519(d, b);
10973 return crypto_verify_32(c, 0, d, 0);
10974 }
10975
10976 function par25519(a) {
10977 var d = new Uint8Array(32);
10978 pack25519(d, a);
10979 return d[0] & 1;
10980 }
10981
10982 function unpack25519(o, n) {
10983 var i;
10984 for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);
10985 o[15] &= 0x7fff;
10986 }
10987
10988 function A(o, a, b) {
10989 for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
10990 }
10991
10992 function Z(o, a, b) {
10993 for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
10994 }
10995
10996 function M(o, a, b) {
10997 var v, c,
10998 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
10999 t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
11000 t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
11001 t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
11002 b0 = b[0],
11003 b1 = b[1],
11004 b2 = b[2],
11005 b3 = b[3],
11006 b4 = b[4],
11007 b5 = b[5],
11008 b6 = b[6],
11009 b7 = b[7],
11010 b8 = b[8],
11011 b9 = b[9],
11012 b10 = b[10],
11013 b11 = b[11],
11014 b12 = b[12],
11015 b13 = b[13],
11016 b14 = b[14],
11017 b15 = b[15];
11018
11019 v = a[0];
11020 t0 += v * b0;
11021 t1 += v * b1;
11022 t2 += v * b2;
11023 t3 += v * b3;
11024 t4 += v * b4;
11025 t5 += v * b5;
11026 t6 += v * b6;
11027 t7 += v * b7;
11028 t8 += v * b8;
11029 t9 += v * b9;
11030 t10 += v * b10;
11031 t11 += v * b11;
11032 t12 += v * b12;
11033 t13 += v * b13;
11034 t14 += v * b14;
11035 t15 += v * b15;
11036 v = a[1];
11037 t1 += v * b0;
11038 t2 += v * b1;
11039 t3 += v * b2;
11040 t4 += v * b3;
11041 t5 += v * b4;
11042 t6 += v * b5;
11043 t7 += v * b6;
11044 t8 += v * b7;
11045 t9 += v * b8;
11046 t10 += v * b9;
11047 t11 += v * b10;
11048 t12 += v * b11;
11049 t13 += v * b12;
11050 t14 += v * b13;
11051 t15 += v * b14;
11052 t16 += v * b15;
11053 v = a[2];
11054 t2 += v * b0;
11055 t3 += v * b1;
11056 t4 += v * b2;
11057 t5 += v * b3;
11058 t6 += v * b4;
11059 t7 += v * b5;
11060 t8 += v * b6;
11061 t9 += v * b7;
11062 t10 += v * b8;
11063 t11 += v * b9;
11064 t12 += v * b10;
11065 t13 += v * b11;
11066 t14 += v * b12;
11067 t15 += v * b13;
11068 t16 += v * b14;
11069 t17 += v * b15;
11070 v = a[3];
11071 t3 += v * b0;
11072 t4 += v * b1;
11073 t5 += v * b2;
11074 t6 += v * b3;
11075 t7 += v * b4;
11076 t8 += v * b5;
11077 t9 += v * b6;
11078 t10 += v * b7;
11079 t11 += v * b8;
11080 t12 += v * b9;
11081 t13 += v * b10;
11082 t14 += v * b11;
11083 t15 += v * b12;
11084 t16 += v * b13;
11085 t17 += v * b14;
11086 t18 += v * b15;
11087 v = a[4];
11088 t4 += v * b0;
11089 t5 += v * b1;
11090 t6 += v * b2;
11091 t7 += v * b3;
11092 t8 += v * b4;
11093 t9 += v * b5;
11094 t10 += v * b6;
11095 t11 += v * b7;
11096 t12 += v * b8;
11097 t13 += v * b9;
11098 t14 += v * b10;
11099 t15 += v * b11;
11100 t16 += v * b12;
11101 t17 += v * b13;
11102 t18 += v * b14;
11103 t19 += v * b15;
11104 v = a[5];
11105 t5 += v * b0;
11106 t6 += v * b1;
11107 t7 += v * b2;
11108 t8 += v * b3;
11109 t9 += v * b4;
11110 t10 += v * b5;
11111 t11 += v * b6;
11112 t12 += v * b7;
11113 t13 += v * b8;
11114 t14 += v * b9;
11115 t15 += v * b10;
11116 t16 += v * b11;
11117 t17 += v * b12;
11118 t18 += v * b13;
11119 t19 += v * b14;
11120 t20 += v * b15;
11121 v = a[6];
11122 t6 += v * b0;
11123 t7 += v * b1;
11124 t8 += v * b2;
11125 t9 += v * b3;
11126 t10 += v * b4;
11127 t11 += v * b5;
11128 t12 += v * b6;
11129 t13 += v * b7;
11130 t14 += v * b8;
11131 t15 += v * b9;
11132 t16 += v * b10;
11133 t17 += v * b11;
11134 t18 += v * b12;
11135 t19 += v * b13;
11136 t20 += v * b14;
11137 t21 += v * b15;
11138 v = a[7];
11139 t7 += v * b0;
11140 t8 += v * b1;
11141 t9 += v * b2;
11142 t10 += v * b3;
11143 t11 += v * b4;
11144 t12 += v * b5;
11145 t13 += v * b6;
11146 t14 += v * b7;
11147 t15 += v * b8;
11148 t16 += v * b9;
11149 t17 += v * b10;
11150 t18 += v * b11;
11151 t19 += v * b12;
11152 t20 += v * b13;
11153 t21 += v * b14;
11154 t22 += v * b15;
11155 v = a[8];
11156 t8 += v * b0;
11157 t9 += v * b1;
11158 t10 += v * b2;
11159 t11 += v * b3;
11160 t12 += v * b4;
11161 t13 += v * b5;
11162 t14 += v * b6;
11163 t15 += v * b7;
11164 t16 += v * b8;
11165 t17 += v * b9;
11166 t18 += v * b10;
11167 t19 += v * b11;
11168 t20 += v * b12;
11169 t21 += v * b13;
11170 t22 += v * b14;
11171 t23 += v * b15;
11172 v = a[9];
11173 t9 += v * b0;
11174 t10 += v * b1;
11175 t11 += v * b2;
11176 t12 += v * b3;
11177 t13 += v * b4;
11178 t14 += v * b5;
11179 t15 += v * b6;
11180 t16 += v * b7;
11181 t17 += v * b8;
11182 t18 += v * b9;
11183 t19 += v * b10;
11184 t20 += v * b11;
11185 t21 += v * b12;
11186 t22 += v * b13;
11187 t23 += v * b14;
11188 t24 += v * b15;
11189 v = a[10];
11190 t10 += v * b0;
11191 t11 += v * b1;
11192 t12 += v * b2;
11193 t13 += v * b3;
11194 t14 += v * b4;
11195 t15 += v * b5;
11196 t16 += v * b6;
11197 t17 += v * b7;
11198 t18 += v * b8;
11199 t19 += v * b9;
11200 t20 += v * b10;
11201 t21 += v * b11;
11202 t22 += v * b12;
11203 t23 += v * b13;
11204 t24 += v * b14;
11205 t25 += v * b15;
11206 v = a[11];
11207 t11 += v * b0;
11208 t12 += v * b1;
11209 t13 += v * b2;
11210 t14 += v * b3;
11211 t15 += v * b4;
11212 t16 += v * b5;
11213 t17 += v * b6;
11214 t18 += v * b7;
11215 t19 += v * b8;
11216 t20 += v * b9;
11217 t21 += v * b10;
11218 t22 += v * b11;
11219 t23 += v * b12;
11220 t24 += v * b13;
11221 t25 += v * b14;
11222 t26 += v * b15;
11223 v = a[12];
11224 t12 += v * b0;
11225 t13 += v * b1;
11226 t14 += v * b2;
11227 t15 += v * b3;
11228 t16 += v * b4;
11229 t17 += v * b5;
11230 t18 += v * b6;
11231 t19 += v * b7;
11232 t20 += v * b8;
11233 t21 += v * b9;
11234 t22 += v * b10;
11235 t23 += v * b11;
11236 t24 += v * b12;
11237 t25 += v * b13;
11238 t26 += v * b14;
11239 t27 += v * b15;
11240 v = a[13];
11241 t13 += v * b0;
11242 t14 += v * b1;
11243 t15 += v * b2;
11244 t16 += v * b3;
11245 t17 += v * b4;
11246 t18 += v * b5;
11247 t19 += v * b6;
11248 t20 += v * b7;
11249 t21 += v * b8;
11250 t22 += v * b9;
11251 t23 += v * b10;
11252 t24 += v * b11;
11253 t25 += v * b12;
11254 t26 += v * b13;
11255 t27 += v * b14;
11256 t28 += v * b15;
11257 v = a[14];
11258 t14 += v * b0;
11259 t15 += v * b1;
11260 t16 += v * b2;
11261 t17 += v * b3;
11262 t18 += v * b4;
11263 t19 += v * b5;
11264 t20 += v * b6;
11265 t21 += v * b7;
11266 t22 += v * b8;
11267 t23 += v * b9;
11268 t24 += v * b10;
11269 t25 += v * b11;
11270 t26 += v * b12;
11271 t27 += v * b13;
11272 t28 += v * b14;
11273 t29 += v * b15;
11274 v = a[15];
11275 t15 += v * b0;
11276 t16 += v * b1;
11277 t17 += v * b2;
11278 t18 += v * b3;
11279 t19 += v * b4;
11280 t20 += v * b5;
11281 t21 += v * b6;
11282 t22 += v * b7;
11283 t23 += v * b8;
11284 t24 += v * b9;
11285 t25 += v * b10;
11286 t26 += v * b11;
11287 t27 += v * b12;
11288 t28 += v * b13;
11289 t29 += v * b14;
11290 t30 += v * b15;
11291
11292 t0 += 38 * t16;
11293 t1 += 38 * t17;
11294 t2 += 38 * t18;
11295 t3 += 38 * t19;
11296 t4 += 38 * t20;
11297 t5 += 38 * t21;
11298 t6 += 38 * t22;
11299 t7 += 38 * t23;
11300 t8 += 38 * t24;
11301 t9 += 38 * t25;
11302 t10 += 38 * t26;
11303 t11 += 38 * t27;
11304 t12 += 38 * t28;
11305 t13 += 38 * t29;
11306 t14 += 38 * t30;
11307 // t15 left as is
11308
11309 // first car
11310 c = 1;
11311 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
11312 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
11313 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
11314 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
11315 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
11316 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
11317 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
11318 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
11319 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
11320 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
11321 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
11322 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
11323 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
11324 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
11325 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
11326 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
11327 t0 += c-1 + 37 * (c-1);
11328
11329 // second car
11330 c = 1;
11331 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
11332 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
11333 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
11334 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
11335 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
11336 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
11337 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
11338 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
11339 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
11340 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
11341 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
11342 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
11343 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
11344 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
11345 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
11346 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
11347 t0 += c-1 + 37 * (c-1);
11348
11349 o[ 0] = t0;
11350 o[ 1] = t1;
11351 o[ 2] = t2;
11352 o[ 3] = t3;
11353 o[ 4] = t4;
11354 o[ 5] = t5;
11355 o[ 6] = t6;
11356 o[ 7] = t7;
11357 o[ 8] = t8;
11358 o[ 9] = t9;
11359 o[10] = t10;
11360 o[11] = t11;
11361 o[12] = t12;
11362 o[13] = t13;
11363 o[14] = t14;
11364 o[15] = t15;
11365 }
11366
11367 function S(o, a) {
11368 M(o, a, a);
11369 }
11370
11371 function inv25519(o, i) {
11372 var c = gf();
11373 var a;
11374 for (a = 0; a < 16; a++) c[a] = i[a];
11375 for (a = 253; a >= 0; a--) {
11376 S(c, c);
11377 if(a !== 2 && a !== 4) M(c, c, i);
11378 }
11379 for (a = 0; a < 16; a++) o[a] = c[a];
11380 }
11381
11382 function pow2523(o, i) {
11383 var c = gf();
11384 var a;
11385 for (a = 0; a < 16; a++) c[a] = i[a];
11386 for (a = 250; a >= 0; a--) {
11387 S(c, c);
11388 if(a !== 1) M(c, c, i);
11389 }
11390 for (a = 0; a < 16; a++) o[a] = c[a];
11391 }
11392
11393 function crypto_scalarmult(q, n, p) {
11394 var z = new Uint8Array(32);
11395 var x = new Float64Array(80), r, i;
11396 var a = gf(), b = gf(), c = gf(),
11397 d = gf(), e = gf(), f = gf();
11398 for (i = 0; i < 31; i++) z[i] = n[i];
11399 z[31]=(n[31]&127)|64;
11400 z[0]&=248;
11401 unpack25519(x,p);
11402 for (i = 0; i < 16; i++) {
11403 b[i]=x[i];
11404 d[i]=a[i]=c[i]=0;
11405 }
11406 a[0]=d[0]=1;
11407 for (i=254; i>=0; --i) {
11408 r=(z[i>>>3]>>>(i&7))&1;
11409 sel25519(a,b,r);
11410 sel25519(c,d,r);
11411 A(e,a,c);
11412 Z(a,a,c);
11413 A(c,b,d);
11414 Z(b,b,d);
11415 S(d,e);
11416 S(f,a);
11417 M(a,c,a);
11418 M(c,b,e);
11419 A(e,a,c);
11420 Z(a,a,c);
11421 S(b,a);
11422 Z(c,d,f);
11423 M(a,c,_121665);
11424 A(a,a,d);
11425 M(c,c,a);
11426 M(a,d,f);
11427 M(d,b,x);
11428 S(b,e);
11429 sel25519(a,b,r);
11430 sel25519(c,d,r);
11431 }
11432 for (i = 0; i < 16; i++) {
11433 x[i+16]=a[i];
11434 x[i+32]=c[i];
11435 x[i+48]=b[i];
11436 x[i+64]=d[i];
11437 }
11438 var x32 = x.subarray(32);
11439 var x16 = x.subarray(16);
11440 inv25519(x32,x32);
11441 M(x16,x16,x32);
11442 pack25519(q,x16);
11443 return 0;
11444 }
11445
11446 function crypto_scalarmult_base(q, n) {
11447 return crypto_scalarmult(q, n, _9);
11448 }
11449
11450 function crypto_box_keypair(y, x) {
11451 randombytes(x, 32);
11452 return crypto_scalarmult_base(y, x);
11453 }
11454
11455 function add(p, q) {
11456 var a = gf(), b = gf(), c = gf(),
11457 d = gf(), e = gf(), f = gf(),
11458 g = gf(), h = gf(), t = gf();
11459
11460 Z(a, p[1], p[0]);
11461 Z(t, q[1], q[0]);
11462 M(a, a, t);
11463 A(b, p[0], p[1]);
11464 A(t, q[0], q[1]);
11465 M(b, b, t);
11466 M(c, p[3], q[3]);
11467 M(c, c, D2);
11468 M(d, p[2], q[2]);
11469 A(d, d, d);
11470 Z(e, b, a);
11471 Z(f, d, c);
11472 A(g, d, c);
11473 A(h, b, a);
11474
11475 M(p[0], e, f);
11476 M(p[1], h, g);
11477 M(p[2], g, f);
11478 M(p[3], e, h);
11479 }
11480
11481 function cswap(p, q, b) {
11482 var i;
11483 for (i = 0; i < 4; i++) {
11484 sel25519(p[i], q[i], b);
11485 }
11486 }
11487
11488 function pack(r, p) {
11489 var tx = gf(), ty = gf(), zi = gf();
11490 inv25519(zi, p[2]);
11491 M(tx, p[0], zi);
11492 M(ty, p[1], zi);
11493 pack25519(r, ty);
11494 r[31] ^= par25519(tx) << 7;
11495 }
11496
11497 function scalarmult(p, q, s) {
11498 var b, i;
11499 set25519(p[0], gf0);
11500 set25519(p[1], gf1);
11501 set25519(p[2], gf1);
11502 set25519(p[3], gf0);
11503 for (i = 255; i >= 0; --i) {
11504 b = (s[(i/8)|0] >> (i&7)) & 1;
11505 cswap(p, q, b);
11506 add(q, p);
11507 add(p, p);
11508 cswap(p, q, b);
11509 }
11510 }
11511
11512 function scalarbase(p, s) {
11513 var q = [gf(), gf(), gf(), gf()];
11514 set25519(q[0], X);
11515 set25519(q[1], Y);
11516 set25519(q[2], gf1);
11517 M(q[3], X, Y);
11518 scalarmult(p, q, s);
11519 }
11520
11521 function crypto_sign_keypair(pk, sk, seeded) {
11522 var d;
11523 var p = [gf(), gf(), gf(), gf()];
11524 var i;
11525
11526 if (!seeded) randombytes(sk, 32);
11527 d = nacl.hash(sk.subarray(0, 32));
11528 d[0] &= 248;
11529 d[31] &= 127;
11530 d[31] |= 64;
11531
11532 scalarbase(p, d);
11533 pack(pk, p);
11534
11535 for (i = 0; i < 32; i++) sk[i+32] = pk[i];
11536 return 0;
11537 }
11538
11539 var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);
11540
11541 function modL(r, x) {
11542 var carry, i, j, k;
11543 for (i = 63; i >= 32; --i) {
11544 carry = 0;
11545 for (j = i - 32, k = i - 12; j < k; ++j) {
11546 x[j] += carry - 16 * x[i] * L[j - (i - 32)];
11547 carry = Math.floor((x[j] + 128) / 256);
11548 x[j] -= carry * 256;
11549 }
11550 x[j] += carry;
11551 x[i] = 0;
11552 }
11553 carry = 0;
11554 for (j = 0; j < 32; j++) {
11555 x[j] += carry - (x[31] >> 4) * L[j];
11556 carry = x[j] >> 8;
11557 x[j] &= 255;
11558 }
11559 for (j = 0; j < 32; j++) x[j] -= carry * L[j];
11560 for (i = 0; i < 32; i++) {
11561 x[i+1] += x[i] >> 8;
11562 r[i] = x[i] & 255;
11563 }
11564 }
11565
11566 function reduce(r) {
11567 var x = new Float64Array(64), i;
11568 for (i = 0; i < 64; i++) x[i] = r[i];
11569 for (i = 0; i < 64; i++) r[i] = 0;
11570 modL(r, x);
11571 }
11572
11573 // Note: difference from C - smlen returned, not passed as argument.
11574 function crypto_sign(sm, m, n, sk) {
11575 var d, h, r;
11576 var i, j, x = new Float64Array(64);
11577 var p = [gf(), gf(), gf(), gf()];
11578
11579 d = nacl.hash(sk.subarray(0, 32));
11580 d[0] &= 248;
11581 d[31] &= 127;
11582 d[31] |= 64;
11583
11584 var smlen = n + 64;
11585 for (i = 0; i < n; i++) sm[64 + i] = m[i];
11586 for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
11587
11588 r = nacl.hash(sm.subarray(32, smlen));
11589 reduce(r);
11590 scalarbase(p, r);
11591 pack(sm, p);
11592
11593 for (i = 32; i < 64; i++) sm[i] = sk[i];
11594 h = nacl.hash(sm.subarray(0, smlen));
11595 reduce(h);
11596
11597 for (i = 0; i < 64; i++) x[i] = 0;
11598 for (i = 0; i < 32; i++) x[i] = r[i];
11599 for (i = 0; i < 32; i++) {
11600 for (j = 0; j < 32; j++) {
11601 x[i+j] += h[i] * d[j];
11602 }
11603 }
11604
11605 modL(sm.subarray(32), x);
11606 return smlen;
11607 }
11608
11609 function unpackneg(r, p) {
11610 var t = gf(), chk = gf(), num = gf(),
11611 den = gf(), den2 = gf(), den4 = gf(),
11612 den6 = gf();
11613
11614 set25519(r[2], gf1);
11615 unpack25519(r[1], p);
11616 S(num, r[1]);
11617 M(den, num, D);
11618 Z(num, num, r[2]);
11619 A(den, r[2], den);
11620
11621 S(den2, den);
11622 S(den4, den2);
11623 M(den6, den4, den2);
11624 M(t, den6, num);
11625 M(t, t, den);
11626
11627 pow2523(t, t);
11628 M(t, t, num);
11629 M(t, t, den);
11630 M(t, t, den);
11631 M(r[0], t, den);
11632
11633 S(chk, r[0]);
11634 M(chk, chk, den);
11635 if (neq25519(chk, num)) M(r[0], r[0], I);
11636
11637 S(chk, r[0]);
11638 M(chk, chk, den);
11639 if (neq25519(chk, num)) return -1;
11640
11641 if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);
11642
11643 M(r[3], r[0], r[1]);
11644 return 0;
11645 }
11646
11647 function crypto_sign_open(m, sm, n, pk) {
11648 var i;
11649 var t = new Uint8Array(32), h;
11650 var p = [gf(), gf(), gf(), gf()],
11651 q = [gf(), gf(), gf(), gf()];
11652
11653 if (n < 64) return -1;
11654
11655 if (unpackneg(q, pk)) return -1;
11656
11657 for (i = 0; i < n; i++) m[i] = sm[i];
11658 for (i = 0; i < 32; i++) m[i+32] = pk[i];
11659 h = nacl.hash(m.subarray(0, n));
11660 reduce(h);
11661 scalarmult(p, q, h);
11662
11663 scalarbase(q, sm.subarray(32));
11664 add(p, q);
11665 pack(t, p);
11666
11667 n -= 64;
11668 if (crypto_verify_32(sm, 0, t, 0)) {
11669 for (i = 0; i < n; i++) m[i] = 0;
11670 return -1;
11671 }
11672
11673 for (i = 0; i < n; i++) m[i] = sm[i + 64];
11674 return n;
11675 }
11676
11677 var crypto_scalarmult_BYTES = 32,
11678 crypto_scalarmult_SCALARBYTES = 32,
11679 crypto_box_PUBLICKEYBYTES = 32,
11680 crypto_box_SECRETKEYBYTES = 32,
11681 crypto_sign_BYTES = 64,
11682 crypto_sign_PUBLICKEYBYTES = 32,
11683 crypto_sign_SECRETKEYBYTES = 64,
11684 crypto_sign_SEEDBYTES = 32;
11685
11686 function checkArrayTypes() {
11687 for (var i = 0; i < arguments.length; i++) {
11688 if (!(arguments[i] instanceof Uint8Array))
11689 throw new TypeError('unexpected type, use Uint8Array');
11690 }
11691 }
11692
11693 function cleanup(arr) {
11694 for (var i = 0; i < arr.length; i++) arr[i] = 0;
11695 }
11696
11697 nacl.scalarMult = function(n, p) {
11698 checkArrayTypes(n, p);
11699 if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
11700 if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
11701 var q = new Uint8Array(crypto_scalarmult_BYTES);
11702 crypto_scalarmult(q, n, p);
11703 return q;
11704 };
11705
11706 nacl.box = {};
11707
11708 nacl.box.keyPair = function() {
11709 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
11710 var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
11711 crypto_box_keypair(pk, sk);
11712 return {publicKey: pk, secretKey: sk};
11713 };
11714
11715 nacl.box.keyPair.fromSecretKey = function(secretKey) {
11716 checkArrayTypes(secretKey);
11717 if (secretKey.length !== crypto_box_SECRETKEYBYTES)
11718 throw new Error('bad secret key size');
11719 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
11720 crypto_scalarmult_base(pk, secretKey);
11721 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
11722 };
11723
11724 nacl.sign = function(msg, secretKey) {
11725 checkArrayTypes(msg, secretKey);
11726 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
11727 throw new Error('bad secret key size');
11728 var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
11729 crypto_sign(signedMsg, msg, msg.length, secretKey);
11730 return signedMsg;
11731 };
11732
11733 nacl.sign.detached = function(msg, secretKey) {
11734 var signedMsg = nacl.sign(msg, secretKey);
11735 var sig = new Uint8Array(crypto_sign_BYTES);
11736 for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
11737 return sig;
11738 };
11739
11740 nacl.sign.detached.verify = function(msg, sig, publicKey) {
11741 checkArrayTypes(msg, sig, publicKey);
11742 if (sig.length !== crypto_sign_BYTES)
11743 throw new Error('bad signature size');
11744 if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
11745 throw new Error('bad public key size');
11746 var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
11747 var m = new Uint8Array(crypto_sign_BYTES + msg.length);
11748 var i;
11749 for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
11750 for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
11751 return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
11752 };
11753
11754 nacl.sign.keyPair = function() {
11755 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
11756 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
11757 crypto_sign_keypair(pk, sk);
11758 return {publicKey: pk, secretKey: sk};
11759 };
11760
11761 nacl.sign.keyPair.fromSecretKey = function(secretKey) {
11762 checkArrayTypes(secretKey);
11763 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
11764 throw new Error('bad secret key size');
11765 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
11766 for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
11767 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
11768 };
11769
11770 nacl.sign.keyPair.fromSeed = function(seed) {
11771 checkArrayTypes(seed);
11772 if (seed.length !== crypto_sign_SEEDBYTES)
11773 throw new Error('bad seed size');
11774 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
11775 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
11776 for (var i = 0; i < 32; i++) sk[i] = seed[i];
11777 crypto_sign_keypair(pk, sk, true);
11778 return {publicKey: pk, secretKey: sk};
11779 };
11780
11781 nacl.setPRNG = function(fn) {
11782 randombytes = fn;
11783 };
11784
11785 (function() {
11786 // Initialize PRNG if environment provides CSPRNG.
11787 // If not, methods calling randombytes will throw.
11788 var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
11789 if (crypto && crypto.getRandomValues) {
11790 // Browsers.
11791 var QUOTA = 65536;
11792 nacl.setPRNG(function(x, n) {
11793 var i, v = new Uint8Array(n);
11794 for (i = 0; i < n; i += QUOTA) {
11795 crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
11796 }
11797 for (i = 0; i < n; i++) x[i] = v[i];
11798 cleanup(v);
11799 });
11800 } else if (typeof commonjsRequire !== 'undefined') {
11801 // Node.js.
11802 crypto = void('crypto');
11803 if (crypto && crypto.randomBytes) {
11804 nacl.setPRNG(function(x, n) {
11805 var i, v = crypto.randomBytes(n);
11806 for (i = 0; i < n; i++) x[i] = v[i];
11807 cleanup(v);
11808 });
11809 }
11810 }
11811 })();
11812
11813 })(module.exports ? module.exports : (self.nacl = self.nacl || {}));
11814 });
11815
11816 // GPG4Browsers - An OpenPGP implementation in javascript
11817
11818 const nodeCrypto$5 = util.getNodeCrypto();
11819
11820 /**
11821 * Buffer for secure random numbers
11822 */
11823 class RandomBuffer {
11824 constructor() {
11825 this.buffer = null;
11826 this.size = null;
11827 this.callback = null;
11828 }
11829
11830 /**
11831 * Initialize buffer
11832 * @param {Integer} size - size of buffer
11833 */
11834 init(size, callback) {
11835 this.buffer = new Uint8Array(size);
11836 this.size = 0;
11837 this.callback = callback;
11838 }
11839
11840 /**
11841 * Concat array of secure random numbers to buffer
11842 * @param {Uint8Array} buf
11843 */
11844 set(buf) {
11845 if (!this.buffer) {
11846 throw new Error('RandomBuffer is not initialized');
11847 }
11848 if (!(buf instanceof Uint8Array)) {
11849 throw new Error('Invalid type: buf not an Uint8Array');
11850 }
11851 const freeSpace = this.buffer.length - this.size;
11852 if (buf.length > freeSpace) {
11853 buf = buf.subarray(0, freeSpace);
11854 }
11855 // set buf with offset old size of buffer
11856 this.buffer.set(buf, this.size);
11857 this.size += buf.length;
11858 }
11859
11860 /**
11861 * Take numbers out of buffer and copy to array
11862 * @param {Uint8Array} buf - The destination array
11863 */
11864 async get(buf) {
11865 if (!this.buffer) {
11866 throw new Error('RandomBuffer is not initialized');
11867 }
11868 if (!(buf instanceof Uint8Array)) {
11869 throw new Error('Invalid type: buf not an Uint8Array');
11870 }
11871 if (this.size < buf.length) {
11872 if (!this.callback) {
11873 throw new Error('Random number buffer depleted');
11874 }
11875 // Wait for random bytes from main context, then try again
11876 await this.callback();
11877 return this.get(buf);
11878 }
11879 for (let i = 0; i < buf.length; i++) {
11880 buf[i] = this.buffer[--this.size];
11881 // clear buffer value
11882 this.buffer[this.size] = 0;
11883 }
11884 }
11885 }
11886
11887 /**
11888 * Retrieve secure random byte array of the specified length
11889 * @param {Integer} length - Length in bytes to generate
11890 * @returns {Promise<Uint8Array>} Random byte array.
11891 * @async
11892 */
11893 async function getRandomBytes(length) {
11894 const buf = new Uint8Array(length);
11895 if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
11896 crypto.getRandomValues(buf);
11897 } else if (nodeCrypto$5) {
11898 const bytes = nodeCrypto$5.randomBytes(buf.length);
11899 buf.set(bytes);
11900 } else if (randomBuffer.buffer) {
11901 await randomBuffer.get(buf);
11902 } else {
11903 throw new Error('No secure random number generator available.');
11904 }
11905 return buf;
11906 }
11907
11908 /**
11909 * Create a secure random BigInteger that is greater than or equal to min and less than max.
11910 * @param {module:BigInteger} min - Lower bound, included
11911 * @param {module:BigInteger} max - Upper bound, excluded
11912 * @returns {Promise<module:BigInteger>} Random BigInteger.
11913 * @async
11914 */
11915 async function getRandomBigInteger(min, max) {
11916 const BigInteger = await util.getBigInteger();
11917
11918 if (max.lt(min)) {
11919 throw new Error('Illegal parameter value: max <= min');
11920 }
11921
11922 const modulus = max.sub(min);
11923 const bytes = modulus.byteLength();
11924
11925 // Using a while loop is necessary to avoid bias introduced by the mod operation.
11926 // However, we request 64 extra random bits so that the bias is negligible.
11927 // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
11928 const r = new BigInteger(await getRandomBytes(bytes + 8));
11929 return r.mod(modulus).add(min);
11930 }
11931
11932 const randomBuffer = new RandomBuffer();
11933
11934 var random = /*#__PURE__*/Object.freeze({
11935 __proto__: null,
11936 getRandomBytes: getRandomBytes,
11937 getRandomBigInteger: getRandomBigInteger,
11938 randomBuffer: randomBuffer
11939 });
11940
11941 // OpenPGP.js - An OpenPGP implementation in javascript
11942
11943 /**
11944 * Generate a probably prime random number
11945 * @param {Integer} bits - Bit length of the prime
11946 * @param {BigInteger} e - Optional RSA exponent to check against the prime
11947 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
11948 * @returns BigInteger
11949 * @async
11950 */
11951 async function randomProbablePrime(bits, e, k) {
11952 const BigInteger = await util.getBigInteger();
11953 const one = new BigInteger(1);
11954 const min = one.leftShift(new BigInteger(bits - 1));
11955 const thirty = new BigInteger(30);
11956 /*
11957 * We can avoid any multiples of 3 and 5 by looking at n mod 30
11958 * 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
11959 * the next possible prime is mod 30:
11960 * 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
11961 */
11962 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];
11963
11964 const n = await getRandomBigInteger(min, min.leftShift(one));
11965 let i = n.mod(thirty).toNumber();
11966
11967 do {
11968 n.iadd(new BigInteger(adds[i]));
11969 i = (i + adds[i]) % adds.length;
11970 // If reached the maximum, go back to the minimum.
11971 if (n.bitLength() > bits) {
11972 n.imod(min.leftShift(one)).iadd(min);
11973 i = n.mod(thirty).toNumber();
11974 }
11975 } while (!await isProbablePrime(n, e, k));
11976 return n;
11977 }
11978
11979 /**
11980 * Probabilistic primality testing
11981 * @param {BigInteger} n - Number to test
11982 * @param {BigInteger} e - Optional RSA exponent to check against the prime
11983 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
11984 * @returns {boolean}
11985 * @async
11986 */
11987 async function isProbablePrime(n, e, k) {
11988 if (e && !n.dec().gcd(e).isOne()) {
11989 return false;
11990 }
11991 if (!await divisionTest(n)) {
11992 return false;
11993 }
11994 if (!await fermat(n)) {
11995 return false;
11996 }
11997 if (!await millerRabin(n, k)) {
11998 return false;
11999 }
12000 // TODO implement the Lucas test
12001 // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
12002 return true;
12003 }
12004
12005 /**
12006 * Tests whether n is probably prime or not using Fermat's test with b = 2.
12007 * Fails if b^(n-1) mod n != 1.
12008 * @param {BigInteger} n - Number to test
12009 * @param {BigInteger} b - Optional Fermat test base
12010 * @returns {boolean}
12011 */
12012 async function fermat(n, b) {
12013 const BigInteger = await util.getBigInteger();
12014 b = b || new BigInteger(2);
12015 return b.modExp(n.dec(), n).isOne();
12016 }
12017
12018 async function divisionTest(n) {
12019 const BigInteger = await util.getBigInteger();
12020 return smallPrimes.every(m => {
12021 return n.mod(new BigInteger(m)) !== 0;
12022 });
12023 }
12024
12025 // https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c
12026 const smallPrimes = [
12027 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
12028 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
12029 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
12030 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
12031 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,
12032 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
12033 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,
12034 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,
12035 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
12036 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,
12037 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
12038 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
12039 709, 719, 727, 733, 739, 743, 751, 757, 761, 769,
12040 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,
12041 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
12042 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,
12043 991, 997, 1009, 1013, 1019, 1021, 1031, 1033,
12044 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,
12045 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
12046 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,
12047 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,
12048 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,
12049 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,
12050 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
12051 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,
12052 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,
12053 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,
12054 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,
12055 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
12056 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,
12057 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,
12058 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,
12059 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,
12060 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
12061 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,
12062 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,
12063 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,
12064 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,
12065 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
12066 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,
12067 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,
12068 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,
12069 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,
12070 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
12071 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,
12072 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,
12073 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,
12074 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,
12075 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
12076 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,
12077 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,
12078 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,
12079 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,
12080 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
12081 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,
12082 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,
12083 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,
12084 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,
12085 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
12086 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,
12087 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,
12088 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,
12089 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,
12090 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
12091 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,
12092 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,
12093 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,
12094 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,
12095 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
12096 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,
12097 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,
12098 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,
12099 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,
12100 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,
12101 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,
12102 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,
12103 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,
12104 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,
12105 4957, 4967, 4969, 4973, 4987, 4993, 4999
12106 ];
12107
12108
12109 // Miller-Rabin - Miller Rabin algorithm for primality test
12110 // Copyright Fedor Indutny, 2014.
12111 //
12112 // This software is licensed under the MIT License.
12113 //
12114 // Permission is hereby granted, free of charge, to any person obtaining a
12115 // copy of this software and associated documentation files (the
12116 // "Software"), to deal in the Software without restriction, including
12117 // without limitation the rights to use, copy, modify, merge, publish,
12118 // distribute, sublicense, and/or sell copies of the Software, and to permit
12119 // persons to whom the Software is furnished to do so, subject to the
12120 // following conditions:
12121 //
12122 // The above copyright notice and this permission notice shall be included
12123 // in all copies or substantial portions of the Software.
12124 //
12125 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12126 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12127 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12128 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12129 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12130 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12131 // USE OR OTHER DEALINGS IN THE SOFTWARE.
12132
12133 // Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin
12134
12135 // Sample syntax for Fixed-Base Miller-Rabin:
12136 // millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))
12137
12138 /**
12139 * Tests whether n is probably prime or not using the Miller-Rabin test.
12140 * See HAC Remark 4.28.
12141 * @param {BigInteger} n - Number to test
12142 * @param {Integer} k - Optional number of iterations of Miller-Rabin test
12143 * @param {Function} rand - Optional function to generate potential witnesses
12144 * @returns {boolean}
12145 * @async
12146 */
12147 async function millerRabin(n, k, rand) {
12148 const BigInteger = await util.getBigInteger();
12149 const len = n.bitLength();
12150
12151 if (!k) {
12152 k = Math.max(1, (len / 48) | 0);
12153 }
12154
12155 const n1 = n.dec(); // n - 1
12156
12157 // Find d and s, (n - 1) = (2 ^ s) * d;
12158 let s = 0;
12159 while (!n1.getBit(s)) { s++; }
12160 const d = n.rightShift(new BigInteger(s));
12161
12162 for (; k > 0; k--) {
12163 const a = rand ? rand() : await getRandomBigInteger(new BigInteger(2), n1);
12164
12165 let x = a.modExp(d, n);
12166 if (x.isOne() || x.equal(n1)) {
12167 continue;
12168 }
12169
12170 let i;
12171 for (i = 1; i < s; i++) {
12172 x = x.mul(x).mod(n);
12173
12174 if (x.isOne()) {
12175 return false;
12176 }
12177 if (x.equal(n1)) {
12178 break;
12179 }
12180 }
12181
12182 if (i === s) {
12183 return false;
12184 }
12185 }
12186
12187 return true;
12188 }
12189
12190 // GPG4Browsers - An OpenPGP implementation in javascript
12191
12192 /**
12193 * ASN1 object identifiers for hashes
12194 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}
12195 */
12196 const hash_headers = [];
12197 hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04,
12198 0x10];
12199 hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];
12200 hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];
12201 hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00,
12202 0x04, 0x20];
12203 hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00,
12204 0x04, 0x30];
12205 hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
12206 0x00, 0x04, 0x40];
12207 hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05,
12208 0x00, 0x04, 0x1C];
12209
12210 /**
12211 * Create padding with secure random data
12212 * @private
12213 * @param {Integer} length - Length of the padding in bytes
12214 * @returns {Promise<Uint8Array>} Random padding.
12215 * @async
12216 */
12217 async function getPKCS1Padding(length) {
12218 const result = new Uint8Array(length);
12219 let count = 0;
12220 while (count < length) {
12221 const randomBytes = await getRandomBytes(length - count);
12222 for (let i = 0; i < randomBytes.length; i++) {
12223 if (randomBytes[i] !== 0) {
12224 result[count++] = randomBytes[i];
12225 }
12226 }
12227 }
12228 return result;
12229 }
12230
12231 /**
12232 * Create a EME-PKCS1-v1_5 padded message
12233 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}
12234 * @param {Uint8Array} message - Message to be encoded
12235 * @param {Integer} keyLength - The length in octets of the key modulus
12236 * @returns {Promise<Uint8Array>} EME-PKCS1 padded message.
12237 * @async
12238 */
12239 async function emeEncode(message, keyLength) {
12240 const mLength = message.length;
12241 // length checking
12242 if (mLength > keyLength - 11) {
12243 throw new Error('Message too long');
12244 }
12245 // Generate an octet string PS of length k - mLen - 3 consisting of
12246 // pseudo-randomly generated nonzero octets
12247 const PS = await getPKCS1Padding(keyLength - mLength - 3);
12248 // Concatenate PS, the message M, and other padding to form an
12249 // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.
12250 const encoded = new Uint8Array(keyLength);
12251 // 0x00 byte
12252 encoded[1] = 2;
12253 encoded.set(PS, 2);
12254 // 0x00 bytes
12255 encoded.set(message, keyLength - mLength);
12256 return encoded;
12257 }
12258
12259 /**
12260 * Decode a EME-PKCS1-v1_5 padded message
12261 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}
12262 * @param {Uint8Array} encoded - Encoded message bytes
12263 * @returns {Uint8Array} Message.
12264 */
12265 function emeDecode(encoded) {
12266 let i = 2;
12267 while (encoded[i] !== 0 && i < encoded.length) {
12268 i++;
12269 }
12270 const psLen = i - 2;
12271 const separator = encoded[i++];
12272 if (encoded[0] === 0 && encoded[1] === 2 && psLen >= 8 && separator === 0) {
12273 return encoded.subarray(i);
12274 }
12275 throw new Error('Decryption error');
12276 }
12277
12278 /**
12279 * Create a EMSA-PKCS1-v1_5 padded message
12280 * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}
12281 * @param {Integer} algo - Hash algorithm type used
12282 * @param {Uint8Array} hashed - Message to be encoded
12283 * @param {Integer} emLen - Intended length in octets of the encoded message
12284 * @returns {Uint8Array} Encoded message.
12285 */
12286 async function emsaEncode(algo, hashed, emLen) {
12287 let i;
12288 if (hashed.length !== hash.getHashByteLength(algo)) {
12289 throw new Error('Invalid hash length');
12290 }
12291 // produce an ASN.1 DER value for the hash function used.
12292 // Let T be the full hash prefix
12293 const hashPrefix = new Uint8Array(hash_headers[algo].length);
12294 for (i = 0; i < hash_headers[algo].length; i++) {
12295 hashPrefix[i] = hash_headers[algo][i];
12296 }
12297 // and let tLen be the length in octets prefix and hashed data
12298 const tLen = hashPrefix.length + hashed.length;
12299 if (emLen < tLen + 11) {
12300 throw new Error('Intended encoded message length too short');
12301 }
12302 // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF
12303 // The length of PS will be at least 8 octets
12304 const PS = new Uint8Array(emLen - tLen - 3).fill(0xff);
12305
12306 // Concatenate PS, the hash prefix, hashed data, and other padding to form the
12307 // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || prefix || hashed
12308 const EM = new Uint8Array(emLen);
12309 EM[1] = 0x01;
12310 EM.set(PS, 2);
12311 EM.set(hashPrefix, emLen - tLen);
12312 EM.set(hashed, emLen - hashed.length);
12313 return EM;
12314 }
12315
12316 var pkcs1 = /*#__PURE__*/Object.freeze({
12317 __proto__: null,
12318 emeEncode: emeEncode,
12319 emeDecode: emeDecode,
12320 emsaEncode: emsaEncode
12321 });
12322
12323 // GPG4Browsers - An OpenPGP implementation in javascript
12324
12325 const webCrypto$5 = util.getWebCrypto();
12326 const nodeCrypto$6 = util.getNodeCrypto();
12327 const asn1 = nodeCrypto$6 ? void('asn1.js') : undefined;
12328
12329 /* eslint-disable no-invalid-this */
12330 const RSAPrivateKey = util.detectNode() ? asn1.define('RSAPrivateKey', function () {
12331 this.seq().obj( // used for native NodeJS crypto
12332 this.key('version').int(), // 0
12333 this.key('modulus').int(), // n
12334 this.key('publicExponent').int(), // e
12335 this.key('privateExponent').int(), // d
12336 this.key('prime1').int(), // p
12337 this.key('prime2').int(), // q
12338 this.key('exponent1').int(), // dp
12339 this.key('exponent2').int(), // dq
12340 this.key('coefficient').int() // u
12341 );
12342 }) : undefined;
12343
12344 const RSAPublicKey = util.detectNode() ? asn1.define('RSAPubliceKey', function () {
12345 this.seq().obj( // used for native NodeJS crypto
12346 this.key('modulus').int(), // n
12347 this.key('publicExponent').int(), // e
12348 );
12349 }) : undefined;
12350 /* eslint-enable no-invalid-this */
12351
12352 /** Create signature
12353 * @param {module:enums.hash} hashAlgo - Hash algorithm
12354 * @param {Uint8Array} data - Message
12355 * @param {Uint8Array} n - RSA public modulus
12356 * @param {Uint8Array} e - RSA public exponent
12357 * @param {Uint8Array} d - RSA private exponent
12358 * @param {Uint8Array} p - RSA private prime p
12359 * @param {Uint8Array} q - RSA private prime q
12360 * @param {Uint8Array} u - RSA private coefficient
12361 * @param {Uint8Array} hashed - Hashed message
12362 * @returns {Promise<Uint8Array>} RSA Signature.
12363 * @async
12364 */
12365 async function sign(hashAlgo, data, n, e, d, p, q, u, hashed) {
12366 if (data && !util.isStream(data)) {
12367 if (util.getWebCrypto()) {
12368 try {
12369 return await webSign(enums.read(enums.webHash, hashAlgo), data, n, e, d, p, q, u);
12370 } catch (err) {
12371 util.printDebugError(err);
12372 }
12373 } else if (util.getNodeCrypto()) {
12374 return nodeSign(hashAlgo, data, n, e, d, p, q, u);
12375 }
12376 }
12377 return bnSign(hashAlgo, n, d, hashed);
12378 }
12379
12380 /**
12381 * Verify signature
12382 * @param {module:enums.hash} hashAlgo - Hash algorithm
12383 * @param {Uint8Array} data - Message
12384 * @param {Uint8Array} s - Signature
12385 * @param {Uint8Array} n - RSA public modulus
12386 * @param {Uint8Array} e - RSA public exponent
12387 * @param {Uint8Array} hashed - Hashed message
12388 * @returns {Boolean}
12389 * @async
12390 */
12391 async function verify(hashAlgo, data, s, n, e, hashed) {
12392 if (data && !util.isStream(data)) {
12393 if (util.getWebCrypto()) {
12394 try {
12395 return await webVerify(enums.read(enums.webHash, hashAlgo), data, s, n, e);
12396 } catch (err) {
12397 util.printDebugError(err);
12398 }
12399 } else if (util.getNodeCrypto()) {
12400 return nodeVerify(hashAlgo, data, s, n, e);
12401 }
12402 }
12403 return bnVerify(hashAlgo, s, n, e, hashed);
12404 }
12405
12406 /**
12407 * Encrypt message
12408 * @param {Uint8Array} data - Message
12409 * @param {Uint8Array} n - RSA public modulus
12410 * @param {Uint8Array} e - RSA public exponent
12411 * @returns {Promise<Uint8Array>} RSA Ciphertext.
12412 * @async
12413 */
12414 async function encrypt$1(data, n, e) {
12415 if (util.getNodeCrypto()) {
12416 return nodeEncrypt$1(data, n, e);
12417 }
12418 return bnEncrypt(data, n, e);
12419 }
12420
12421 /**
12422 * Decrypt RSA message
12423 * @param {Uint8Array} m - Message
12424 * @param {Uint8Array} n - RSA public modulus
12425 * @param {Uint8Array} e - RSA public exponent
12426 * @param {Uint8Array} d - RSA private exponent
12427 * @param {Uint8Array} p - RSA private prime p
12428 * @param {Uint8Array} q - RSA private prime q
12429 * @param {Uint8Array} u - RSA private coefficient
12430 * @returns {Promise<String>} RSA Plaintext.
12431 * @async
12432 */
12433 async function decrypt$1(data, n, e, d, p, q, u) {
12434 if (util.getNodeCrypto()) {
12435 return nodeDecrypt$1(data, n, e, d, p, q, u);
12436 }
12437 return bnDecrypt(data, n, e, d, p, q, u);
12438 }
12439
12440 /**
12441 * Generate a new random private key B bits long with public exponent E.
12442 *
12443 * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using
12444 * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.
12445 * @see module:crypto/public_key/prime
12446 * @param {Integer} bits - RSA bit length
12447 * @param {Integer} e - RSA public exponent
12448 * @returns {{n, e, d,
12449 * p, q ,u: Uint8Array}} RSA public modulus, RSA public exponent, RSA private exponent,
12450 * RSA private prime p, RSA private prime q, u = p ** -1 mod q
12451 * @async
12452 */
12453 async function generate(bits, e) {
12454 const BigInteger = await util.getBigInteger();
12455
12456 e = new BigInteger(e);
12457
12458 // Native RSA keygen using Web Crypto
12459 if (util.getWebCrypto()) {
12460 const keyGenOpt = {
12461 name: 'RSASSA-PKCS1-v1_5',
12462 modulusLength: bits, // the specified keysize in bits
12463 publicExponent: e.toUint8Array(), // take three bytes (max 65537) for exponent
12464 hash: {
12465 name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'
12466 }
12467 };
12468 const keyPair = await webCrypto$5.generateKey(keyGenOpt, true, ['sign', 'verify']);
12469
12470 // export the generated keys as JsonWebKey (JWK)
12471 // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33
12472 const jwk = await webCrypto$5.exportKey('jwk', keyPair.privateKey);
12473 // map JWK parameters to corresponding OpenPGP names
12474 return {
12475 n: b64ToUint8Array(jwk.n),
12476 e: e.toUint8Array(),
12477 d: b64ToUint8Array(jwk.d),
12478 // switch p and q
12479 p: b64ToUint8Array(jwk.q),
12480 q: b64ToUint8Array(jwk.p),
12481 // Since p and q are switched in places, u is the inverse of jwk.q
12482 u: b64ToUint8Array(jwk.qi)
12483 };
12484 } else if (util.getNodeCrypto() && nodeCrypto$6.generateKeyPair && RSAPrivateKey) {
12485 const opts = {
12486 modulusLength: bits,
12487 publicExponent: e.toNumber(),
12488 publicKeyEncoding: { type: 'pkcs1', format: 'der' },
12489 privateKeyEncoding: { type: 'pkcs1', format: 'der' }
12490 };
12491 const prv = await new Promise((resolve, reject) => nodeCrypto$6.generateKeyPair('rsa', opts, (err, _, der) => {
12492 if (err) {
12493 reject(err);
12494 } else {
12495 resolve(RSAPrivateKey.decode(der, 'der'));
12496 }
12497 }));
12498 /**
12499 * OpenPGP spec differs from DER spec, DER: `u = (inverse of q) mod p`, OpenPGP: `u = (inverse of p) mod q`.
12500 * @link https://tools.ietf.org/html/rfc3447#section-3.2
12501 * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1
12502 */
12503 return {
12504 n: prv.modulus.toArrayLike(Uint8Array),
12505 e: prv.publicExponent.toArrayLike(Uint8Array),
12506 d: prv.privateExponent.toArrayLike(Uint8Array),
12507 // switch p and q
12508 p: prv.prime2.toArrayLike(Uint8Array),
12509 q: prv.prime1.toArrayLike(Uint8Array),
12510 // Since p and q are switched in places, we can keep u as defined by DER
12511 u: prv.coefficient.toArrayLike(Uint8Array)
12512 };
12513 }
12514
12515 // RSA keygen fallback using 40 iterations of the Miller-Rabin test
12516 // See https://stackoverflow.com/a/6330138 for justification
12517 // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST
12518 let p;
12519 let q;
12520 let n;
12521 do {
12522 q = await randomProbablePrime(bits - (bits >> 1), e, 40);
12523 p = await randomProbablePrime(bits >> 1, e, 40);
12524 n = p.mul(q);
12525 } while (n.bitLength() !== bits);
12526
12527 const phi = p.dec().imul(q.dec());
12528
12529 if (q.lt(p)) {
12530 [p, q] = [q, p];
12531 }
12532
12533 return {
12534 n: n.toUint8Array(),
12535 e: e.toUint8Array(),
12536 d: e.modInv(phi).toUint8Array(),
12537 p: p.toUint8Array(),
12538 q: q.toUint8Array(),
12539 // dp: d.mod(p.subn(1)),
12540 // dq: d.mod(q.subn(1)),
12541 u: p.modInv(q).toUint8Array()
12542 };
12543 }
12544
12545 /**
12546 * Validate RSA parameters
12547 * @param {Uint8Array} n - RSA public modulus
12548 * @param {Uint8Array} e - RSA public exponent
12549 * @param {Uint8Array} d - RSA private exponent
12550 * @param {Uint8Array} p - RSA private prime p
12551 * @param {Uint8Array} q - RSA private prime q
12552 * @param {Uint8Array} u - RSA inverse of p w.r.t. q
12553 * @returns {Promise<Boolean>} Whether params are valid.
12554 * @async
12555 */
12556 async function validateParams(n, e, d, p, q, u) {
12557 const BigInteger = await util.getBigInteger();
12558 n = new BigInteger(n);
12559 p = new BigInteger(p);
12560 q = new BigInteger(q);
12561
12562 // expect pq = n
12563 if (!p.mul(q).equal(n)) {
12564 return false;
12565 }
12566
12567 const two = new BigInteger(2);
12568 // expect p*u = 1 mod q
12569 u = new BigInteger(u);
12570 if (!p.mul(u).mod(q).isOne()) {
12571 return false;
12572 }
12573
12574 e = new BigInteger(e);
12575 d = new BigInteger(d);
12576 /**
12577 * In RSA pkcs#1 the exponents (d, e) are inverses modulo lcm(p-1, q-1)
12578 * We check that [de = 1 mod (p-1)] and [de = 1 mod (q-1)]
12579 * By CRT on coprime factors of (p-1, q-1) it follows that [de = 1 mod lcm(p-1, q-1)]
12580 *
12581 * We blind the multiplication with r, and check that rde = r mod lcm(p-1, q-1)
12582 */
12583 const nSizeOver3 = new BigInteger(Math.floor(n.bitLength() / 3));
12584 const r = await getRandomBigInteger(two, two.leftShift(nSizeOver3)); // r in [ 2, 2^{|n|/3} ) < p and q
12585 const rde = r.mul(d).mul(e);
12586
12587 const areInverses = rde.mod(p.dec()).equal(r) && rde.mod(q.dec()).equal(r);
12588 if (!areInverses) {
12589 return false;
12590 }
12591
12592 return true;
12593 }
12594
12595 async function bnSign(hashAlgo, n, d, hashed) {
12596 const BigInteger = await util.getBigInteger();
12597 n = new BigInteger(n);
12598 const m = new BigInteger(await emsaEncode(hashAlgo, hashed, n.byteLength()));
12599 d = new BigInteger(d);
12600 if (m.gte(n)) {
12601 throw new Error('Message size cannot exceed modulus size');
12602 }
12603 return m.modExp(d, n).toUint8Array('be', n.byteLength());
12604 }
12605
12606 async function webSign(hashName, data, n, e, d, p, q, u) {
12607 /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.
12608 * We swap them in privateToJWK, so it usually works out, but nevertheless,
12609 * not all OpenPGP keys are compatible with this requirement.
12610 * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still
12611 * does if the underlying Web Crypto does so (e.g. old MS Edge 50% of the time).
12612 */
12613 const jwk = await privateToJWK(n, e, d, p, q, u);
12614 const algo = {
12615 name: 'RSASSA-PKCS1-v1_5',
12616 hash: { name: hashName }
12617 };
12618 const key = await webCrypto$5.importKey('jwk', jwk, algo, false, ['sign']);
12619 // add hash field for ms edge support
12620 return new Uint8Array(await webCrypto$5.sign({ 'name': 'RSASSA-PKCS1-v1_5', 'hash': hashName }, key, data));
12621 }
12622
12623 async function nodeSign(hashAlgo, data, n, e, d, p, q, u) {
12624 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
12625 const pBNum = new BN(p);
12626 const qBNum = new BN(q);
12627 const dBNum = new BN(d);
12628 const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)
12629 const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)
12630 const sign = nodeCrypto$6.createSign(enums.read(enums.hash, hashAlgo));
12631 sign.write(data);
12632 sign.end();
12633 const keyObject = {
12634 version: 0,
12635 modulus: new BN(n),
12636 publicExponent: new BN(e),
12637 privateExponent: new BN(d),
12638 // switch p and q
12639 prime1: new BN(q),
12640 prime2: new BN(p),
12641 // switch dp and dq
12642 exponent1: dq,
12643 exponent2: dp,
12644 coefficient: new BN(u)
12645 };
12646 if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects
12647 const der = RSAPrivateKey.encode(keyObject, 'der');
12648 return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' }));
12649 }
12650 const pem = RSAPrivateKey.encode(keyObject, 'pem', {
12651 label: 'RSA PRIVATE KEY'
12652 });
12653 return new Uint8Array(sign.sign(pem));
12654 }
12655
12656 async function bnVerify(hashAlgo, s, n, e, hashed) {
12657 const BigInteger = await util.getBigInteger();
12658 n = new BigInteger(n);
12659 s = new BigInteger(s);
12660 e = new BigInteger(e);
12661 if (s.gte(n)) {
12662 throw new Error('Signature size cannot exceed modulus size');
12663 }
12664 const EM1 = s.modExp(e, n).toUint8Array('be', n.byteLength());
12665 const EM2 = await emsaEncode(hashAlgo, hashed, n.byteLength());
12666 return util.equalsUint8Array(EM1, EM2);
12667 }
12668
12669 async function webVerify(hashName, data, s, n, e) {
12670 const jwk = publicToJWK(n, e);
12671 const key = await webCrypto$5.importKey('jwk', jwk, {
12672 name: 'RSASSA-PKCS1-v1_5',
12673 hash: { name: hashName }
12674 }, false, ['verify']);
12675 // add hash field for ms edge support
12676 return webCrypto$5.verify({ 'name': 'RSASSA-PKCS1-v1_5', 'hash': hashName }, key, s, data);
12677 }
12678
12679 async function nodeVerify(hashAlgo, data, s, n, e) {
12680 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
12681
12682 const verify = nodeCrypto$6.createVerify(enums.read(enums.hash, hashAlgo));
12683 verify.write(data);
12684 verify.end();
12685 const keyObject = {
12686 modulus: new BN(n),
12687 publicExponent: new BN(e)
12688 };
12689 let key;
12690 if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') { //from version 11.6.0 Node supports der encoded key objects
12691 const der = RSAPublicKey.encode(keyObject, 'der');
12692 key = { key: der, format: 'der', type: 'pkcs1' };
12693 } else {
12694 key = RSAPublicKey.encode(keyObject, 'pem', {
12695 label: 'RSA PUBLIC KEY'
12696 });
12697 }
12698 try {
12699 return await verify.verify(key, s);
12700 } catch (err) {
12701 return false;
12702 }
12703 }
12704
12705 async function nodeEncrypt$1(data, n, e) {
12706 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
12707
12708 const keyObject = {
12709 modulus: new BN(n),
12710 publicExponent: new BN(e)
12711 };
12712 let key;
12713 if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') {
12714 const der = RSAPublicKey.encode(keyObject, 'der');
12715 key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING };
12716 } else {
12717 const pem = RSAPublicKey.encode(keyObject, 'pem', {
12718 label: 'RSA PUBLIC KEY'
12719 });
12720 key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING };
12721 }
12722 return new Uint8Array(nodeCrypto$6.publicEncrypt(key, data));
12723 }
12724
12725 async function bnEncrypt(data, n, e) {
12726 const BigInteger = await util.getBigInteger();
12727 n = new BigInteger(n);
12728 data = new BigInteger(await emeEncode(data, n.byteLength()));
12729 e = new BigInteger(e);
12730 if (data.gte(n)) {
12731 throw new Error('Message size cannot exceed modulus size');
12732 }
12733 return data.modExp(e, n).toUint8Array('be', n.byteLength());
12734 }
12735
12736 async function nodeDecrypt$1(data, n, e, d, p, q, u) {
12737 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
12738
12739 const pBNum = new BN(p);
12740 const qBNum = new BN(q);
12741 const dBNum = new BN(d);
12742 const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)
12743 const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)
12744 const keyObject = {
12745 version: 0,
12746 modulus: new BN(n),
12747 publicExponent: new BN(e),
12748 privateExponent: new BN(d),
12749 // switch p and q
12750 prime1: new BN(q),
12751 prime2: new BN(p),
12752 // switch dp and dq
12753 exponent1: dq,
12754 exponent2: dp,
12755 coefficient: new BN(u)
12756 };
12757 let key;
12758 if (typeof nodeCrypto$6.createPrivateKey !== 'undefined') {
12759 const der = RSAPrivateKey.encode(keyObject, 'der');
12760 key = { key: der, format: 'der' , type: 'pkcs1', padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING };
12761 } else {
12762 const pem = RSAPrivateKey.encode(keyObject, 'pem', {
12763 label: 'RSA PRIVATE KEY'
12764 });
12765 key = { key: pem, padding: nodeCrypto$6.constants.RSA_PKCS1_PADDING };
12766 }
12767 try {
12768 return new Uint8Array(nodeCrypto$6.privateDecrypt(key, data));
12769 } catch (err) {
12770 throw new Error('Decryption error');
12771 }
12772 }
12773
12774 async function bnDecrypt(data, n, e, d, p, q, u) {
12775 const BigInteger = await util.getBigInteger();
12776 data = new BigInteger(data);
12777 n = new BigInteger(n);
12778 e = new BigInteger(e);
12779 d = new BigInteger(d);
12780 p = new BigInteger(p);
12781 q = new BigInteger(q);
12782 u = new BigInteger(u);
12783 if (data.gte(n)) {
12784 throw new Error('Data too large.');
12785 }
12786 const dq = d.mod(q.dec()); // d mod (q-1)
12787 const dp = d.mod(p.dec()); // d mod (p-1)
12788
12789 const unblinder = (await getRandomBigInteger(new BigInteger(2), n)).mod(n);
12790 const blinder = unblinder.modInv(n).modExp(e, n);
12791 data = data.mul(blinder).mod(n);
12792
12793
12794 const mp = data.modExp(dp, p); // data**{d mod (q-1)} mod p
12795 const mq = data.modExp(dq, q); // data**{d mod (p-1)} mod q
12796 const h = u.mul(mq.sub(mp)).mod(q); // u * (mq-mp) mod q (operands already < q)
12797
12798 let result = h.mul(p).add(mp); // result < n due to relations above
12799
12800 result = result.mul(unblinder).mod(n);
12801
12802
12803 return emeDecode(result.toUint8Array('be', n.byteLength()));
12804 }
12805
12806 /** Convert Openpgp private key params to jwk key according to
12807 * @link https://tools.ietf.org/html/rfc7517
12808 * @param {String} hashAlgo
12809 * @param {Uint8Array} n
12810 * @param {Uint8Array} e
12811 * @param {Uint8Array} d
12812 * @param {Uint8Array} p
12813 * @param {Uint8Array} q
12814 * @param {Uint8Array} u
12815 */
12816 async function privateToJWK(n, e, d, p, q, u) {
12817 const BigInteger = await util.getBigInteger();
12818 const pNum = new BigInteger(p);
12819 const qNum = new BigInteger(q);
12820 const dNum = new BigInteger(d);
12821
12822 let dq = dNum.mod(qNum.dec()); // d mod (q-1)
12823 let dp = dNum.mod(pNum.dec()); // d mod (p-1)
12824 dp = dp.toUint8Array();
12825 dq = dq.toUint8Array();
12826 return {
12827 kty: 'RSA',
12828 n: uint8ArrayToB64(n, true),
12829 e: uint8ArrayToB64(e, true),
12830 d: uint8ArrayToB64(d, true),
12831 // switch p and q
12832 p: uint8ArrayToB64(q, true),
12833 q: uint8ArrayToB64(p, true),
12834 // switch dp and dq
12835 dp: uint8ArrayToB64(dq, true),
12836 dq: uint8ArrayToB64(dp, true),
12837 qi: uint8ArrayToB64(u, true),
12838 ext: true
12839 };
12840 }
12841
12842 /** Convert Openpgp key public params to jwk key according to
12843 * @link https://tools.ietf.org/html/rfc7517
12844 * @param {String} hashAlgo
12845 * @param {Uint8Array} n
12846 * @param {Uint8Array} e
12847 */
12848 function publicToJWK(n, e) {
12849 return {
12850 kty: 'RSA',
12851 n: uint8ArrayToB64(n, true),
12852 e: uint8ArrayToB64(e, true),
12853 ext: true
12854 };
12855 }
12856
12857 var rsa = /*#__PURE__*/Object.freeze({
12858 __proto__: null,
12859 sign: sign,
12860 verify: verify,
12861 encrypt: encrypt$1,
12862 decrypt: decrypt$1,
12863 generate: generate,
12864 validateParams: validateParams
12865 });
12866
12867 // GPG4Browsers - An OpenPGP implementation in javascript
12868
12869 /**
12870 * ElGamal Encryption function
12871 * Note that in OpenPGP, the message needs to be padded with PKCS#1 (same as RSA)
12872 * @param {Uint8Array} data - To be padded and encrypted
12873 * @param {Uint8Array} p
12874 * @param {Uint8Array} g
12875 * @param {Uint8Array} y
12876 * @returns {Promise<{ c1: Uint8Array, c2: Uint8Array }>}
12877 * @async
12878 */
12879 async function encrypt$2(data, p, g, y) {
12880 const BigInteger = await util.getBigInteger();
12881 p = new BigInteger(p);
12882 g = new BigInteger(g);
12883 y = new BigInteger(y);
12884
12885 const padded = await emeEncode(data, p.byteLength());
12886 const m = new BigInteger(padded);
12887
12888 // OpenPGP uses a "special" version of ElGamal where g is generator of the full group Z/pZ*
12889 // hence g has order p-1, and to avoid that k = 0 mod p-1, we need to pick k in [1, p-2]
12890 const k = await getRandomBigInteger(new BigInteger(1), p.dec());
12891 return {
12892 c1: g.modExp(k, p).toUint8Array(),
12893 c2: y.modExp(k, p).imul(m).imod(p).toUint8Array()
12894 };
12895 }
12896
12897 /**
12898 * ElGamal Encryption function
12899 * @param {Uint8Array} c1
12900 * @param {Uint8Array} c2
12901 * @param {Uint8Array} p
12902 * @param {Uint8Array} x
12903 * @returns {Promise<Uint8Array>} Unpadded message.
12904 * @async
12905 */
12906 async function decrypt$2(c1, c2, p, x) {
12907 const BigInteger = await util.getBigInteger();
12908 c1 = new BigInteger(c1);
12909 c2 = new BigInteger(c2);
12910 p = new BigInteger(p);
12911 x = new BigInteger(x);
12912
12913 const padded = c1.modExp(x, p).modInv(p).imul(c2).imod(p);
12914 return emeDecode(padded.toUint8Array('be', p.byteLength()));
12915 }
12916
12917 /**
12918 * Validate ElGamal parameters
12919 * @param {Uint8Array} p - ElGamal prime
12920 * @param {Uint8Array} g - ElGamal group generator
12921 * @param {Uint8Array} y - ElGamal public key
12922 * @param {Uint8Array} x - ElGamal private exponent
12923 * @returns {Promise<Boolean>} Whether params are valid.
12924 * @async
12925 */
12926 async function validateParams$1(p, g, y, x) {
12927 const BigInteger = await util.getBigInteger();
12928 p = new BigInteger(p);
12929 g = new BigInteger(g);
12930 y = new BigInteger(y);
12931
12932 const one = new BigInteger(1);
12933 // Check that 1 < g < p
12934 if (g.lte(one) || g.gte(p)) {
12935 return false;
12936 }
12937
12938 // Expect p-1 to be large
12939 const pSize = new BigInteger(p.bitLength());
12940 const n1023 = new BigInteger(1023);
12941 if (pSize.lt(n1023)) {
12942 return false;
12943 }
12944
12945 /**
12946 * g should have order p-1
12947 * Check that g ** (p-1) = 1 mod p
12948 */
12949 if (!g.modExp(p.dec(), p).isOne()) {
12950 return false;
12951 }
12952
12953 /**
12954 * Since p-1 is not prime, g might have a smaller order that divides p-1
12955 * We want to make sure that the order is large enough to hinder a small subgroup attack
12956 *
12957 * We just check g**i != 1 for all i up to a threshold
12958 */
12959 let res = g;
12960 const i = new BigInteger(1);
12961 const threshold = new BigInteger(2).leftShift(new BigInteger(17)); // we want order > threshold
12962 while (i.lt(threshold)) {
12963 res = res.mul(g).imod(p);
12964 if (res.isOne()) {
12965 return false;
12966 }
12967 i.iinc();
12968 }
12969
12970 /**
12971 * Re-derive public key y' = g ** x mod p
12972 * Expect y == y'
12973 *
12974 * Blinded exponentiation computes g**{r(p-1) + x} to compare to y
12975 */
12976 x = new BigInteger(x);
12977 const two = new BigInteger(2);
12978 const r = await getRandomBigInteger(two.leftShift(pSize.dec()), two.leftShift(pSize)); // draw r of same size as p-1
12979 const rqx = p.dec().imul(r).iadd(x);
12980 if (!y.equal(g.modExp(rqx, p))) {
12981 return false;
12982 }
12983
12984 return true;
12985 }
12986
12987 var elgamal = /*#__PURE__*/Object.freeze({
12988 __proto__: null,
12989 encrypt: encrypt$2,
12990 decrypt: decrypt$2,
12991 validateParams: validateParams$1
12992 });
12993
12994 // OpenPGP.js - An OpenPGP implementation in javascript
12995
12996 class OID {
12997 constructor(oid) {
12998 if (oid instanceof OID) {
12999 this.oid = oid.oid;
13000 } else if (util.isArray(oid) ||
13001 util.isUint8Array(oid)) {
13002 oid = new Uint8Array(oid);
13003 if (oid[0] === 0x06) { // DER encoded oid byte array
13004 if (oid[1] !== oid.length - 2) {
13005 throw new Error('Length mismatch in DER encoded oid');
13006 }
13007 oid = oid.subarray(2);
13008 }
13009 this.oid = oid;
13010 } else {
13011 this.oid = '';
13012 }
13013 }
13014
13015 /**
13016 * Method to read an OID object
13017 * @param {Uint8Array} input - Where to read the OID from
13018 * @returns {Number} Number of read bytes.
13019 */
13020 read(input) {
13021 if (input.length >= 1) {
13022 const length = input[0];
13023 if (input.length >= 1 + length) {
13024 this.oid = input.subarray(1, 1 + length);
13025 return 1 + this.oid.length;
13026 }
13027 }
13028 throw new Error('Invalid oid');
13029 }
13030
13031 /**
13032 * Serialize an OID object
13033 * @returns {Uint8Array} Array with the serialized value the OID.
13034 */
13035 write() {
13036 return util.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);
13037 }
13038
13039 /**
13040 * Serialize an OID object as a hex string
13041 * @returns {string} String with the hex value of the OID.
13042 */
13043 toHex() {
13044 return util.uint8ArrayToHex(this.oid);
13045 }
13046
13047 /**
13048 * If a known curve object identifier, return the canonical name of the curve
13049 * @returns {string} String with the canonical name of the curve.
13050 */
13051 getName() {
13052 const hex = this.toHex();
13053 if (enums.curve[hex]) {
13054 return enums.write(enums.curve, hex);
13055 } else {
13056 throw new Error('Unknown curve object identifier.');
13057 }
13058 }
13059 }
13060
13061 // OpenPGP.js - An OpenPGP implementation in javascript
13062
13063 function keyFromPrivate(indutnyCurve, priv) {
13064 const keyPair = indutnyCurve.keyPair({ priv: priv });
13065 return keyPair;
13066 }
13067
13068 function keyFromPublic(indutnyCurve, pub) {
13069 const keyPair = indutnyCurve.keyPair({ pub: pub });
13070 if (keyPair.validate().result !== true) {
13071 throw new Error('Invalid elliptic public key');
13072 }
13073 return keyPair;
13074 }
13075
13076 async function getIndutnyCurve(name) {
13077 if (!defaultConfig.useIndutnyElliptic) {
13078 throw new Error('This curve is only supported in the full build of OpenPGP.js');
13079 }
13080 const { default: elliptic } = await Promise.resolve().then(function () { return elliptic$1; });
13081 return new elliptic.ec(name);
13082 }
13083
13084 // OpenPGP.js - An OpenPGP implementation in javascript
13085
13086 const webCrypto$6 = util.getWebCrypto();
13087 const nodeCrypto$7 = util.getNodeCrypto();
13088
13089 const webCurves = {
13090 'p256': 'P-256',
13091 'p384': 'P-384',
13092 'p521': 'P-521'
13093 };
13094 const knownCurves = nodeCrypto$7 ? nodeCrypto$7.getCurves() : [];
13095 const nodeCurves = nodeCrypto$7 ? {
13096 secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,
13097 p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,
13098 p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,
13099 p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,
13100 ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined,
13101 curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined,
13102 brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,
13103 brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,
13104 brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined
13105 } : {};
13106
13107 const curves = {
13108 p256: {
13109 oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],
13110 keyType: enums.publicKey.ecdsa,
13111 hash: enums.hash.sha256,
13112 cipher: enums.symmetric.aes128,
13113 node: nodeCurves.p256,
13114 web: webCurves.p256,
13115 payloadSize: 32,
13116 sharedSize: 256
13117 },
13118 p384: {
13119 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],
13120 keyType: enums.publicKey.ecdsa,
13121 hash: enums.hash.sha384,
13122 cipher: enums.symmetric.aes192,
13123 node: nodeCurves.p384,
13124 web: webCurves.p384,
13125 payloadSize: 48,
13126 sharedSize: 384
13127 },
13128 p521: {
13129 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],
13130 keyType: enums.publicKey.ecdsa,
13131 hash: enums.hash.sha512,
13132 cipher: enums.symmetric.aes256,
13133 node: nodeCurves.p521,
13134 web: webCurves.p521,
13135 payloadSize: 66,
13136 sharedSize: 528
13137 },
13138 secp256k1: {
13139 oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],
13140 keyType: enums.publicKey.ecdsa,
13141 hash: enums.hash.sha256,
13142 cipher: enums.symmetric.aes128,
13143 node: nodeCurves.secp256k1,
13144 payloadSize: 32
13145 },
13146 ed25519: {
13147 oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],
13148 keyType: enums.publicKey.eddsa,
13149 hash: enums.hash.sha512,
13150 node: false, // nodeCurves.ed25519 TODO
13151 payloadSize: 32
13152 },
13153 curve25519: {
13154 oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],
13155 keyType: enums.publicKey.ecdh,
13156 hash: enums.hash.sha256,
13157 cipher: enums.symmetric.aes128,
13158 node: false, // nodeCurves.curve25519 TODO
13159 payloadSize: 32
13160 },
13161 brainpoolP256r1: {
13162 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],
13163 keyType: enums.publicKey.ecdsa,
13164 hash: enums.hash.sha256,
13165 cipher: enums.symmetric.aes128,
13166 node: nodeCurves.brainpoolP256r1,
13167 payloadSize: 32
13168 },
13169 brainpoolP384r1: {
13170 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],
13171 keyType: enums.publicKey.ecdsa,
13172 hash: enums.hash.sha384,
13173 cipher: enums.symmetric.aes192,
13174 node: nodeCurves.brainpoolP384r1,
13175 payloadSize: 48
13176 },
13177 brainpoolP512r1: {
13178 oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],
13179 keyType: enums.publicKey.ecdsa,
13180 hash: enums.hash.sha512,
13181 cipher: enums.symmetric.aes256,
13182 node: nodeCurves.brainpoolP512r1,
13183 payloadSize: 64
13184 }
13185 };
13186
13187 class Curve {
13188 constructor(oidOrName, params) {
13189 try {
13190 if (util.isArray(oidOrName) ||
13191 util.isUint8Array(oidOrName)) {
13192 // by oid byte array
13193 oidOrName = new OID(oidOrName);
13194 }
13195 if (oidOrName instanceof OID) {
13196 // by curve OID
13197 oidOrName = oidOrName.getName();
13198 }
13199 // by curve name or oid string
13200 this.name = enums.write(enums.curve, oidOrName);
13201 } catch (err) {
13202 throw new Error('Not valid curve');
13203 }
13204 params = params || curves[this.name];
13205
13206 this.keyType = params.keyType;
13207
13208 this.oid = params.oid;
13209 this.hash = params.hash;
13210 this.cipher = params.cipher;
13211 this.node = params.node && curves[this.name];
13212 this.web = params.web && curves[this.name];
13213 this.payloadSize = params.payloadSize;
13214 if (this.web && util.getWebCrypto()) {
13215 this.type = 'web';
13216 } else if (this.node && util.getNodeCrypto()) {
13217 this.type = 'node';
13218 } else if (this.name === 'curve25519') {
13219 this.type = 'curve25519';
13220 } else if (this.name === 'ed25519') {
13221 this.type = 'ed25519';
13222 }
13223 }
13224
13225 async genKeyPair() {
13226 let keyPair;
13227 switch (this.type) {
13228 case 'web':
13229 try {
13230 return await webGenKeyPair(this.name);
13231 } catch (err) {
13232 util.printDebugError('Browser did not support generating ec key ' + err.message);
13233 break;
13234 }
13235 case 'node':
13236 return nodeGenKeyPair(this.name);
13237 case 'curve25519': {
13238 const privateKey = await getRandomBytes(32);
13239 privateKey[0] = (privateKey[0] & 127) | 64;
13240 privateKey[31] &= 248;
13241 const secretKey = privateKey.slice().reverse();
13242 keyPair = naclFastLight.box.keyPair.fromSecretKey(secretKey);
13243 const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);
13244 return { publicKey, privateKey };
13245 }
13246 case 'ed25519': {
13247 const privateKey = await getRandomBytes(32);
13248 const keyPair = naclFastLight.sign.keyPair.fromSeed(privateKey);
13249 const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);
13250 return { publicKey, privateKey };
13251 }
13252 }
13253 const indutnyCurve = await getIndutnyCurve(this.name);
13254 keyPair = await indutnyCurve.genKeyPair({
13255 entropy: util.uint8ArrayToString(await getRandomBytes(32))
13256 });
13257 return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) };
13258 }
13259 }
13260
13261 async function generate$1(curve) {
13262 const BigInteger = await util.getBigInteger();
13263
13264 curve = new Curve(curve);
13265 const keyPair = await curve.genKeyPair();
13266 const Q = new BigInteger(keyPair.publicKey).toUint8Array();
13267 const secret = new BigInteger(keyPair.privateKey).toUint8Array('be', curve.payloadSize);
13268 return {
13269 oid: curve.oid,
13270 Q,
13271 secret,
13272 hash: curve.hash,
13273 cipher: curve.cipher
13274 };
13275 }
13276
13277 function getPreferredHashAlgo(oid) {
13278 return curves[enums.write(enums.curve, oid.toHex())].hash;
13279 }
13280
13281 /**
13282 * Validate ECDH and ECDSA parameters
13283 * Not suitable for EdDSA (different secret key format)
13284 * @param {module:enums.publicKey} algo - EC algorithm, to filter supported curves
13285 * @param {module:type/oid} oid - EC object identifier
13286 * @param {Uint8Array} Q - EC public point
13287 * @param {Uint8Array} d - EC secret scalar
13288 * @returns {Promise<Boolean>} Whether params are valid.
13289 * @async
13290 */
13291 async function validateStandardParams(algo, oid, Q, d) {
13292 const supportedCurves = {
13293 p256: true,
13294 p384: true,
13295 p521: true,
13296 secp256k1: true,
13297 curve25519: algo === enums.publicKey.ecdh,
13298 brainpoolP256r1: true,
13299 brainpoolP384r1: true,
13300 brainpoolP512r1: true
13301 };
13302
13303 // Check whether the given curve is supported
13304 const curveName = oid.getName();
13305 if (!supportedCurves[curveName]) {
13306 return false;
13307 }
13308
13309 if (curveName === 'curve25519') {
13310 d = d.slice().reverse();
13311 // Re-derive public point Q'
13312 const { publicKey } = naclFastLight.box.keyPair.fromSecretKey(d);
13313
13314 Q = new Uint8Array(Q);
13315 const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix
13316 if (!util.equalsUint8Array(dG, Q)) {
13317 return false;
13318 }
13319
13320 return true;
13321 }
13322
13323 const curve = await getIndutnyCurve(curveName);
13324 try {
13325 // Parse Q and check that it is on the curve but not at infinity
13326 Q = keyFromPublic(curve, Q).getPublic();
13327 } catch (validationErrors) {
13328 return false;
13329 }
13330
13331 /**
13332 * Re-derive public point Q' = dG from private key
13333 * Expect Q == Q'
13334 */
13335 const dG = keyFromPrivate(curve, d).getPublic();
13336 if (!dG.eq(Q)) {
13337 return false;
13338 }
13339
13340 return true;
13341 }
13342
13343 //////////////////////////
13344 // //
13345 // Helper functions //
13346 // //
13347 //////////////////////////
13348
13349
13350 async function webGenKeyPair(name) {
13351 // Note: keys generated with ECDSA and ECDH are structurally equivalent
13352 const webCryptoKey = await webCrypto$6.generateKey({ name: 'ECDSA', namedCurve: webCurves[name] }, true, ['sign', 'verify']);
13353
13354 const privateKey = await webCrypto$6.exportKey('jwk', webCryptoKey.privateKey);
13355 const publicKey = await webCrypto$6.exportKey('jwk', webCryptoKey.publicKey);
13356
13357 return {
13358 publicKey: jwkToRawPublic(publicKey),
13359 privateKey: b64ToUint8Array(privateKey.d)
13360 };
13361 }
13362
13363 async function nodeGenKeyPair(name) {
13364 // Note: ECDSA and ECDH key generation is structurally equivalent
13365 const ecdh = nodeCrypto$7.createECDH(nodeCurves[name]);
13366 await ecdh.generateKeys();
13367 return {
13368 publicKey: new Uint8Array(ecdh.getPublicKey()),
13369 privateKey: new Uint8Array(ecdh.getPrivateKey())
13370 };
13371 }
13372
13373 //////////////////////////
13374 // //
13375 // Helper functions //
13376 // //
13377 //////////////////////////
13378
13379 /**
13380 * @param {JsonWebKey} jwk - key for conversion
13381 *
13382 * @returns {Uint8Array} Raw public key.
13383 */
13384 function jwkToRawPublic(jwk) {
13385 const bufX = b64ToUint8Array(jwk.x);
13386 const bufY = b64ToUint8Array(jwk.y);
13387 const publicKey = new Uint8Array(bufX.length + bufY.length + 1);
13388 publicKey[0] = 0x04;
13389 publicKey.set(bufX, 1);
13390 publicKey.set(bufY, bufX.length + 1);
13391 return publicKey;
13392 }
13393
13394 /**
13395 * @param {Integer} payloadSize - ec payload size
13396 * @param {String} name - curve name
13397 * @param {Uint8Array} publicKey - public key
13398 *
13399 * @returns {JsonWebKey} Public key in jwk format.
13400 */
13401 function rawPublicToJWK(payloadSize, name, publicKey) {
13402 const len = payloadSize;
13403 const bufX = publicKey.slice(1, len + 1);
13404 const bufY = publicKey.slice(len + 1, len * 2 + 1);
13405 // https://www.rfc-editor.org/rfc/rfc7518.txt
13406 const jwk = {
13407 kty: 'EC',
13408 crv: name,
13409 x: uint8ArrayToB64(bufX, true),
13410 y: uint8ArrayToB64(bufY, true),
13411 ext: true
13412 };
13413 return jwk;
13414 }
13415
13416 /**
13417 * @param {Integer} payloadSize - ec payload size
13418 * @param {String} name - curve name
13419 * @param {Uint8Array} publicKey - public key
13420 * @param {Uint8Array} privateKey - private key
13421 *
13422 * @returns {JsonWebKey} Private key in jwk format.
13423 */
13424 function privateToJWK$1(payloadSize, name, publicKey, privateKey) {
13425 const jwk = rawPublicToJWK(payloadSize, name, publicKey);
13426 jwk.d = uint8ArrayToB64(privateKey, true);
13427 return jwk;
13428 }
13429
13430 // OpenPGP.js - An OpenPGP implementation in javascript
13431
13432 const webCrypto$7 = util.getWebCrypto();
13433 const nodeCrypto$8 = util.getNodeCrypto();
13434
13435 /**
13436 * Sign a message using the provided key
13437 * @param {module:type/oid} oid - Elliptic curve object identifier
13438 * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign
13439 * @param {Uint8Array} message - Message to sign
13440 * @param {Uint8Array} publicKey - Public key
13441 * @param {Uint8Array} privateKey - Private key used to sign the message
13442 * @param {Uint8Array} hashed - The hashed message
13443 * @returns {Promise<{
13444 * r: Uint8Array,
13445 * s: Uint8Array
13446 * }>} Signature of the message
13447 * @async
13448 */
13449 async function sign$1(oid, hashAlgo, message, publicKey, privateKey, hashed) {
13450 const curve = new Curve(oid);
13451 if (message && !util.isStream(message)) {
13452 const keyPair = { publicKey, privateKey };
13453 switch (curve.type) {
13454 case 'web': {
13455 // If browser doesn't support a curve, we'll catch it
13456 try {
13457 // Need to await to make sure browser succeeds
13458 return await webSign$1(curve, hashAlgo, message, keyPair);
13459 } catch (err) {
13460 // We do not fallback if the error is related to key integrity
13461 // Unfortunaley Safari does not support p521 and throws a DataError when using it
13462 // So we need to always fallback for that curve
13463 if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {
13464 throw err;
13465 }
13466 util.printDebugError('Browser did not support signing: ' + err.message);
13467 }
13468 break;
13469 }
13470 case 'node': {
13471 const signature = await nodeSign$1(curve, hashAlgo, message, keyPair);
13472 return {
13473 r: signature.r.toArrayLike(Uint8Array),
13474 s: signature.s.toArrayLike(Uint8Array)
13475 };
13476 }
13477 }
13478 }
13479 return ellipticSign(curve, hashed, privateKey);
13480 }
13481
13482 /**
13483 * Verifies if a signature is valid for a message
13484 * @param {module:type/oid} oid - Elliptic curve object identifier
13485 * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature
13486 * @param {{r: Uint8Array,
13487 s: Uint8Array}} signature Signature to verify
13488 * @param {Uint8Array} message - Message to verify
13489 * @param {Uint8Array} publicKey - Public key used to verify the message
13490 * @param {Uint8Array} hashed - The hashed message
13491 * @returns {Boolean}
13492 * @async
13493 */
13494 async function verify$1(oid, hashAlgo, signature, message, publicKey, hashed) {
13495 const curve = new Curve(oid);
13496 if (message && !util.isStream(message)) {
13497 switch (curve.type) {
13498 case 'web':
13499 try {
13500 // Need to await to make sure browser succeeds
13501 return await webVerify$1(curve, hashAlgo, signature, message, publicKey);
13502 } catch (err) {
13503 // We do not fallback if the error is related to key integrity
13504 // Unfortunately Safari does not support p521 and throws a DataError when using it
13505 // So we need to always fallback for that curve
13506 if (curve.name !== 'p521' && (err.name === 'DataError' || err.name === 'OperationError')) {
13507 throw err;
13508 }
13509 util.printDebugError('Browser did not support verifying: ' + err.message);
13510 }
13511 break;
13512 case 'node':
13513 return nodeVerify$1(curve, hashAlgo, signature, message, publicKey);
13514 }
13515 }
13516 const digest = (typeof hashAlgo === 'undefined') ? message : hashed;
13517 return ellipticVerify(curve, signature, digest, publicKey);
13518 }
13519
13520 /**
13521 * Validate ECDSA parameters
13522 * @param {module:type/oid} oid - Elliptic curve object identifier
13523 * @param {Uint8Array} Q - ECDSA public point
13524 * @param {Uint8Array} d - ECDSA secret scalar
13525 * @returns {Promise<Boolean>} Whether params are valid.
13526 * @async
13527 */
13528 async function validateParams$2(oid, Q, d) {
13529 const curve = new Curve(oid);
13530 // Reject curves x25519 and ed25519
13531 if (curve.keyType !== enums.publicKey.ecdsa) {
13532 return false;
13533 }
13534
13535 // To speed up the validation, we try to use node- or webcrypto when available
13536 // and sign + verify a random message
13537 switch (curve.type) {
13538 case 'web':
13539 case 'node': {
13540 const message = await getRandomBytes(8);
13541 const hashAlgo = enums.hash.sha256;
13542 const hashed = await hash.digest(hashAlgo, message);
13543 try {
13544 const signature = await sign$1(oid, hashAlgo, message, Q, d, hashed);
13545 return await verify$1(oid, hashAlgo, signature, message, Q, hashed);
13546 } catch (err) {
13547 return false;
13548 }
13549 }
13550 default:
13551 return validateStandardParams(enums.publicKey.ecdsa, oid, Q, d);
13552 }
13553 }
13554
13555
13556 //////////////////////////
13557 // //
13558 // Helper functions //
13559 // //
13560 //////////////////////////
13561
13562 async function ellipticSign(curve, hashed, privateKey) {
13563 const indutnyCurve = await getIndutnyCurve(curve.name);
13564 const key = keyFromPrivate(indutnyCurve, privateKey);
13565 const signature = key.sign(hashed);
13566 return {
13567 r: signature.r.toArrayLike(Uint8Array),
13568 s: signature.s.toArrayLike(Uint8Array)
13569 };
13570 }
13571
13572 async function ellipticVerify(curve, signature, digest, publicKey) {
13573 const indutnyCurve = await getIndutnyCurve(curve.name);
13574 const key = keyFromPublic(indutnyCurve, publicKey);
13575 return key.verify(digest, signature);
13576 }
13577
13578 async function webSign$1(curve, hashAlgo, message, keyPair) {
13579 const len = curve.payloadSize;
13580 const jwk = privateToJWK$1(curve.payloadSize, webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);
13581 const key = await webCrypto$7.importKey(
13582 'jwk',
13583 jwk,
13584 {
13585 'name': 'ECDSA',
13586 'namedCurve': webCurves[curve.name],
13587 'hash': { name: enums.read(enums.webHash, curve.hash) }
13588 },
13589 false,
13590 ['sign']
13591 );
13592
13593 const signature = new Uint8Array(await webCrypto$7.sign(
13594 {
13595 'name': 'ECDSA',
13596 'namedCurve': webCurves[curve.name],
13597 'hash': { name: enums.read(enums.webHash, hashAlgo) }
13598 },
13599 key,
13600 message
13601 ));
13602
13603 return {
13604 r: signature.slice(0, len),
13605 s: signature.slice(len, len << 1)
13606 };
13607 }
13608
13609 async function webVerify$1(curve, hashAlgo, { r, s }, message, publicKey) {
13610 const jwk = rawPublicToJWK(curve.payloadSize, webCurves[curve.name], publicKey);
13611 const key = await webCrypto$7.importKey(
13612 'jwk',
13613 jwk,
13614 {
13615 'name': 'ECDSA',
13616 'namedCurve': webCurves[curve.name],
13617 'hash': { name: enums.read(enums.webHash, curve.hash) }
13618 },
13619 false,
13620 ['verify']
13621 );
13622
13623 const signature = util.concatUint8Array([r, s]).buffer;
13624
13625 return webCrypto$7.verify(
13626 {
13627 'name': 'ECDSA',
13628 'namedCurve': webCurves[curve.name],
13629 'hash': { name: enums.read(enums.webHash, hashAlgo) }
13630 },
13631 key,
13632 signature,
13633 message
13634 );
13635 }
13636
13637 async function nodeSign$1(curve, hashAlgo, message, keyPair) {
13638 const sign = nodeCrypto$8.createSign(enums.read(enums.hash, hashAlgo));
13639 sign.write(message);
13640 sign.end();
13641 const key = ECPrivateKey.encode({
13642 version: 1,
13643 parameters: curve.oid,
13644 privateKey: Array.from(keyPair.privateKey),
13645 publicKey: { unused: 0, data: Array.from(keyPair.publicKey) }
13646 }, 'pem', {
13647 label: 'EC PRIVATE KEY'
13648 });
13649
13650 return ECDSASignature.decode(sign.sign(key), 'der');
13651 }
13652
13653 async function nodeVerify$1(curve, hashAlgo, { r, s }, message, publicKey) {
13654 const { default: BN } = await Promise.resolve().then(function () { return bn$1; });
13655
13656 const verify = nodeCrypto$8.createVerify(enums.read(enums.hash, hashAlgo));
13657 verify.write(message);
13658 verify.end();
13659 const key = SubjectPublicKeyInfo.encode({
13660 algorithm: {
13661 algorithm: [1, 2, 840, 10045, 2, 1],
13662 parameters: curve.oid
13663 },
13664 subjectPublicKey: { unused: 0, data: Array.from(publicKey) }
13665 }, 'pem', {
13666 label: 'PUBLIC KEY'
13667 });
13668 const signature = ECDSASignature.encode({
13669 r: new BN(r), s: new BN(s)
13670 }, 'der');
13671
13672 try {
13673 return verify.verify(key, signature);
13674 } catch (err) {
13675 return false;
13676 }
13677 }
13678
13679 // Originally written by Owen Smith https://github.com/omsmith
13680 // Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/
13681
13682 /* eslint-disable no-invalid-this */
13683
13684 const asn1$1 = nodeCrypto$8 ? void('asn1.js') : undefined;
13685
13686 const ECDSASignature = nodeCrypto$8 ?
13687 asn1$1.define('ECDSASignature', function() {
13688 this.seq().obj(
13689 this.key('r').int(),
13690 this.key('s').int()
13691 );
13692 }) : undefined;
13693
13694 const ECPrivateKey = nodeCrypto$8 ?
13695 asn1$1.define('ECPrivateKey', function() {
13696 this.seq().obj(
13697 this.key('version').int(),
13698 this.key('privateKey').octstr(),
13699 this.key('parameters').explicit(0).optional().any(),
13700 this.key('publicKey').explicit(1).optional().bitstr()
13701 );
13702 }) : undefined;
13703
13704 const AlgorithmIdentifier = nodeCrypto$8 ?
13705 asn1$1.define('AlgorithmIdentifier', function() {
13706 this.seq().obj(
13707 this.key('algorithm').objid(),
13708 this.key('parameters').optional().any()
13709 );
13710 }) : undefined;
13711
13712 const SubjectPublicKeyInfo = nodeCrypto$8 ?
13713 asn1$1.define('SubjectPublicKeyInfo', function() {
13714 this.seq().obj(
13715 this.key('algorithm').use(AlgorithmIdentifier),
13716 this.key('subjectPublicKey').bitstr()
13717 );
13718 }) : undefined;
13719
13720 var ecdsa = /*#__PURE__*/Object.freeze({
13721 __proto__: null,
13722 sign: sign$1,
13723 verify: verify$1,
13724 validateParams: validateParams$2
13725 });
13726
13727 // OpenPGP.js - An OpenPGP implementation in javascript
13728
13729 naclFastLight.hash = bytes => new Uint8Array(_512().update(bytes).digest());
13730
13731 /**
13732 * Sign a message using the provided key
13733 * @param {module:type/oid} oid - Elliptic curve object identifier
13734 * @param {module:enums.hash} hashAlgo - Hash algorithm used to sign (must be sha256 or stronger)
13735 * @param {Uint8Array} message - Message to sign
13736 * @param {Uint8Array} publicKey - Public key
13737 * @param {Uint8Array} privateKey - Private key used to sign the message
13738 * @param {Uint8Array} hashed - The hashed message
13739 * @returns {Promise<{
13740 * r: Uint8Array,
13741 * s: Uint8Array
13742 * }>} Signature of the message
13743 * @async
13744 */
13745 async function sign$2(oid, hashAlgo, message, publicKey, privateKey, hashed) {
13746 if (hash.getHashByteLength(hashAlgo) < hash.getHashByteLength(enums.hash.sha256)) {
13747 // see https://tools.ietf.org/id/draft-ietf-openpgp-rfc4880bis-10.html#section-15-7.2
13748 throw new Error('Hash algorithm too weak: sha256 or stronger is required for EdDSA.');
13749 }
13750 const secretKey = util.concatUint8Array([privateKey, publicKey.subarray(1)]);
13751 const signature = naclFastLight.sign.detached(hashed, secretKey);
13752 // EdDSA signature params are returned in little-endian format
13753 return {
13754 r: signature.subarray(0, 32),
13755 s: signature.subarray(32)
13756 };
13757 }
13758
13759 /**
13760 * Verifies if a signature is valid for a message
13761 * @param {module:type/oid} oid - Elliptic curve object identifier
13762 * @param {module:enums.hash} hashAlgo - Hash algorithm used in the signature
13763 * @param {{r: Uint8Array,
13764 s: Uint8Array}} signature Signature to verify the message
13765 * @param {Uint8Array} m - Message to verify
13766 * @param {Uint8Array} publicKey - Public key used to verify the message
13767 * @param {Uint8Array} hashed - The hashed message
13768 * @returns {Boolean}
13769 * @async
13770 */
13771 async function verify$2(oid, hashAlgo, { r, s }, m, publicKey, hashed) {
13772 const signature = util.concatUint8Array([r, s]);
13773 return naclFastLight.sign.detached.verify(hashed, signature, publicKey.subarray(1));
13774 }
13775 /**
13776 * Validate EdDSA parameters
13777 * @param {module:type/oid} oid - Elliptic curve object identifier
13778 * @param {Uint8Array} Q - EdDSA public point
13779 * @param {Uint8Array} k - EdDSA secret seed
13780 * @returns {Promise<Boolean>} Whether params are valid.
13781 * @async
13782 */
13783 async function validateParams$3(oid, Q, k) {
13784 // Check whether the given curve is supported
13785 if (oid.getName() !== 'ed25519') {
13786 return false;
13787 }
13788
13789 /**
13790 * Derive public point Q' = dG from private key
13791 * and expect Q == Q'
13792 */
13793 const { publicKey } = naclFastLight.sign.keyPair.fromSeed(k);
13794 const dG = new Uint8Array([0x40, ...publicKey]); // Add public key prefix
13795 return util.equalsUint8Array(Q, dG);
13796 }
13797
13798 var eddsa = /*#__PURE__*/Object.freeze({
13799 __proto__: null,
13800 sign: sign$2,
13801 verify: verify$2,
13802 validateParams: validateParams$3
13803 });
13804
13805 // OpenPGP.js - An OpenPGP implementation in javascript
13806
13807 /**
13808 * AES key wrap
13809 * @function
13810 * @param {Uint8Array} key
13811 * @param {Uint8Array} data
13812 * @returns {Uint8Array}
13813 */
13814 function wrap(key, data) {
13815 const aes = new cipher['aes' + (key.length * 8)](key);
13816 const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
13817 const P = unpack(data);
13818 let A = IV;
13819 const R = P;
13820 const n = P.length / 2;
13821 const t = new Uint32Array([0, 0]);
13822 let B = new Uint32Array(4);
13823 for (let j = 0; j <= 5; ++j) {
13824 for (let i = 0; i < n; ++i) {
13825 t[1] = n * j + (1 + i);
13826 // B = A
13827 B[0] = A[0];
13828 B[1] = A[1];
13829 // B = A || R[i]
13830 B[2] = R[2 * i];
13831 B[3] = R[2 * i + 1];
13832 // B = AES(K, B)
13833 B = unpack(aes.encrypt(pack(B)));
13834 // A = MSB(64, B) ^ t
13835 A = B.subarray(0, 2);
13836 A[0] ^= t[0];
13837 A[1] ^= t[1];
13838 // R[i] = LSB(64, B)
13839 R[2 * i] = B[2];
13840 R[2 * i + 1] = B[3];
13841 }
13842 }
13843 return pack(A, R);
13844 }
13845
13846 /**
13847 * AES key unwrap
13848 * @function
13849 * @param {String} key
13850 * @param {String} data
13851 * @returns {Uint8Array}
13852 * @throws {Error}
13853 */
13854 function unwrap(key, data) {
13855 const aes = new cipher['aes' + (key.length * 8)](key);
13856 const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
13857 const C = unpack(data);
13858 let A = C.subarray(0, 2);
13859 const R = C.subarray(2);
13860 const n = C.length / 2 - 1;
13861 const t = new Uint32Array([0, 0]);
13862 let B = new Uint32Array(4);
13863 for (let j = 5; j >= 0; --j) {
13864 for (let i = n - 1; i >= 0; --i) {
13865 t[1] = n * j + (i + 1);
13866 // B = A ^ t
13867 B[0] = A[0] ^ t[0];
13868 B[1] = A[1] ^ t[1];
13869 // B = (A ^ t) || R[i]
13870 B[2] = R[2 * i];
13871 B[3] = R[2 * i + 1];
13872 // B = AES-1(B)
13873 B = unpack(aes.decrypt(pack(B)));
13874 // A = MSB(64, B)
13875 A = B.subarray(0, 2);
13876 // R[i] = LSB(64, B)
13877 R[2 * i] = B[2];
13878 R[2 * i + 1] = B[3];
13879 }
13880 }
13881 if (A[0] === IV[0] && A[1] === IV[1]) {
13882 return pack(R);
13883 }
13884 throw new Error('Key Data Integrity failed');
13885 }
13886
13887 function createArrayBuffer(data) {
13888 if (util.isString(data)) {
13889 const { length } = data;
13890 const buffer = new ArrayBuffer(length);
13891 const view = new Uint8Array(buffer);
13892 for (let j = 0; j < length; ++j) {
13893 view[j] = data.charCodeAt(j);
13894 }
13895 return buffer;
13896 }
13897 return new Uint8Array(data).buffer;
13898 }
13899
13900 function unpack(data) {
13901 const { length } = data;
13902 const buffer = createArrayBuffer(data);
13903 const view = new DataView(buffer);
13904 const arr = new Uint32Array(length / 4);
13905 for (let i = 0; i < length / 4; ++i) {
13906 arr[i] = view.getUint32(4 * i);
13907 }
13908 return arr;
13909 }
13910
13911 function pack() {
13912 let length = 0;
13913 for (let k = 0; k < arguments.length; ++k) {
13914 length += 4 * arguments[k].length;
13915 }
13916 const buffer = new ArrayBuffer(length);
13917 const view = new DataView(buffer);
13918 let offset = 0;
13919 for (let i = 0; i < arguments.length; ++i) {
13920 for (let j = 0; j < arguments[i].length; ++j) {
13921 view.setUint32(offset + 4 * j, arguments[i][j]);
13922 }
13923 offset += 4 * arguments[i].length;
13924 }
13925 return new Uint8Array(buffer);
13926 }
13927
13928 var aesKW = /*#__PURE__*/Object.freeze({
13929 __proto__: null,
13930 wrap: wrap,
13931 unwrap: unwrap
13932 });
13933
13934 // OpenPGP.js - An OpenPGP implementation in javascript
13935
13936 /**
13937 * @fileoverview Functions to add and remove PKCS5 padding
13938 * @see PublicKeyEncryptedSessionKeyPacket
13939 * @module crypto/pkcs5
13940 * @private
13941 */
13942
13943 /**
13944 * Add pkcs5 padding to a message
13945 * @param {Uint8Array} message - message to pad
13946 * @returns {Uint8Array} Padded message.
13947 */
13948 function encode$1(message) {
13949 const c = 8 - (message.length % 8);
13950 const padded = new Uint8Array(message.length + c).fill(c);
13951 padded.set(message);
13952 return padded;
13953 }
13954
13955 /**
13956 * Remove pkcs5 padding from a message
13957 * @param {Uint8Array} message - message to remove padding from
13958 * @returns {Uint8Array} Message without padding.
13959 */
13960 function decode$1(message) {
13961 const len = message.length;
13962 if (len > 0) {
13963 const c = message[len - 1];
13964 if (c >= 1) {
13965 const provided = message.subarray(len - c);
13966 const computed = new Uint8Array(c).fill(c);
13967 if (util.equalsUint8Array(provided, computed)) {
13968 return message.subarray(0, len - c);
13969 }
13970 }
13971 }
13972 throw new Error('Invalid padding');
13973 }
13974
13975 var pkcs5 = /*#__PURE__*/Object.freeze({
13976 __proto__: null,
13977 encode: encode$1,
13978 decode: decode$1
13979 });
13980
13981 // OpenPGP.js - An OpenPGP implementation in javascript
13982
13983 const webCrypto$8 = util.getWebCrypto();
13984 const nodeCrypto$9 = util.getNodeCrypto();
13985
13986 /**
13987 * Validate ECDH parameters
13988 * @param {module:type/oid} oid - Elliptic curve object identifier
13989 * @param {Uint8Array} Q - ECDH public point
13990 * @param {Uint8Array} d - ECDH secret scalar
13991 * @returns {Promise<Boolean>} Whether params are valid.
13992 * @async
13993 */
13994 async function validateParams$4(oid, Q, d) {
13995 return validateStandardParams(enums.publicKey.ecdh, oid, Q, d);
13996 }
13997
13998 // Build Param for ECDH algorithm (RFC 6637)
13999 function buildEcdhParam(public_algo, oid, kdfParams, fingerprint) {
14000 return util.concatUint8Array([
14001 oid.write(),
14002 new Uint8Array([public_algo]),
14003 kdfParams.write(),
14004 util.stringToUint8Array('Anonymous Sender '),
14005 fingerprint.subarray(0, 20)
14006 ]);
14007 }
14008
14009 // Key Derivation Function (RFC 6637)
14010 async function kdf(hashAlgo, X, length, param, stripLeading = false, stripTrailing = false) {
14011 // Note: X is little endian for Curve25519, big-endian for all others.
14012 // This is not ideal, but the RFC's are unclear
14013 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
14014 let i;
14015 if (stripLeading) {
14016 // Work around old go crypto bug
14017 for (i = 0; i < X.length && X[i] === 0; i++);
14018 X = X.subarray(i);
14019 }
14020 if (stripTrailing) {
14021 // Work around old OpenPGP.js bug
14022 for (i = X.length - 1; i >= 0 && X[i] === 0; i--);
14023 X = X.subarray(0, i + 1);
14024 }
14025 const digest = await hash.digest(hashAlgo, util.concatUint8Array([
14026 new Uint8Array([0, 0, 0, 1]),
14027 X,
14028 param
14029 ]));
14030 return digest.subarray(0, length);
14031 }
14032
14033 /**
14034 * Generate ECDHE ephemeral key and secret from public key
14035 *
14036 * @param {Curve} curve - Elliptic curve object
14037 * @param {Uint8Array} Q - Recipient public key
14038 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
14039 * @async
14040 */
14041 async function genPublicEphemeralKey(curve, Q) {
14042 switch (curve.type) {
14043 case 'curve25519': {
14044 const d = await getRandomBytes(32);
14045 const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, null, d);
14046 let { publicKey } = naclFastLight.box.keyPair.fromSecretKey(secretKey);
14047 publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]);
14048 return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
14049 }
14050 case 'web':
14051 if (curve.web && util.getWebCrypto()) {
14052 try {
14053 return await webPublicEphemeralKey(curve, Q);
14054 } catch (err) {
14055 util.printDebugError(err);
14056 }
14057 }
14058 break;
14059 case 'node':
14060 return nodePublicEphemeralKey(curve, Q);
14061 }
14062 return ellipticPublicEphemeralKey(curve, Q);
14063 }
14064
14065 /**
14066 * Encrypt and wrap a session key
14067 *
14068 * @param {module:type/oid} oid - Elliptic curve object identifier
14069 * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use
14070 * @param {Uint8Array} data - Unpadded session key data
14071 * @param {Uint8Array} Q - Recipient public key
14072 * @param {Uint8Array} fingerprint - Recipient fingerprint
14073 * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}
14074 * @async
14075 */
14076 async function encrypt$3(oid, kdfParams, data, Q, fingerprint) {
14077 const m = encode$1(data);
14078
14079 const curve = new Curve(oid);
14080 const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);
14081 const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);
14082 const cipherAlgo = enums.read(enums.symmetric, kdfParams.cipher);
14083 const Z = await kdf(kdfParams.hash, sharedKey, cipher[cipherAlgo].keySize, param);
14084 const wrappedKey = wrap(Z, m);
14085 return { publicKey, wrappedKey };
14086 }
14087
14088 /**
14089 * Generate ECDHE secret from private key and public part of ephemeral key
14090 *
14091 * @param {Curve} curve - Elliptic curve object
14092 * @param {Uint8Array} V - Public part of ephemeral key
14093 * @param {Uint8Array} Q - Recipient public key
14094 * @param {Uint8Array} d - Recipient private key
14095 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
14096 * @async
14097 */
14098 async function genPrivateEphemeralKey(curve, V, Q, d) {
14099 if (d.length !== curve.payloadSize) {
14100 const privateKey = new Uint8Array(curve.payloadSize);
14101 privateKey.set(d, curve.payloadSize - d.length);
14102 d = privateKey;
14103 }
14104 switch (curve.type) {
14105 case 'curve25519': {
14106 const secretKey = d.slice().reverse();
14107 const sharedKey = naclFastLight.scalarMult(secretKey, V.subarray(1));
14108 return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
14109 }
14110 case 'web':
14111 if (curve.web && util.getWebCrypto()) {
14112 try {
14113 return await webPrivateEphemeralKey(curve, V, Q, d);
14114 } catch (err) {
14115 util.printDebugError(err);
14116 }
14117 }
14118 break;
14119 case 'node':
14120 return nodePrivateEphemeralKey(curve, V, d);
14121 }
14122 return ellipticPrivateEphemeralKey(curve, V, d);
14123 }
14124
14125 /**
14126 * Decrypt and unwrap the value derived from session key
14127 *
14128 * @param {module:type/oid} oid - Elliptic curve object identifier
14129 * @param {module:type/kdf_params} kdfParams - KDF params including cipher and algorithm to use
14130 * @param {Uint8Array} V - Public part of ephemeral key
14131 * @param {Uint8Array} C - Encrypted and wrapped value derived from session key
14132 * @param {Uint8Array} Q - Recipient public key
14133 * @param {Uint8Array} d - Recipient private key
14134 * @param {Uint8Array} fingerprint - Recipient fingerprint
14135 * @returns {Promise<Uint8Array>} Value derived from session key.
14136 * @async
14137 */
14138 async function decrypt$3(oid, kdfParams, V, C, Q, d, fingerprint) {
14139 const curve = new Curve(oid);
14140 const { sharedKey } = await genPrivateEphemeralKey(curve, V, Q, d);
14141 const param = buildEcdhParam(enums.publicKey.ecdh, oid, kdfParams, fingerprint);
14142 const cipherAlgo = enums.read(enums.symmetric, kdfParams.cipher);
14143 let err;
14144 for (let i = 0; i < 3; i++) {
14145 try {
14146 // Work around old go crypto bug and old OpenPGP.js bug, respectively.
14147 const Z = await kdf(kdfParams.hash, sharedKey, cipher[cipherAlgo].keySize, param, i === 1, i === 2);
14148 return decode$1(unwrap(Z, C));
14149 } catch (e) {
14150 err = e;
14151 }
14152 }
14153 throw err;
14154 }
14155
14156 /**
14157 * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto
14158 *
14159 * @param {Curve} curve - Elliptic curve object
14160 * @param {Uint8Array} V - Public part of ephemeral key
14161 * @param {Uint8Array} Q - Recipient public key
14162 * @param {Uint8Array} d - Recipient private key
14163 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
14164 * @async
14165 */
14166 async function webPrivateEphemeralKey(curve, V, Q, d) {
14167 const recipient = privateToJWK$1(curve.payloadSize, curve.web.web, Q, d);
14168 let privateKey = webCrypto$8.importKey(
14169 'jwk',
14170 recipient,
14171 {
14172 name: 'ECDH',
14173 namedCurve: curve.web.web
14174 },
14175 true,
14176 ['deriveKey', 'deriveBits']
14177 );
14178 const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, V);
14179 let sender = webCrypto$8.importKey(
14180 'jwk',
14181 jwk,
14182 {
14183 name: 'ECDH',
14184 namedCurve: curve.web.web
14185 },
14186 true,
14187 []
14188 );
14189 [privateKey, sender] = await Promise.all([privateKey, sender]);
14190 let S = webCrypto$8.deriveBits(
14191 {
14192 name: 'ECDH',
14193 namedCurve: curve.web.web,
14194 public: sender
14195 },
14196 privateKey,
14197 curve.web.sharedSize
14198 );
14199 let secret = webCrypto$8.exportKey(
14200 'jwk',
14201 privateKey
14202 );
14203 [S, secret] = await Promise.all([S, secret]);
14204 const sharedKey = new Uint8Array(S);
14205 const secretKey = b64ToUint8Array(secret.d);
14206 return { secretKey, sharedKey };
14207 }
14208
14209 /**
14210 * Generate ECDHE ephemeral key and secret from public key using webCrypto
14211 *
14212 * @param {Curve} curve - Elliptic curve object
14213 * @param {Uint8Array} Q - Recipient public key
14214 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
14215 * @async
14216 */
14217 async function webPublicEphemeralKey(curve, Q) {
14218 const jwk = rawPublicToJWK(curve.payloadSize, curve.web.web, Q);
14219 let keyPair = webCrypto$8.generateKey(
14220 {
14221 name: 'ECDH',
14222 namedCurve: curve.web.web
14223 },
14224 true,
14225 ['deriveKey', 'deriveBits']
14226 );
14227 let recipient = webCrypto$8.importKey(
14228 'jwk',
14229 jwk,
14230 {
14231 name: 'ECDH',
14232 namedCurve: curve.web.web
14233 },
14234 false,
14235 []
14236 );
14237 [keyPair, recipient] = await Promise.all([keyPair, recipient]);
14238 let s = webCrypto$8.deriveBits(
14239 {
14240 name: 'ECDH',
14241 namedCurve: curve.web.web,
14242 public: recipient
14243 },
14244 keyPair.privateKey,
14245 curve.web.sharedSize
14246 );
14247 let p = webCrypto$8.exportKey(
14248 'jwk',
14249 keyPair.publicKey
14250 );
14251 [s, p] = await Promise.all([s, p]);
14252 const sharedKey = new Uint8Array(s);
14253 const publicKey = new Uint8Array(jwkToRawPublic(p));
14254 return { publicKey, sharedKey };
14255 }
14256
14257 /**
14258 * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic
14259 *
14260 * @param {Curve} curve - Elliptic curve object
14261 * @param {Uint8Array} V - Public part of ephemeral key
14262 * @param {Uint8Array} d - Recipient private key
14263 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
14264 * @async
14265 */
14266 async function ellipticPrivateEphemeralKey(curve, V, d) {
14267 const indutnyCurve = await getIndutnyCurve(curve.name);
14268 V = keyFromPublic(indutnyCurve, V);
14269 d = keyFromPrivate(indutnyCurve, d);
14270 const secretKey = new Uint8Array(d.getPrivate());
14271 const S = d.derive(V.getPublic());
14272 const len = indutnyCurve.curve.p.byteLength();
14273 const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
14274 return { secretKey, sharedKey };
14275 }
14276
14277 /**
14278 * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic
14279 *
14280 * @param {Curve} curve - Elliptic curve object
14281 * @param {Uint8Array} Q - Recipient public key
14282 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
14283 * @async
14284 */
14285 async function ellipticPublicEphemeralKey(curve, Q) {
14286 const indutnyCurve = await getIndutnyCurve(curve.name);
14287 const v = await curve.genKeyPair();
14288 Q = keyFromPublic(indutnyCurve, Q);
14289 const V = keyFromPrivate(indutnyCurve, v.privateKey);
14290 const publicKey = v.publicKey;
14291 const S = V.derive(Q.getPublic());
14292 const len = indutnyCurve.curve.p.byteLength();
14293 const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
14294 return { publicKey, sharedKey };
14295 }
14296
14297 /**
14298 * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto
14299 *
14300 * @param {Curve} curve - Elliptic curve object
14301 * @param {Uint8Array} V - Public part of ephemeral key
14302 * @param {Uint8Array} d - Recipient private key
14303 * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
14304 * @async
14305 */
14306 async function nodePrivateEphemeralKey(curve, V, d) {
14307 const recipient = nodeCrypto$9.createECDH(curve.node.node);
14308 recipient.setPrivateKey(d);
14309 const sharedKey = new Uint8Array(recipient.computeSecret(V));
14310 const secretKey = new Uint8Array(recipient.getPrivateKey());
14311 return { secretKey, sharedKey };
14312 }
14313
14314 /**
14315 * Generate ECDHE ephemeral key and secret from public key using nodeCrypto
14316 *
14317 * @param {Curve} curve - Elliptic curve object
14318 * @param {Uint8Array} Q - Recipient public key
14319 * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
14320 * @async
14321 */
14322 async function nodePublicEphemeralKey(curve, Q) {
14323 const sender = nodeCrypto$9.createECDH(curve.node.node);
14324 sender.generateKeys();
14325 const sharedKey = new Uint8Array(sender.computeSecret(Q));
14326 const publicKey = new Uint8Array(sender.getPublicKey());
14327 return { publicKey, sharedKey };
14328 }
14329
14330 var ecdh = /*#__PURE__*/Object.freeze({
14331 __proto__: null,
14332 validateParams: validateParams$4,
14333 encrypt: encrypt$3,
14334 decrypt: decrypt$3
14335 });
14336
14337 // OpenPGP.js - An OpenPGP implementation in javascript
14338
14339 var elliptic = /*#__PURE__*/Object.freeze({
14340 __proto__: null,
14341 Curve: Curve,
14342 ecdh: ecdh,
14343 ecdsa: ecdsa,
14344 eddsa: eddsa,
14345 generate: generate$1,
14346 getPreferredHashAlgo: getPreferredHashAlgo
14347 });
14348
14349 // GPG4Browsers - An OpenPGP implementation in javascript
14350
14351 /*
14352 TODO regarding the hash function, read:
14353 https://tools.ietf.org/html/rfc4880#section-13.6
14354 https://tools.ietf.org/html/rfc4880#section-14
14355 */
14356
14357 /**
14358 * DSA Sign function
14359 * @param {Integer} hashAlgo
14360 * @param {Uint8Array} hashed
14361 * @param {Uint8Array} g
14362 * @param {Uint8Array} p
14363 * @param {Uint8Array} q
14364 * @param {Uint8Array} x
14365 * @returns {Promise<{ r: Uint8Array, s: Uint8Array }>}
14366 * @async
14367 */
14368 async function sign$3(hashAlgo, hashed, g, p, q, x) {
14369 const BigInteger = await util.getBigInteger();
14370 const one = new BigInteger(1);
14371 p = new BigInteger(p);
14372 q = new BigInteger(q);
14373 g = new BigInteger(g);
14374 x = new BigInteger(x);
14375
14376 let k;
14377 let r;
14378 let s;
14379 let t;
14380 g = g.mod(p);
14381 x = x.mod(q);
14382 // If the output size of the chosen hash is larger than the number of
14383 // bits of q, the hash result is truncated to fit by taking the number
14384 // of leftmost bits equal to the number of bits of q. This (possibly
14385 // truncated) hash function result is treated as a number and used
14386 // directly in the DSA signature algorithm.
14387 const h = new BigInteger(hashed.subarray(0, q.byteLength())).mod(q);
14388 // FIPS-186-4, section 4.6:
14389 // The values of r and s shall be checked to determine if r = 0 or s = 0.
14390 // If either r = 0 or s = 0, a new value of k shall be generated, and the
14391 // signature shall be recalculated. It is extremely unlikely that r = 0
14392 // or s = 0 if signatures are generated properly.
14393 while (true) {
14394 // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
14395 k = await getRandomBigInteger(one, q); // returns in [1, q-1]
14396 r = g.modExp(k, p).imod(q); // (g**k mod p) mod q
14397 if (r.isZero()) {
14398 continue;
14399 }
14400 const xr = x.mul(r).imod(q);
14401 t = h.add(xr).imod(q); // H(m) + x*r mod q
14402 s = k.modInv(q).imul(t).imod(q); // k**-1 * (H(m) + x*r) mod q
14403 if (s.isZero()) {
14404 continue;
14405 }
14406 break;
14407 }
14408 return {
14409 r: r.toUint8Array('be', q.byteLength()),
14410 s: s.toUint8Array('be', q.byteLength())
14411 };
14412 }
14413
14414 /**
14415 * DSA Verify function
14416 * @param {Integer} hashAlgo
14417 * @param {Uint8Array} r
14418 * @param {Uint8Array} s
14419 * @param {Uint8Array} hashed
14420 * @param {Uint8Array} g
14421 * @param {Uint8Array} p
14422 * @param {Uint8Array} q
14423 * @param {Uint8Array} y
14424 * @returns {boolean}
14425 * @async
14426 */
14427 async function verify$3(hashAlgo, r, s, hashed, g, p, q, y) {
14428 const BigInteger = await util.getBigInteger();
14429 const zero = new BigInteger(0);
14430 r = new BigInteger(r);
14431 s = new BigInteger(s);
14432
14433 p = new BigInteger(p);
14434 q = new BigInteger(q);
14435 g = new BigInteger(g);
14436 y = new BigInteger(y);
14437
14438 if (r.lte(zero) || r.gte(q) ||
14439 s.lte(zero) || s.gte(q)) {
14440 util.printDebug('invalid DSA Signature');
14441 return false;
14442 }
14443 const h = new BigInteger(hashed.subarray(0, q.byteLength())).imod(q);
14444 const w = s.modInv(q); // s**-1 mod q
14445 if (w.isZero()) {
14446 util.printDebug('invalid DSA Signature');
14447 return false;
14448 }
14449
14450 g = g.mod(p);
14451 y = y.mod(p);
14452 const u1 = h.mul(w).imod(q); // H(m) * w mod q
14453 const u2 = r.mul(w).imod(q); // r * w mod q
14454 const t1 = g.modExp(u1, p); // g**u1 mod p
14455 const t2 = y.modExp(u2, p); // y**u2 mod p
14456 const v = t1.mul(t2).imod(p).imod(q); // (g**u1 * y**u2 mod p) mod q
14457 return v.equal(r);
14458 }
14459
14460 /**
14461 * Validate DSA parameters
14462 * @param {Uint8Array} p - DSA prime
14463 * @param {Uint8Array} q - DSA group order
14464 * @param {Uint8Array} g - DSA sub-group generator
14465 * @param {Uint8Array} y - DSA public key
14466 * @param {Uint8Array} x - DSA private key
14467 * @returns {Promise<Boolean>} Whether params are valid.
14468 * @async
14469 */
14470 async function validateParams$5(p, q, g, y, x) {
14471 const BigInteger = await util.getBigInteger();
14472 p = new BigInteger(p);
14473 q = new BigInteger(q);
14474 g = new BigInteger(g);
14475 y = new BigInteger(y);
14476 const one = new BigInteger(1);
14477 // Check that 1 < g < p
14478 if (g.lte(one) || g.gte(p)) {
14479 return false;
14480 }
14481
14482 /**
14483 * Check that subgroup order q divides p-1
14484 */
14485 if (!p.dec().mod(q).isZero()) {
14486 return false;
14487 }
14488
14489 /**
14490 * g has order q
14491 * Check that g ** q = 1 mod p
14492 */
14493 if (!g.modExp(q, p).isOne()) {
14494 return false;
14495 }
14496
14497 /**
14498 * Check q is large and probably prime (we mainly want to avoid small factors)
14499 */
14500 const qSize = new BigInteger(q.bitLength());
14501 const n150 = new BigInteger(150);
14502 if (qSize.lt(n150) || !(await isProbablePrime(q, null, 32))) {
14503 return false;
14504 }
14505
14506 /**
14507 * Re-derive public key y' = g ** x mod p
14508 * Expect y == y'
14509 *
14510 * Blinded exponentiation computes g**{rq + x} to compare to y
14511 */
14512 x = new BigInteger(x);
14513 const two = new BigInteger(2);
14514 const r = await getRandomBigInteger(two.leftShift(qSize.dec()), two.leftShift(qSize)); // draw r of same size as q
14515 const rqx = q.mul(r).add(x);
14516 if (!y.equal(g.modExp(rqx, p))) {
14517 return false;
14518 }
14519
14520 return true;
14521 }
14522
14523 var dsa = /*#__PURE__*/Object.freeze({
14524 __proto__: null,
14525 sign: sign$3,
14526 verify: verify$3,
14527 validateParams: validateParams$5
14528 });
14529
14530 /**
14531 * @fileoverview Asymmetric cryptography functions
14532 * @module crypto/public_key
14533 * @private
14534 */
14535
14536 var publicKey = {
14537 /** @see module:crypto/public_key/rsa */
14538 rsa: rsa,
14539 /** @see module:crypto/public_key/elgamal */
14540 elgamal: elgamal,
14541 /** @see module:crypto/public_key/elliptic */
14542 elliptic: elliptic,
14543 /** @see module:crypto/public_key/dsa */
14544 dsa: dsa,
14545 /** @see tweetnacl */
14546 nacl: naclFastLight
14547 };
14548
14549 /**
14550 * @fileoverview Provides functions for asymmetric signing and signature verification
14551 * @module crypto/signature
14552 * @private
14553 */
14554
14555 /**
14556 * Parse signature in binary form to get the parameters.
14557 * The returned values are only padded for EdDSA, since in the other cases their expected length
14558 * depends on the key params, hence we delegate the padding to the signature verification function.
14559 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
14560 * See {@link https://tools.ietf.org/html/rfc4880#section-5.2.2|RFC 4880 5.2.2.}
14561 * @param {module:enums.publicKey} algo - Public key algorithm
14562 * @param {Uint8Array} signature - Data for which the signature was created
14563 * @returns {Promise<Object>} True if signature is valid.
14564 * @async
14565 */
14566 function parseSignatureParams(algo, signature) {
14567 let read = 0;
14568 switch (algo) {
14569 // Algorithm-Specific Fields for RSA signatures:
14570 // - MPI of RSA signature value m**d mod n.
14571 case enums.publicKey.rsaEncryptSign:
14572 case enums.publicKey.rsaEncrypt:
14573 case enums.publicKey.rsaSign: {
14574 const s = util.readMPI(signature.subarray(read));
14575 // The signature needs to be the same length as the public key modulo n.
14576 // We pad s on signature verification, where we have access to n.
14577 return { s };
14578 }
14579 // Algorithm-Specific Fields for DSA or ECDSA signatures:
14580 // - MPI of DSA or ECDSA value r.
14581 // - MPI of DSA or ECDSA value s.
14582 case enums.publicKey.dsa:
14583 case enums.publicKey.ecdsa:
14584 {
14585 const r = util.readMPI(signature.subarray(read)); read += r.length + 2;
14586 const s = util.readMPI(signature.subarray(read));
14587 return { r, s };
14588 }
14589 // Algorithm-Specific Fields for EdDSA signatures:
14590 // - MPI of an EC point r.
14591 // - EdDSA value s, in MPI, in the little endian representation
14592 case enums.publicKey.eddsa: {
14593 // When parsing little-endian MPI data, we always need to left-pad it, as done with big-endian values:
14594 // https://www.ietf.org/archive/id/draft-ietf-openpgp-rfc4880bis-10.html#section-3.2-9
14595 let r = util.readMPI(signature.subarray(read)); read += r.length + 2;
14596 r = util.leftPad(r, 32);
14597 let s = util.readMPI(signature.subarray(read));
14598 s = util.leftPad(s, 32);
14599 return { r, s };
14600 }
14601 default:
14602 throw new Error('Invalid signature algorithm.');
14603 }
14604 }
14605
14606 /**
14607 * Verifies the signature provided for data using specified algorithms and public key parameters.
14608 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
14609 * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
14610 * for public key and hash algorithms.
14611 * @param {module:enums.publicKey} algo - Public key algorithm
14612 * @param {module:enums.hash} hashAlgo - Hash algorithm
14613 * @param {Object} signature - Named algorithm-specific signature parameters
14614 * @param {Object} publicParams - Algorithm-specific public key parameters
14615 * @param {Uint8Array} data - Data for which the signature was created
14616 * @param {Uint8Array} hashed - The hashed data
14617 * @returns {Promise<Boolean>} True if signature is valid.
14618 * @async
14619 */
14620 async function verify$4(algo, hashAlgo, signature, publicParams, data, hashed) {
14621 switch (algo) {
14622 case enums.publicKey.rsaEncryptSign:
14623 case enums.publicKey.rsaEncrypt:
14624 case enums.publicKey.rsaSign: {
14625 const { n, e } = publicParams;
14626 const s = util.leftPad(signature.s, n.length); // padding needed for webcrypto and node crypto
14627 return publicKey.rsa.verify(hashAlgo, data, s, n, e, hashed);
14628 }
14629 case enums.publicKey.dsa: {
14630 const { g, p, q, y } = publicParams;
14631 const { r, s } = signature; // no need to pad, since we always handle them as BigIntegers
14632 return publicKey.dsa.verify(hashAlgo, r, s, hashed, g, p, q, y);
14633 }
14634 case enums.publicKey.ecdsa: {
14635 const { oid, Q } = publicParams;
14636 const curveSize = new publicKey.elliptic.Curve(oid).payloadSize;
14637 // padding needed for webcrypto
14638 const r = util.leftPad(signature.r, curveSize);
14639 const s = util.leftPad(signature.s, curveSize);
14640 return publicKey.elliptic.ecdsa.verify(oid, hashAlgo, { r, s }, data, Q, hashed);
14641 }
14642 case enums.publicKey.eddsa: {
14643 const { oid, Q } = publicParams;
14644 // signature already padded on parsing
14645 return publicKey.elliptic.eddsa.verify(oid, hashAlgo, signature, data, Q, hashed);
14646 }
14647 default:
14648 throw new Error('Invalid signature algorithm.');
14649 }
14650 }
14651
14652 /**
14653 * Creates a signature on data using specified algorithms and private key parameters.
14654 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
14655 * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
14656 * for public key and hash algorithms.
14657 * @param {module:enums.publicKey} algo - Public key algorithm
14658 * @param {module:enums.hash} hashAlgo - Hash algorithm
14659 * @param {Object} publicKeyParams - Algorithm-specific public and private key parameters
14660 * @param {Object} privateKeyParams - Algorithm-specific public and private key parameters
14661 * @param {Uint8Array} data - Data to be signed
14662 * @param {Uint8Array} hashed - The hashed data
14663 * @returns {Promise<Object>} Signature Object containing named signature parameters.
14664 * @async
14665 */
14666 async function sign$4(algo, hashAlgo, publicKeyParams, privateKeyParams, data, hashed) {
14667 if (!publicKeyParams || !privateKeyParams) {
14668 throw new Error('Missing key parameters');
14669 }
14670 switch (algo) {
14671 case enums.publicKey.rsaEncryptSign:
14672 case enums.publicKey.rsaEncrypt:
14673 case enums.publicKey.rsaSign: {
14674 const { n, e } = publicKeyParams;
14675 const { d, p, q, u } = privateKeyParams;
14676 const s = await publicKey.rsa.sign(hashAlgo, data, n, e, d, p, q, u, hashed);
14677 return { s };
14678 }
14679 case enums.publicKey.dsa: {
14680 const { g, p, q } = publicKeyParams;
14681 const { x } = privateKeyParams;
14682 return publicKey.dsa.sign(hashAlgo, hashed, g, p, q, x);
14683 }
14684 case enums.publicKey.elgamal: {
14685 throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');
14686 }
14687 case enums.publicKey.ecdsa: {
14688 const { oid, Q } = publicKeyParams;
14689 const { d } = privateKeyParams;
14690 return publicKey.elliptic.ecdsa.sign(oid, hashAlgo, data, Q, d, hashed);
14691 }
14692 case enums.publicKey.eddsa: {
14693 const { oid, Q } = publicKeyParams;
14694 const { seed } = privateKeyParams;
14695 return publicKey.elliptic.eddsa.sign(oid, hashAlgo, data, Q, seed, hashed);
14696 }
14697 default:
14698 throw new Error('Invalid signature algorithm.');
14699 }
14700 }
14701
14702 var signature = /*#__PURE__*/Object.freeze({
14703 __proto__: null,
14704 parseSignatureParams: parseSignatureParams,
14705 verify: verify$4,
14706 sign: sign$4
14707 });
14708
14709 // OpenPGP.js - An OpenPGP implementation in javascript
14710
14711 class ECDHSymmetricKey {
14712 constructor(data) {
14713 if (typeof data === 'undefined') {
14714 data = new Uint8Array([]);
14715 } else if (util.isString(data)) {
14716 data = util.stringToUint8Array(data);
14717 } else {
14718 data = new Uint8Array(data);
14719 }
14720 this.data = data;
14721 }
14722
14723 /**
14724 * Read an ECDHSymmetricKey from an Uint8Array
14725 * @param {Uint8Array} input - Where to read the encoded symmetric key from
14726 * @returns {Number} Number of read bytes.
14727 */
14728 read(input) {
14729 if (input.length >= 1) {
14730 const length = input[0];
14731 if (input.length >= 1 + length) {
14732 this.data = input.subarray(1, 1 + length);
14733 return 1 + this.data.length;
14734 }
14735 }
14736 throw new Error('Invalid symmetric key');
14737 }
14738
14739 /**
14740 * Write an ECDHSymmetricKey as an Uint8Array
14741 * @returns {Uint8Array} An array containing the value
14742 */
14743 write() {
14744 return util.concatUint8Array([new Uint8Array([this.data.length]), this.data]);
14745 }
14746 }
14747
14748 // OpenPGP.js - An OpenPGP implementation in javascript
14749 // Copyright (C) 2015-2016 Decentral
14750 //
14751 // This library is free software; you can redistribute it and/or
14752 // modify it under the terms of the GNU Lesser General Public
14753 // License as published by the Free Software Foundation; either
14754 // version 3.0 of the License, or (at your option) any later version.
14755 //
14756 // This library is distributed in the hope that it will be useful,
14757 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14758 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14759 // Lesser General Public License for more details.
14760 //
14761 // You should have received a copy of the GNU Lesser General Public
14762 // License along with this library; if not, write to the Free Software
14763 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
14764
14765 /**
14766 * Implementation of type KDF parameters
14767 *
14768 * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:
14769 * A key derivation function (KDF) is necessary to implement the EC
14770 * encryption. The Concatenation Key Derivation Function (Approved
14771 * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is
14772 * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.
14773 * @module type/kdf_params
14774 * @private
14775 */
14776
14777 class KDFParams {
14778 /**
14779 * @param {enums.hash} hash - Hash algorithm
14780 * @param {enums.symmetric} cipher - Symmetric algorithm
14781 */
14782 constructor(data) {
14783 if (data) {
14784 const { hash, cipher } = data;
14785 this.hash = hash;
14786 this.cipher = cipher;
14787 } else {
14788 this.hash = null;
14789 this.cipher = null;
14790 }
14791 }
14792
14793 /**
14794 * Read KDFParams from an Uint8Array
14795 * @param {Uint8Array} input - Where to read the KDFParams from
14796 * @returns {Number} Number of read bytes.
14797 */
14798 read(input) {
14799 if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {
14800 throw new Error('Cannot read KDFParams');
14801 }
14802 this.hash = input[2];
14803 this.cipher = input[3];
14804 return 4;
14805 }
14806
14807 /**
14808 * Write KDFParams to an Uint8Array
14809 * @returns {Uint8Array} Array with the KDFParams value
14810 */
14811 write() {
14812 return new Uint8Array([3, 1, this.hash, this.cipher]);
14813 }
14814 }
14815
14816 // GPG4Browsers - An OpenPGP implementation in javascript
14817
14818 /**
14819 * Encrypts data using specified algorithm and public key parameters.
14820 * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.
14821 * @param {module:enums.publicKey} algo - Public key algorithm
14822 * @param {Object} publicParams - Algorithm-specific public key parameters
14823 * @param {Uint8Array} data - Data to be encrypted
14824 * @param {Uint8Array} fingerprint - Recipient fingerprint
14825 * @returns {Promise<Object>} Encrypted session key parameters.
14826 * @async
14827 */
14828 async function publicKeyEncrypt(algo, publicParams, data, fingerprint) {
14829 switch (algo) {
14830 case enums.publicKey.rsaEncrypt:
14831 case enums.publicKey.rsaEncryptSign: {
14832 const { n, e } = publicParams;
14833 const c = await publicKey.rsa.encrypt(data, n, e);
14834 return { c };
14835 }
14836 case enums.publicKey.elgamal: {
14837 const { p, g, y } = publicParams;
14838 return publicKey.elgamal.encrypt(data, p, g, y);
14839 }
14840 case enums.publicKey.ecdh: {
14841 const { oid, Q, kdfParams } = publicParams;
14842 const { publicKey: V, wrappedKey: C } = await publicKey.elliptic.ecdh.encrypt(
14843 oid, kdfParams, data, Q, fingerprint);
14844 return { V, C: new ECDHSymmetricKey(C) };
14845 }
14846 default:
14847 return [];
14848 }
14849 }
14850
14851 /**
14852 * Decrypts data using specified algorithm and private key parameters.
14853 * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}
14854 * @param {module:enums.publicKey} algo - Public key algorithm
14855 * @param {Object} publicKeyParams - Algorithm-specific public key parameters
14856 * @param {Object} privateKeyParams - Algorithm-specific private key parameters
14857 * @param {Object} sessionKeyParams - Encrypted session key parameters
14858 * @param {Uint8Array} fingerprint - Recipient fingerprint
14859 * @returns {Promise<Uint8Array>} Decrypted data.
14860 * @async
14861 */
14862 async function publicKeyDecrypt(algo, publicKeyParams, privateKeyParams, sessionKeyParams, fingerprint) {
14863 switch (algo) {
14864 case enums.publicKey.rsaEncryptSign:
14865 case enums.publicKey.rsaEncrypt: {
14866 const { c } = sessionKeyParams;
14867 const { n, e } = publicKeyParams;
14868 const { d, p, q, u } = privateKeyParams;
14869 return publicKey.rsa.decrypt(c, n, e, d, p, q, u);
14870 }
14871 case enums.publicKey.elgamal: {
14872 const { c1, c2 } = sessionKeyParams;
14873 const p = publicKeyParams.p;
14874 const x = privateKeyParams.x;
14875 return publicKey.elgamal.decrypt(c1, c2, p, x);
14876 }
14877 case enums.publicKey.ecdh: {
14878 const { oid, Q, kdfParams } = publicKeyParams;
14879 const { d } = privateKeyParams;
14880 const { V, C } = sessionKeyParams;
14881 return publicKey.elliptic.ecdh.decrypt(
14882 oid, kdfParams, V, C.data, Q, d, fingerprint);
14883 }
14884 default:
14885 throw new Error('Invalid public key encryption algorithm.');
14886 }
14887 }
14888
14889 /**
14890 * Parse public key material in binary form to get the key parameters
14891 * @param {module:enums.publicKey} algo - The key algorithm
14892 * @param {Uint8Array} bytes - The key material to parse
14893 * @returns {{ read: Number, publicParams: Object }} Number of read bytes plus key parameters referenced by name.
14894 */
14895 function parsePublicKeyParams(algo, bytes) {
14896 let read = 0;
14897 switch (algo) {
14898 case enums.publicKey.rsaEncrypt:
14899 case enums.publicKey.rsaEncryptSign:
14900 case enums.publicKey.rsaSign: {
14901 const n = util.readMPI(bytes.subarray(read)); read += n.length + 2;
14902 const e = util.readMPI(bytes.subarray(read)); read += e.length + 2;
14903 return { read, publicParams: { n, e } };
14904 }
14905 case enums.publicKey.dsa: {
14906 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
14907 const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;
14908 const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;
14909 const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;
14910 return { read, publicParams: { p, q, g, y } };
14911 }
14912 case enums.publicKey.elgamal: {
14913 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
14914 const g = util.readMPI(bytes.subarray(read)); read += g.length + 2;
14915 const y = util.readMPI(bytes.subarray(read)); read += y.length + 2;
14916 return { read, publicParams: { p, g, y } };
14917 }
14918 case enums.publicKey.ecdsa: {
14919 const oid = new OID(); read += oid.read(bytes);
14920 const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
14921 return { read: read, publicParams: { oid, Q } };
14922 }
14923 case enums.publicKey.eddsa: {
14924 const oid = new OID(); read += oid.read(bytes);
14925 let Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
14926 Q = util.leftPad(Q, 33);
14927 return { read: read, publicParams: { oid, Q } };
14928 }
14929 case enums.publicKey.ecdh: {
14930 const oid = new OID(); read += oid.read(bytes);
14931 const Q = util.readMPI(bytes.subarray(read)); read += Q.length + 2;
14932 const kdfParams = new KDFParams(); read += kdfParams.read(bytes.subarray(read));
14933 return { read: read, publicParams: { oid, Q, kdfParams } };
14934 }
14935 default:
14936 throw new Error('Invalid public key encryption algorithm.');
14937 }
14938 }
14939
14940 /**
14941 * Parse private key material in binary form to get the key parameters
14942 * @param {module:enums.publicKey} algo - The key algorithm
14943 * @param {Uint8Array} bytes - The key material to parse
14944 * @param {Object} publicParams - (ECC only) public params, needed to format some private params
14945 * @returns {{ read: Number, privateParams: Object }} Number of read bytes plus the key parameters referenced by name.
14946 */
14947 function parsePrivateKeyParams(algo, bytes, publicParams) {
14948 let read = 0;
14949 switch (algo) {
14950 case enums.publicKey.rsaEncrypt:
14951 case enums.publicKey.rsaEncryptSign:
14952 case enums.publicKey.rsaSign: {
14953 const d = util.readMPI(bytes.subarray(read)); read += d.length + 2;
14954 const p = util.readMPI(bytes.subarray(read)); read += p.length + 2;
14955 const q = util.readMPI(bytes.subarray(read)); read += q.length + 2;
14956 const u = util.readMPI(bytes.subarray(read)); read += u.length + 2;
14957 return { read, privateParams: { d, p, q, u } };
14958 }
14959 case enums.publicKey.dsa:
14960 case enums.publicKey.elgamal: {
14961 const x = util.readMPI(bytes.subarray(read)); read += x.length + 2;
14962 return { read, privateParams: { x } };
14963 }
14964 case enums.publicKey.ecdsa:
14965 case enums.publicKey.ecdh: {
14966 const curve = new Curve(publicParams.oid);
14967 let d = util.readMPI(bytes.subarray(read)); read += d.length + 2;
14968 d = util.leftPad(d, curve.payloadSize);
14969 return { read, privateParams: { d } };
14970 }
14971 case enums.publicKey.eddsa: {
14972 let seed = util.readMPI(bytes.subarray(read)); read += seed.length + 2;
14973 seed = util.leftPad(seed, 32);
14974 return { read, privateParams: { seed } };
14975 }
14976 default:
14977 throw new Error('Invalid public key encryption algorithm.');
14978 }
14979 }
14980
14981 /** Returns the types comprising the encrypted session key of an algorithm
14982 * @param {module:enums.publicKey} algo - The key algorithm
14983 * @param {Uint8Array} bytes - The key material to parse
14984 * @returns {Object} The session key parameters referenced by name.
14985 */
14986 function parseEncSessionKeyParams(algo, bytes) {
14987 let read = 0;
14988 switch (algo) {
14989 // Algorithm-Specific Fields for RSA encrypted session keys:
14990 // - MPI of RSA encrypted value m**e mod n.
14991 case enums.publicKey.rsaEncrypt:
14992 case enums.publicKey.rsaEncryptSign: {
14993 const c = util.readMPI(bytes.subarray(read));
14994 return { c };
14995 }
14996
14997 // Algorithm-Specific Fields for Elgamal encrypted session keys:
14998 // - MPI of Elgamal value g**k mod p
14999 // - MPI of Elgamal value m * y**k mod p
15000 case enums.publicKey.elgamal: {
15001 const c1 = util.readMPI(bytes.subarray(read)); read += c1.length + 2;
15002 const c2 = util.readMPI(bytes.subarray(read));
15003 return { c1, c2 };
15004 }
15005 // Algorithm-Specific Fields for ECDH encrypted session keys:
15006 // - MPI containing the ephemeral key used to establish the shared secret
15007 // - ECDH Symmetric Key
15008 case enums.publicKey.ecdh: {
15009 const V = util.readMPI(bytes.subarray(read)); read += V.length + 2;
15010 const C = new ECDHSymmetricKey(); C.read(bytes.subarray(read));
15011 return { V, C };
15012 }
15013 default:
15014 throw new Error('Invalid public key encryption algorithm.');
15015 }
15016 }
15017
15018 /**
15019 * Convert params to MPI and serializes them in the proper order
15020 * @param {module:enums.publicKey} algo - The public key algorithm
15021 * @param {Object} params - The key parameters indexed by name
15022 * @returns {Uint8Array} The array containing the MPIs.
15023 */
15024 function serializeParams(algo, params) {
15025 const orderedParams = Object.keys(params).map(name => {
15026 const param = params[name];
15027 return util.isUint8Array(param) ? util.uint8ArrayToMPI(param) : param.write();
15028 });
15029 return util.concatUint8Array(orderedParams);
15030 }
15031
15032 /**
15033 * Generate algorithm-specific key parameters
15034 * @param {module:enums.publicKey} algo - The public key algorithm
15035 * @param {Integer} bits - Bit length for RSA keys
15036 * @param {module:type/oid} oid - Object identifier for ECC keys
15037 * @returns {Promise<{ publicParams: {Object}, privateParams: {Object} }>} The parameters referenced by name.
15038 * @async
15039 */
15040 function generateParams(algo, bits, oid) {
15041 switch (algo) {
15042 case enums.publicKey.rsaEncrypt:
15043 case enums.publicKey.rsaEncryptSign:
15044 case enums.publicKey.rsaSign: {
15045 return publicKey.rsa.generate(bits, 65537).then(({ n, e, d, p, q, u }) => ({
15046 privateParams: { d, p, q, u },
15047 publicParams: { n, e }
15048 }));
15049 }
15050 case enums.publicKey.ecdsa:
15051 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({
15052 privateParams: { d: secret },
15053 publicParams: { oid: new OID(oid), Q }
15054 }));
15055 case enums.publicKey.eddsa:
15056 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret }) => ({
15057 privateParams: { seed: secret },
15058 publicParams: { oid: new OID(oid), Q }
15059 }));
15060 case enums.publicKey.ecdh:
15061 return publicKey.elliptic.generate(oid).then(({ oid, Q, secret, hash, cipher }) => ({
15062 privateParams: { d: secret },
15063 publicParams: {
15064 oid: new OID(oid),
15065 Q,
15066 kdfParams: new KDFParams({ hash, cipher })
15067 }
15068 }));
15069 case enums.publicKey.dsa:
15070 case enums.publicKey.elgamal:
15071 throw new Error('Unsupported algorithm for key generation.');
15072 default:
15073 throw new Error('Invalid public key algorithm.');
15074 }
15075 }
15076
15077 /**
15078 * Validate algorithm-specific key parameters
15079 * @param {module:enums.publicKey} algo - The public key algorithm
15080 * @param {Object} publicParams - Algorithm-specific public key parameters
15081 * @param {Object} privateParams - Algorithm-specific private key parameters
15082 * @returns {Promise<Boolean>} Whether the parameters are valid.
15083 * @async
15084 */
15085 async function validateParams$6(algo, publicParams, privateParams) {
15086 if (!publicParams || !privateParams) {
15087 throw new Error('Missing key parameters');
15088 }
15089 switch (algo) {
15090 case enums.publicKey.rsaEncrypt:
15091 case enums.publicKey.rsaEncryptSign:
15092 case enums.publicKey.rsaSign: {
15093 const { n, e } = publicParams;
15094 const { d, p, q, u } = privateParams;
15095 return publicKey.rsa.validateParams(n, e, d, p, q, u);
15096 }
15097 case enums.publicKey.dsa: {
15098 const { p, q, g, y } = publicParams;
15099 const { x } = privateParams;
15100 return publicKey.dsa.validateParams(p, q, g, y, x);
15101 }
15102 case enums.publicKey.elgamal: {
15103 const { p, g, y } = publicParams;
15104 const { x } = privateParams;
15105 return publicKey.elgamal.validateParams(p, g, y, x);
15106 }
15107 case enums.publicKey.ecdsa:
15108 case enums.publicKey.ecdh: {
15109 const algoModule = publicKey.elliptic[enums.read(enums.publicKey, algo)];
15110 const { oid, Q } = publicParams;
15111 const { d } = privateParams;
15112 return algoModule.validateParams(oid, Q, d);
15113 }
15114 case enums.publicKey.eddsa: {
15115 const { oid, Q } = publicParams;
15116 const { seed } = privateParams;
15117 return publicKey.elliptic.eddsa.validateParams(oid, Q, seed);
15118 }
15119 default:
15120 throw new Error('Invalid public key algorithm.');
15121 }
15122 }
15123
15124 /**
15125 * Generates a random byte prefix for the specified algorithm
15126 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
15127 * @param {module:enums.symmetric} algo - Symmetric encryption algorithm
15128 * @returns {Promise<Uint8Array>} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.
15129 * @async
15130 */
15131 async function getPrefixRandom(algo) {
15132 const prefixrandom = await getRandomBytes(cipher[algo].blockSize);
15133 const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);
15134 return util.concat([prefixrandom, repeat]);
15135 }
15136
15137 /**
15138 * Generating a session key for the specified symmetric algorithm
15139 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
15140 * @param {module:enums.symmetric} algo - Symmetric encryption algorithm
15141 * @returns {Promise<Uint8Array>} Random bytes as a string to be used as a key.
15142 * @async
15143 */
15144 function generateSessionKey(algo) {
15145 return getRandomBytes(cipher[algo].keySize);
15146 }
15147
15148 var crypto$1 = /*#__PURE__*/Object.freeze({
15149 __proto__: null,
15150 publicKeyEncrypt: publicKeyEncrypt,
15151 publicKeyDecrypt: publicKeyDecrypt,
15152 parsePublicKeyParams: parsePublicKeyParams,
15153 parsePrivateKeyParams: parsePrivateKeyParams,
15154 parseEncSessionKeyParams: parseEncSessionKeyParams,
15155 serializeParams: serializeParams,
15156 generateParams: generateParams,
15157 validateParams: validateParams$6,
15158 getPrefixRandom: getPrefixRandom,
15159 generateSessionKey: generateSessionKey
15160 });
15161
15162 /**
15163 * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js
15164 * @see module:crypto/crypto
15165 * @see module:crypto/signature
15166 * @see module:crypto/public_key
15167 * @see module:crypto/cipher
15168 * @see module:crypto/random
15169 * @see module:crypto/hash
15170 * @module crypto
15171 * @private
15172 */
15173
15174 // TODO move cfb and gcm to cipher
15175 const mod = {
15176 /** @see module:crypto/cipher */
15177 cipher: cipher,
15178 /** @see module:crypto/hash */
15179 hash: hash,
15180 /** @see module:crypto/mode */
15181 mode: mode,
15182 /** @see module:crypto/public_key */
15183 publicKey: publicKey,
15184 /** @see module:crypto/signature */
15185 signature: signature,
15186 /** @see module:crypto/random */
15187 random: random,
15188 /** @see module:crypto/pkcs1 */
15189 pkcs1: pkcs1,
15190 /** @see module:crypto/pkcs5 */
15191 pkcs5: pkcs5,
15192 /** @see module:crypto/aes_kw */
15193 aesKW: aesKW
15194 };
15195
15196 Object.assign(mod, crypto$1);
15197
15198 var TYPED_OK = typeof Uint8Array !== "undefined" &&
15199 typeof Uint16Array !== "undefined" &&
15200 typeof Int32Array !== "undefined";
15201
15202
15203 // reduce buffer size, avoiding mem copy
15204 function shrinkBuf(buf, size) {
15205 if (buf.length === size) {
15206 return buf;
15207 }
15208 if (buf.subarray) {
15209 return buf.subarray(0, size);
15210 }
15211 buf.length = size;
15212 return buf;
15213 }
15214
15215
15216 const fnTyped = {
15217 arraySet: function (dest, src, src_offs, len, dest_offs) {
15218 if (src.subarray && dest.subarray) {
15219 dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
15220 return;
15221 }
15222 // Fallback to ordinary array
15223 for (let i = 0; i < len; i++) {
15224 dest[dest_offs + i] = src[src_offs + i];
15225 }
15226 },
15227 // Join array of chunks to single array.
15228 flattenChunks: function (chunks) {
15229 let i, l, len, pos, chunk;
15230
15231 // calculate data length
15232 len = 0;
15233 for (i = 0, l = chunks.length; i < l; i++) {
15234 len += chunks[i].length;
15235 }
15236
15237 // join chunks
15238 const result = new Uint8Array(len);
15239 pos = 0;
15240 for (i = 0, l = chunks.length; i < l; i++) {
15241 chunk = chunks[i];
15242 result.set(chunk, pos);
15243 pos += chunk.length;
15244 }
15245
15246 return result;
15247 }
15248 };
15249
15250 const fnUntyped = {
15251 arraySet: function (dest, src, src_offs, len, dest_offs) {
15252 for (let i = 0; i < len; i++) {
15253 dest[dest_offs + i] = src[src_offs + i];
15254 }
15255 },
15256 // Join array of chunks to single array.
15257 flattenChunks: function (chunks) {
15258 return [].concat.apply([], chunks);
15259 }
15260 };
15261
15262
15263 // Enable/Disable typed arrays use, for testing
15264 //
15265
15266 let Buf8 = TYPED_OK ? Uint8Array : Array;
15267 let Buf16 = TYPED_OK ? Uint16Array : Array;
15268 let Buf32 = TYPED_OK ? Int32Array : Array;
15269 let flattenChunks = TYPED_OK ? fnTyped.flattenChunks : fnUntyped.flattenChunks;
15270 let arraySet = TYPED_OK ? fnTyped.arraySet : fnUntyped.arraySet;
15271
15272 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
15273 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
15274 //
15275 // This software is provided 'as-is', without any express or implied
15276 // warranty. In no event will the authors be held liable for any damages
15277 // arising from the use of this software.
15278 //
15279 // Permission is granted to anyone to use this software for any purpose,
15280 // including commercial applications, and to alter it and redistribute it
15281 // freely, subject to the following restrictions:
15282 //
15283 // 1. The origin of this software must not be misrepresented; you must not
15284 // claim that you wrote the original software. If you use this software
15285 // in a product, an acknowledgment in the product documentation would be
15286 // appreciated but is not required.
15287 // 2. Altered source versions must be plainly marked as such, and must not be
15288 // misrepresented as being the original software.
15289 // 3. This notice may not be removed or altered from any source distribution.
15290
15291 /* Allowed flush values; see deflate() and inflate() below for details */
15292 const Z_NO_FLUSH = 0;
15293 const Z_PARTIAL_FLUSH = 1;
15294 const Z_SYNC_FLUSH = 2;
15295 const Z_FULL_FLUSH = 3;
15296 const Z_FINISH = 4;
15297 const Z_BLOCK = 5;
15298 const Z_TREES = 6;
15299
15300 /* Return codes for the compression/decompression functions. Negative values
15301 * are errors, positive values are used for special but normal events.
15302 */
15303 const Z_OK = 0;
15304 const Z_STREAM_END = 1;
15305 const Z_NEED_DICT = 2;
15306 const Z_STREAM_ERROR = -2;
15307 const Z_DATA_ERROR = -3;
15308 //export const Z_MEM_ERROR = -4;
15309 const Z_BUF_ERROR = -5;
15310 const Z_DEFAULT_COMPRESSION = -1;
15311
15312
15313 const Z_FILTERED = 1;
15314 const Z_HUFFMAN_ONLY = 2;
15315 const Z_RLE = 3;
15316 const Z_FIXED = 4;
15317 const Z_DEFAULT_STRATEGY = 0;
15318
15319 /* Possible values of the data_type field (though see inflate()) */
15320 const Z_BINARY = 0;
15321 const Z_TEXT = 1;
15322 //export const Z_ASCII = 1; // = Z_TEXT (deprecated)
15323 const Z_UNKNOWN = 2;
15324
15325 /* The deflate compression method */
15326 const Z_DEFLATED = 8;
15327 //export const Z_NULL = null // Use -1 or null inline, depending on var type
15328
15329 /*============================================================================*/
15330
15331
15332 function zero$1(buf) {
15333 let len = buf.length; while (--len >= 0) {
15334 buf[len] = 0;
15335 }
15336 }
15337
15338 // From zutil.h
15339
15340 const STORED_BLOCK = 0;
15341 const STATIC_TREES = 1;
15342 const DYN_TREES = 2;
15343 /* The three kinds of block type */
15344
15345 const MIN_MATCH = 3;
15346 const MAX_MATCH = 258;
15347 /* The minimum and maximum match lengths */
15348
15349 // From deflate.h
15350 /* ===========================================================================
15351 * Internal compression state.
15352 */
15353
15354 const LENGTH_CODES = 29;
15355 /* number of length codes, not counting the special END_BLOCK code */
15356
15357 const LITERALS = 256;
15358 /* number of literal bytes 0..255 */
15359
15360 const L_CODES = LITERALS + 1 + LENGTH_CODES;
15361 /* number of Literal or Length codes, including the END_BLOCK code */
15362
15363 const D_CODES = 30;
15364 /* number of distance codes */
15365
15366 const BL_CODES = 19;
15367 /* number of codes used to transfer the bit lengths */
15368
15369 const HEAP_SIZE = 2 * L_CODES + 1;
15370 /* maximum heap size */
15371
15372 const MAX_BITS = 15;
15373 /* All codes must not exceed MAX_BITS bits */
15374
15375 const Buf_size = 16;
15376 /* size of bit buffer in bi_buf */
15377
15378
15379 /* ===========================================================================
15380 * Constants
15381 */
15382
15383 const MAX_BL_BITS = 7;
15384 /* Bit length codes must not exceed MAX_BL_BITS bits */
15385
15386 const END_BLOCK = 256;
15387 /* end of block literal code */
15388
15389 const REP_3_6 = 16;
15390 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
15391
15392 const REPZ_3_10 = 17;
15393 /* repeat a zero length 3-10 times (3 bits of repeat count) */
15394
15395 const REPZ_11_138 = 18;
15396 /* repeat a zero length 11-138 times (7 bits of repeat count) */
15397
15398 /* eslint-disable comma-spacing,array-bracket-spacing */
15399 const extra_lbits = /* extra bits for each length code */
15400 [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];
15401
15402 const extra_dbits = /* extra bits for each distance code */
15403 [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];
15404
15405 const extra_blbits = /* extra bits for each bit length code */
15406 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
15407
15408 const bl_order =
15409 [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
15410 /* eslint-enable comma-spacing,array-bracket-spacing */
15411
15412 /* The lengths of the bit length codes are sent in order of decreasing
15413 * probability, to avoid transmitting the lengths for unused bit length codes.
15414 */
15415
15416 /* ===========================================================================
15417 * Local data. These are initialized only once.
15418 */
15419
15420 // We pre-fill arrays with 0 to avoid uninitialized gaps
15421
15422 const DIST_CODE_LEN = 512; /* see definition of array dist_code below */
15423
15424 // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
15425 const static_ltree = new Array((L_CODES + 2) * 2);
15426 zero$1(static_ltree);
15427 /* The static literal tree. Since the bit lengths are imposed, there is no
15428 * need for the L_CODES extra codes used during heap construction. However
15429 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
15430 * below).
15431 */
15432
15433 const static_dtree = new Array(D_CODES * 2);
15434 zero$1(static_dtree);
15435 /* The static distance tree. (Actually a trivial tree since all codes use
15436 * 5 bits.)
15437 */
15438
15439 const _dist_code = new Array(DIST_CODE_LEN);
15440 zero$1(_dist_code);
15441 /* Distance codes. The first 256 values correspond to the distances
15442 * 3 .. 258, the last 256 values correspond to the top 8 bits of
15443 * the 15 bit distances.
15444 */
15445
15446 const _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
15447 zero$1(_length_code);
15448 /* length code for each normalized match length (0 == MIN_MATCH) */
15449
15450 const base_length = new Array(LENGTH_CODES);
15451 zero$1(base_length);
15452 /* First normalized length for each code (0 = MIN_MATCH) */
15453
15454 const base_dist = new Array(D_CODES);
15455 zero$1(base_dist);
15456 /* First normalized distance for each code (0 = distance of 1) */
15457
15458
15459 function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
15460
15461 this.static_tree = static_tree; /* static tree or NULL */
15462 this.extra_bits = extra_bits; /* extra bits for each code or NULL */
15463 this.extra_base = extra_base; /* base index for extra_bits */
15464 this.elems = elems; /* max number of elements in the tree */
15465 this.max_length = max_length; /* max bit length for the codes */
15466
15467 // show if `static_tree` has data or dummy - needed for monomorphic objects
15468 this.has_stree = static_tree && static_tree.length;
15469 }
15470
15471
15472 let static_l_desc;
15473 let static_d_desc;
15474 let static_bl_desc;
15475
15476
15477 function TreeDesc(dyn_tree, stat_desc) {
15478 this.dyn_tree = dyn_tree; /* the dynamic tree */
15479 this.max_code = 0; /* largest code with non zero frequency */
15480 this.stat_desc = stat_desc; /* the corresponding static tree */
15481 }
15482
15483
15484
15485 function d_code(dist) {
15486 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
15487 }
15488
15489
15490 /* ===========================================================================
15491 * Output a short LSB first on the stream.
15492 * IN assertion: there is enough room in pendingBuf.
15493 */
15494 function put_short(s, w) {
15495 // put_byte(s, (uch)((w) & 0xff));
15496 // put_byte(s, (uch)((ush)(w) >> 8));
15497 s.pending_buf[s.pending++] = w & 0xff;
15498 s.pending_buf[s.pending++] = w >>> 8 & 0xff;
15499 }
15500
15501
15502 /* ===========================================================================
15503 * Send a value on a given number of bits.
15504 * IN assertion: length <= 16 and value fits in length bits.
15505 */
15506 function send_bits(s, value, length) {
15507 if (s.bi_valid > Buf_size - length) {
15508 s.bi_buf |= value << s.bi_valid & 0xffff;
15509 put_short(s, s.bi_buf);
15510 s.bi_buf = value >> Buf_size - s.bi_valid;
15511 s.bi_valid += length - Buf_size;
15512 } else {
15513 s.bi_buf |= value << s.bi_valid & 0xffff;
15514 s.bi_valid += length;
15515 }
15516 }
15517
15518
15519 function send_code(s, c, tree) {
15520 send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
15521 }
15522
15523
15524 /* ===========================================================================
15525 * Reverse the first len bits of a code, using straightforward code (a faster
15526 * method would use a table)
15527 * IN assertion: 1 <= len <= 15
15528 */
15529 function bi_reverse(code, len) {
15530 let res = 0;
15531 do {
15532 res |= code & 1;
15533 code >>>= 1;
15534 res <<= 1;
15535 } while (--len > 0);
15536 return res >>> 1;
15537 }
15538
15539
15540 /* ===========================================================================
15541 * Flush the bit buffer, keeping at most 7 bits in it.
15542 */
15543 function bi_flush(s) {
15544 if (s.bi_valid === 16) {
15545 put_short(s, s.bi_buf);
15546 s.bi_buf = 0;
15547 s.bi_valid = 0;
15548
15549 } else if (s.bi_valid >= 8) {
15550 s.pending_buf[s.pending++] = s.bi_buf & 0xff;
15551 s.bi_buf >>= 8;
15552 s.bi_valid -= 8;
15553 }
15554 }
15555
15556
15557 /* ===========================================================================
15558 * Compute the optimal bit lengths for a tree and update the total bit length
15559 * for the current block.
15560 * IN assertion: the fields freq and dad are set, heap[heap_max] and
15561 * above are the tree nodes sorted by increasing frequency.
15562 * OUT assertions: the field len is set to the optimal bit length, the
15563 * array bl_count contains the frequencies for each bit length.
15564 * The length opt_len is updated; static_len is also updated if stree is
15565 * not null.
15566 */
15567 function gen_bitlen(s, desc)
15568 // deflate_state *s;
15569 // tree_desc *desc; /* the tree descriptor */
15570 {
15571 const tree = desc.dyn_tree;
15572 const max_code = desc.max_code;
15573 const stree = desc.stat_desc.static_tree;
15574 const has_stree = desc.stat_desc.has_stree;
15575 const extra = desc.stat_desc.extra_bits;
15576 const base = desc.stat_desc.extra_base;
15577 const max_length = desc.stat_desc.max_length;
15578 let h; /* heap index */
15579 let n, m; /* iterate over the tree elements */
15580 let bits; /* bit length */
15581 let xbits; /* extra bits */
15582 let f; /* frequency */
15583 let overflow = 0; /* number of elements with bit length too large */
15584
15585 for (bits = 0; bits <= MAX_BITS; bits++) {
15586 s.bl_count[bits] = 0;
15587 }
15588
15589 /* In a first pass, compute the optimal bit lengths (which may
15590 * overflow in the case of the bit length tree).
15591 */
15592 tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
15593
15594 for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
15595 n = s.heap[h];
15596 bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
15597 if (bits > max_length) {
15598 bits = max_length;
15599 overflow++;
15600 }
15601 tree[n * 2 + 1]/*.Len*/ = bits;
15602 /* We overwrite tree[n].Dad which is no longer needed */
15603
15604 if (n > max_code) {
15605 continue;
15606 } /* not a leaf node */
15607
15608 s.bl_count[bits]++;
15609 xbits = 0;
15610 if (n >= base) {
15611 xbits = extra[n - base];
15612 }
15613 f = tree[n * 2]/*.Freq*/;
15614 s.opt_len += f * (bits + xbits);
15615 if (has_stree) {
15616 s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
15617 }
15618 }
15619 if (overflow === 0) {
15620 return;
15621 }
15622
15623 // Trace((stderr,"\nbit length overflow\n"));
15624 /* This happens for example on obj2 and pic of the Calgary corpus */
15625
15626 /* Find the first bit length which could increase: */
15627 do {
15628 bits = max_length - 1;
15629 while (s.bl_count[bits] === 0) {
15630 bits--;
15631 }
15632 s.bl_count[bits]--; /* move one leaf down the tree */
15633 s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
15634 s.bl_count[max_length]--;
15635 /* The brother of the overflow item also moves one step up,
15636 * but this does not affect bl_count[max_length]
15637 */
15638 overflow -= 2;
15639 } while (overflow > 0);
15640
15641 /* Now recompute all bit lengths, scanning in increasing frequency.
15642 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
15643 * lengths instead of fixing only the wrong ones. This idea is taken
15644 * from 'ar' written by Haruhiko Okumura.)
15645 */
15646 for (bits = max_length; bits !== 0; bits--) {
15647 n = s.bl_count[bits];
15648 while (n !== 0) {
15649 m = s.heap[--h];
15650 if (m > max_code) {
15651 continue;
15652 }
15653 if (tree[m * 2 + 1]/*.Len*/ !== bits) {
15654 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
15655 s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
15656 tree[m * 2 + 1]/*.Len*/ = bits;
15657 }
15658 n--;
15659 }
15660 }
15661 }
15662
15663
15664 /* ===========================================================================
15665 * Generate the codes for a given tree and bit counts (which need not be
15666 * optimal).
15667 * IN assertion: the array bl_count contains the bit length statistics for
15668 * the given tree and the field len is set for all tree elements.
15669 * OUT assertion: the field code is set for all tree elements of non
15670 * zero code length.
15671 */
15672 function gen_codes(tree, max_code, bl_count)
15673 // ct_data *tree; /* the tree to decorate */
15674 // int max_code; /* largest code with non zero frequency */
15675 // ushf *bl_count; /* number of codes at each bit length */
15676 {
15677 const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
15678 let code = 0; /* running code value */
15679 let bits; /* bit index */
15680 let n; /* code index */
15681
15682 /* The distribution counts are first used to generate the code values
15683 * without bit reversal.
15684 */
15685 for (bits = 1; bits <= MAX_BITS; bits++) {
15686 next_code[bits] = code = code + bl_count[bits - 1] << 1;
15687 }
15688 /* Check that the bit counts in bl_count are consistent. The last code
15689 * must be all ones.
15690 */
15691 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
15692 // "inconsistent bit counts");
15693 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
15694
15695 for (n = 0; n <= max_code; n++) {
15696 const len = tree[n * 2 + 1]/*.Len*/;
15697 if (len === 0) {
15698 continue;
15699 }
15700 /* Now reverse the bits */
15701 tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
15702
15703 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
15704 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
15705 }
15706 }
15707
15708
15709 /* ===========================================================================
15710 * Initialize the various 'constant' tables.
15711 */
15712 function tr_static_init() {
15713 let n; /* iterates over tree elements */
15714 let bits; /* bit counter */
15715 let length; /* length value */
15716 let code; /* code value */
15717 let dist; /* distance index */
15718 const bl_count = new Array(MAX_BITS + 1);
15719 /* number of codes at each bit length for an optimal tree */
15720
15721 // do check in _tr_init()
15722 //if (static_init_done) return;
15723
15724 /* For some embedded targets, global variables are not initialized: */
15725 /*#ifdef NO_INIT_GLOBAL_POINTERS
15726 static_l_desc.static_tree = static_ltree;
15727 static_l_desc.extra_bits = extra_lbits;
15728 static_d_desc.static_tree = static_dtree;
15729 static_d_desc.extra_bits = extra_dbits;
15730 static_bl_desc.extra_bits = extra_blbits;
15731 #endif*/
15732
15733 /* Initialize the mapping length (0..255) -> length code (0..28) */
15734 length = 0;
15735 for (code = 0; code < LENGTH_CODES - 1; code++) {
15736 base_length[code] = length;
15737 for (n = 0; n < 1 << extra_lbits[code]; n++) {
15738 _length_code[length++] = code;
15739 }
15740 }
15741 //Assert (length == 256, "tr_static_init: length != 256");
15742 /* Note that the length 255 (match length 258) can be represented
15743 * in two different ways: code 284 + 5 bits or code 285, so we
15744 * overwrite length_code[255] to use the best encoding:
15745 */
15746 _length_code[length - 1] = code;
15747
15748 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
15749 dist = 0;
15750 for (code = 0; code < 16; code++) {
15751 base_dist[code] = dist;
15752 for (n = 0; n < 1 << extra_dbits[code]; n++) {
15753 _dist_code[dist++] = code;
15754 }
15755 }
15756 //Assert (dist == 256, "tr_static_init: dist != 256");
15757 dist >>= 7; /* from now on, all distances are divided by 128 */
15758 for (; code < D_CODES; code++) {
15759 base_dist[code] = dist << 7;
15760 for (n = 0; n < 1 << extra_dbits[code] - 7; n++) {
15761 _dist_code[256 + dist++] = code;
15762 }
15763 }
15764 //Assert (dist == 256, "tr_static_init: 256+dist != 512");
15765
15766 /* Construct the codes of the static literal tree */
15767 for (bits = 0; bits <= MAX_BITS; bits++) {
15768 bl_count[bits] = 0;
15769 }
15770
15771 n = 0;
15772 while (n <= 143) {
15773 static_ltree[n * 2 + 1]/*.Len*/ = 8;
15774 n++;
15775 bl_count[8]++;
15776 }
15777 while (n <= 255) {
15778 static_ltree[n * 2 + 1]/*.Len*/ = 9;
15779 n++;
15780 bl_count[9]++;
15781 }
15782 while (n <= 279) {
15783 static_ltree[n * 2 + 1]/*.Len*/ = 7;
15784 n++;
15785 bl_count[7]++;
15786 }
15787 while (n <= 287) {
15788 static_ltree[n * 2 + 1]/*.Len*/ = 8;
15789 n++;
15790 bl_count[8]++;
15791 }
15792 /* Codes 286 and 287 do not exist, but we must include them in the
15793 * tree construction to get a canonical Huffman tree (longest code
15794 * all ones)
15795 */
15796 gen_codes(static_ltree, L_CODES + 1, bl_count);
15797
15798 /* The static distance tree is trivial: */
15799 for (n = 0; n < D_CODES; n++) {
15800 static_dtree[n * 2 + 1]/*.Len*/ = 5;
15801 static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
15802 }
15803
15804 // Now data ready and we can init static trees
15805 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
15806 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
15807 static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
15808
15809 //static_init_done = true;
15810 }
15811
15812
15813 /* ===========================================================================
15814 * Initialize a new block.
15815 */
15816 function init_block(s) {
15817 let n; /* iterates over tree elements */
15818
15819 /* Initialize the trees. */
15820 for (n = 0; n < L_CODES; n++) {
15821 s.dyn_ltree[n * 2]/*.Freq*/ = 0;
15822 }
15823 for (n = 0; n < D_CODES; n++) {
15824 s.dyn_dtree[n * 2]/*.Freq*/ = 0;
15825 }
15826 for (n = 0; n < BL_CODES; n++) {
15827 s.bl_tree[n * 2]/*.Freq*/ = 0;
15828 }
15829
15830 s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
15831 s.opt_len = s.static_len = 0;
15832 s.last_lit = s.matches = 0;
15833 }
15834
15835
15836 /* ===========================================================================
15837 * Flush the bit buffer and align the output on a byte boundary
15838 */
15839 function bi_windup(s) {
15840 if (s.bi_valid > 8) {
15841 put_short(s, s.bi_buf);
15842 } else if (s.bi_valid > 0) {
15843 //put_byte(s, (Byte)s->bi_buf);
15844 s.pending_buf[s.pending++] = s.bi_buf;
15845 }
15846 s.bi_buf = 0;
15847 s.bi_valid = 0;
15848 }
15849
15850 /* ===========================================================================
15851 * Copy a stored block, storing first the length and its
15852 * one's complement if requested.
15853 */
15854 function copy_block(s, buf, len, header)
15855 //DeflateState *s;
15856 //charf *buf; /* the input data */
15857 //unsigned len; /* its length */
15858 //int header; /* true if block header must be written */
15859 {
15860 bi_windup(s); /* align on byte boundary */
15861
15862 if (header) {
15863 put_short(s, len);
15864 put_short(s, ~len);
15865 }
15866 // while (len--) {
15867 // put_byte(s, *buf++);
15868 // }
15869 arraySet(s.pending_buf, s.window, buf, len, s.pending);
15870 s.pending += len;
15871 }
15872
15873 /* ===========================================================================
15874 * Compares to subtrees, using the tree depth as tie breaker when
15875 * the subtrees have equal frequency. This minimizes the worst case length.
15876 */
15877 function smaller(tree, n, m, depth) {
15878 const _n2 = n * 2;
15879 const _m2 = m * 2;
15880 return tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
15881 tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m];
15882 }
15883
15884 /* ===========================================================================
15885 * Restore the heap property by moving down the tree starting at node k,
15886 * exchanging a node with the smallest of its two sons if necessary, stopping
15887 * when the heap property is re-established (each father smaller than its
15888 * two sons).
15889 */
15890 function pqdownheap(s, tree, k)
15891 // deflate_state *s;
15892 // ct_data *tree; /* the tree to restore */
15893 // int k; /* node to move down */
15894 {
15895 const v = s.heap[k];
15896 let j = k << 1; /* left son of k */
15897 while (j <= s.heap_len) {
15898 /* Set j to the smallest of the two sons: */
15899 if (j < s.heap_len &&
15900 smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
15901 j++;
15902 }
15903 /* Exit if v is smaller than both sons */
15904 if (smaller(tree, v, s.heap[j], s.depth)) {
15905 break;
15906 }
15907
15908 /* Exchange v with the smallest son */
15909 s.heap[k] = s.heap[j];
15910 k = j;
15911
15912 /* And continue down the tree, setting j to the left son of k */
15913 j <<= 1;
15914 }
15915 s.heap[k] = v;
15916 }
15917
15918
15919 // inlined manually
15920 // var SMALLEST = 1;
15921
15922 /* ===========================================================================
15923 * Send the block data compressed using the given Huffman trees
15924 */
15925 function compress_block(s, ltree, dtree)
15926 // deflate_state *s;
15927 // const ct_data *ltree; /* literal tree */
15928 // const ct_data *dtree; /* distance tree */
15929 {
15930 let dist; /* distance of matched string */
15931 let lc; /* match length or unmatched char (if dist == 0) */
15932 let lx = 0; /* running index in l_buf */
15933 let code; /* the code to send */
15934 let extra; /* number of extra bits to send */
15935
15936 if (s.last_lit !== 0) {
15937 do {
15938 dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1];
15939 lc = s.pending_buf[s.l_buf + lx];
15940 lx++;
15941
15942 if (dist === 0) {
15943 send_code(s, lc, ltree); /* send a literal byte */
15944 //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
15945 } else {
15946 /* Here, lc is the match length - MIN_MATCH */
15947 code = _length_code[lc];
15948 send_code(s, code + LITERALS + 1, ltree); /* send the length code */
15949 extra = extra_lbits[code];
15950 if (extra !== 0) {
15951 lc -= base_length[code];
15952 send_bits(s, lc, extra); /* send the extra length bits */
15953 }
15954 dist--; /* dist is now the match distance - 1 */
15955 code = d_code(dist);
15956 //Assert (code < D_CODES, "bad d_code");
15957
15958 send_code(s, code, dtree); /* send the distance code */
15959 extra = extra_dbits[code];
15960 if (extra !== 0) {
15961 dist -= base_dist[code];
15962 send_bits(s, dist, extra); /* send the extra distance bits */
15963 }
15964 } /* literal or match pair ? */
15965
15966 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
15967 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
15968 // "pendingBuf overflow");
15969
15970 } while (lx < s.last_lit);
15971 }
15972
15973 send_code(s, END_BLOCK, ltree);
15974 }
15975
15976
15977 /* ===========================================================================
15978 * Construct one Huffman tree and assigns the code bit strings and lengths.
15979 * Update the total bit length for the current block.
15980 * IN assertion: the field freq is set for all tree elements.
15981 * OUT assertions: the fields len and code are set to the optimal bit length
15982 * and corresponding code. The length opt_len is updated; static_len is
15983 * also updated if stree is not null. The field max_code is set.
15984 */
15985 function build_tree(s, desc)
15986 // deflate_state *s;
15987 // tree_desc *desc; /* the tree descriptor */
15988 {
15989 const tree = desc.dyn_tree;
15990 const stree = desc.stat_desc.static_tree;
15991 const has_stree = desc.stat_desc.has_stree;
15992 const elems = desc.stat_desc.elems;
15993 let n, m; /* iterate over heap elements */
15994 let max_code = -1; /* largest code with non zero frequency */
15995 let node; /* new node being created */
15996
15997 /* Construct the initial heap, with least frequent element in
15998 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
15999 * heap[0] is not used.
16000 */
16001 s.heap_len = 0;
16002 s.heap_max = HEAP_SIZE;
16003
16004 for (n = 0; n < elems; n++) {
16005 if (tree[n * 2]/*.Freq*/ !== 0) {
16006 s.heap[++s.heap_len] = max_code = n;
16007 s.depth[n] = 0;
16008
16009 } else {
16010 tree[n * 2 + 1]/*.Len*/ = 0;
16011 }
16012 }
16013
16014 /* The pkzip format requires that at least one distance code exists,
16015 * and that at least one bit should be sent even if there is only one
16016 * possible code. So to avoid special checks later on we force at least
16017 * two codes of non zero frequency.
16018 */
16019 while (s.heap_len < 2) {
16020 node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
16021 tree[node * 2]/*.Freq*/ = 1;
16022 s.depth[node] = 0;
16023 s.opt_len--;
16024
16025 if (has_stree) {
16026 s.static_len -= stree[node * 2 + 1]/*.Len*/;
16027 }
16028 /* node is 0 or 1 so it does not have extra bits */
16029 }
16030 desc.max_code = max_code;
16031
16032 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
16033 * establish sub-heaps of increasing lengths:
16034 */
16035 for (n = s.heap_len >> 1/*int /2*/; n >= 1; n--) {
16036 pqdownheap(s, tree, n);
16037 }
16038
16039 /* Construct the Huffman tree by repeatedly combining the least two
16040 * frequent nodes.
16041 */
16042 node = elems; /* next internal node of the tree */
16043 do {
16044 //pqremove(s, tree, n); /* n = node of least frequency */
16045 /*** pqremove ***/
16046 n = s.heap[1/*SMALLEST*/];
16047 s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
16048 pqdownheap(s, tree, 1/*SMALLEST*/);
16049 /***/
16050
16051 m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
16052
16053 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
16054 s.heap[--s.heap_max] = m;
16055
16056 /* Create a new node father of n and m */
16057 tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
16058 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
16059 tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
16060
16061 /* and insert the new node in the heap */
16062 s.heap[1/*SMALLEST*/] = node++;
16063 pqdownheap(s, tree, 1/*SMALLEST*/);
16064
16065 } while (s.heap_len >= 2);
16066
16067 s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
16068
16069 /* At this point, the fields freq and dad are set. We can now
16070 * generate the bit lengths.
16071 */
16072 gen_bitlen(s, desc);
16073
16074 /* The field len is now set, we can generate the bit codes */
16075 gen_codes(tree, max_code, s.bl_count);
16076 }
16077
16078
16079 /* ===========================================================================
16080 * Scan a literal or distance tree to determine the frequencies of the codes
16081 * in the bit length tree.
16082 */
16083 function scan_tree(s, tree, max_code)
16084 // deflate_state *s;
16085 // ct_data *tree; /* the tree to be scanned */
16086 // int max_code; /* and its largest code of non zero frequency */
16087 {
16088 let n; /* iterates over all tree elements */
16089 let prevlen = -1; /* last emitted length */
16090 let curlen; /* length of current code */
16091
16092 let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
16093
16094 let count = 0; /* repeat count of the current code */
16095 let max_count = 7; /* max repeat count */
16096 let min_count = 4; /* min repeat count */
16097
16098 if (nextlen === 0) {
16099 max_count = 138;
16100 min_count = 3;
16101 }
16102 tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
16103
16104 for (n = 0; n <= max_code; n++) {
16105 curlen = nextlen;
16106 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
16107
16108 if (++count < max_count && curlen === nextlen) {
16109 continue;
16110
16111 } else if (count < min_count) {
16112 s.bl_tree[curlen * 2]/*.Freq*/ += count;
16113
16114 } else if (curlen !== 0) {
16115
16116 if (curlen !== prevlen) {
16117 s.bl_tree[curlen * 2]/*.Freq*/++;
16118 }
16119 s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
16120
16121 } else if (count <= 10) {
16122 s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
16123
16124 } else {
16125 s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
16126 }
16127
16128 count = 0;
16129 prevlen = curlen;
16130
16131 if (nextlen === 0) {
16132 max_count = 138;
16133 min_count = 3;
16134
16135 } else if (curlen === nextlen) {
16136 max_count = 6;
16137 min_count = 3;
16138
16139 } else {
16140 max_count = 7;
16141 min_count = 4;
16142 }
16143 }
16144 }
16145
16146
16147 /* ===========================================================================
16148 * Send a literal or distance tree in compressed form, using the codes in
16149 * bl_tree.
16150 */
16151 function send_tree(s, tree, max_code)
16152 // deflate_state *s;
16153 // ct_data *tree; /* the tree to be scanned */
16154 // int max_code; /* and its largest code of non zero frequency */
16155 {
16156 let n; /* iterates over all tree elements */
16157 let prevlen = -1; /* last emitted length */
16158 let curlen; /* length of current code */
16159
16160 let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
16161
16162 let count = 0; /* repeat count of the current code */
16163 let max_count = 7; /* max repeat count */
16164 let min_count = 4; /* min repeat count */
16165
16166 /* tree[max_code+1].Len = -1; */ /* guard already set */
16167 if (nextlen === 0) {
16168 max_count = 138;
16169 min_count = 3;
16170 }
16171
16172 for (n = 0; n <= max_code; n++) {
16173 curlen = nextlen;
16174 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
16175
16176 if (++count < max_count && curlen === nextlen) {
16177 continue;
16178
16179 } else if (count < min_count) {
16180 do {
16181 send_code(s, curlen, s.bl_tree);
16182 } while (--count !== 0);
16183
16184 } else if (curlen !== 0) {
16185 if (curlen !== prevlen) {
16186 send_code(s, curlen, s.bl_tree);
16187 count--;
16188 }
16189 //Assert(count >= 3 && count <= 6, " 3_6?");
16190 send_code(s, REP_3_6, s.bl_tree);
16191 send_bits(s, count - 3, 2);
16192
16193 } else if (count <= 10) {
16194 send_code(s, REPZ_3_10, s.bl_tree);
16195 send_bits(s, count - 3, 3);
16196
16197 } else {
16198 send_code(s, REPZ_11_138, s.bl_tree);
16199 send_bits(s, count - 11, 7);
16200 }
16201
16202 count = 0;
16203 prevlen = curlen;
16204 if (nextlen === 0) {
16205 max_count = 138;
16206 min_count = 3;
16207
16208 } else if (curlen === nextlen) {
16209 max_count = 6;
16210 min_count = 3;
16211
16212 } else {
16213 max_count = 7;
16214 min_count = 4;
16215 }
16216 }
16217 }
16218
16219
16220 /* ===========================================================================
16221 * Construct the Huffman tree for the bit lengths and return the index in
16222 * bl_order of the last bit length code to send.
16223 */
16224 function build_bl_tree(s) {
16225 let max_blindex; /* index of last bit length code of non zero freq */
16226
16227 /* Determine the bit length frequencies for literal and distance trees */
16228 scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
16229 scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
16230
16231 /* Build the bit length tree: */
16232 build_tree(s, s.bl_desc);
16233 /* opt_len now includes the length of the tree representations, except
16234 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
16235 */
16236
16237 /* Determine the number of bit length codes to send. The pkzip format
16238 * requires that at least 4 bit length codes be sent. (appnote.txt says
16239 * 3 but the actual value used is 4.)
16240 */
16241 for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
16242 if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
16243 break;
16244 }
16245 }
16246 /* Update opt_len to include the bit length tree and counts */
16247 s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
16248 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
16249 // s->opt_len, s->static_len));
16250
16251 return max_blindex;
16252 }
16253
16254
16255 /* ===========================================================================
16256 * Send the header for a block using dynamic Huffman trees: the counts, the
16257 * lengths of the bit length codes, the literal tree and the distance tree.
16258 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
16259 */
16260 function send_all_trees(s, lcodes, dcodes, blcodes)
16261 // deflate_state *s;
16262 // int lcodes, dcodes, blcodes; /* number of codes for each tree */
16263 {
16264 let rank; /* index in bl_order */
16265
16266 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
16267 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
16268 // "too many codes");
16269 //Tracev((stderr, "\nbl counts: "));
16270 send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
16271 send_bits(s, dcodes - 1, 5);
16272 send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
16273 for (rank = 0; rank < blcodes; rank++) {
16274 //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
16275 send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
16276 }
16277 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
16278
16279 send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
16280 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
16281
16282 send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
16283 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
16284 }
16285
16286
16287 /* ===========================================================================
16288 * Check if the data type is TEXT or BINARY, using the following algorithm:
16289 * - TEXT if the two conditions below are satisfied:
16290 * a) There are no non-portable control characters belonging to the
16291 * "black list" (0..6, 14..25, 28..31).
16292 * b) There is at least one printable character belonging to the
16293 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
16294 * - BINARY otherwise.
16295 * - The following partially-portable control characters form a
16296 * "gray list" that is ignored in this detection algorithm:
16297 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
16298 * IN assertion: the fields Freq of dyn_ltree are set.
16299 */
16300 function detect_data_type(s) {
16301 /* black_mask is the bit mask of black-listed bytes
16302 * set bits 0..6, 14..25, and 28..31
16303 * 0xf3ffc07f = binary 11110011111111111100000001111111
16304 */
16305 let black_mask = 0xf3ffc07f;
16306 let n;
16307
16308 /* Check for non-textual ("black-listed") bytes. */
16309 for (n = 0; n <= 31; n++, black_mask >>>= 1) {
16310 if (black_mask & 1 && s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
16311 return Z_BINARY;
16312 }
16313 }
16314
16315 /* Check for textual ("white-listed") bytes. */
16316 if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
16317 s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
16318 return Z_TEXT;
16319 }
16320 for (n = 32; n < LITERALS; n++) {
16321 if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
16322 return Z_TEXT;
16323 }
16324 }
16325
16326 /* There are no "black-listed" or "white-listed" bytes:
16327 * this stream either is empty or has tolerated ("gray-listed") bytes only.
16328 */
16329 return Z_BINARY;
16330 }
16331
16332
16333 let static_init_done = false;
16334
16335 /* ===========================================================================
16336 * Initialize the tree data structures for a new zlib stream.
16337 */
16338 function _tr_init(s) {
16339
16340 if (!static_init_done) {
16341 tr_static_init();
16342 static_init_done = true;
16343 }
16344
16345 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
16346 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
16347 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
16348
16349 s.bi_buf = 0;
16350 s.bi_valid = 0;
16351
16352 /* Initialize the first block of the first file: */
16353 init_block(s);
16354 }
16355
16356
16357 /* ===========================================================================
16358 * Send a stored block
16359 */
16360 function _tr_stored_block(s, buf, stored_len, last)
16361 //DeflateState *s;
16362 //charf *buf; /* input block */
16363 //ulg stored_len; /* length of input block */
16364 //int last; /* one if this is the last block for a file */
16365 {
16366 send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
16367 copy_block(s, buf, stored_len, true); /* with header */
16368 }
16369
16370
16371 /* ===========================================================================
16372 * Send one empty static block to give enough lookahead for inflate.
16373 * This takes 10 bits, of which 7 may remain in the bit buffer.
16374 */
16375 function _tr_align(s) {
16376 send_bits(s, STATIC_TREES << 1, 3);
16377 send_code(s, END_BLOCK, static_ltree);
16378 bi_flush(s);
16379 }
16380
16381
16382 /* ===========================================================================
16383 * Determine the best encoding for the current block: dynamic trees, static
16384 * trees or store, and output the encoded block to the zip file.
16385 */
16386 function _tr_flush_block(s, buf, stored_len, last)
16387 //DeflateState *s;
16388 //charf *buf; /* input block, or NULL if too old */
16389 //ulg stored_len; /* length of input block */
16390 //int last; /* one if this is the last block for a file */
16391 {
16392 let opt_lenb, static_lenb; /* opt_len and static_len in bytes */
16393 let max_blindex = 0; /* index of last bit length code of non zero freq */
16394
16395 /* Build the Huffman trees unless a stored block is forced */
16396 if (s.level > 0) {
16397
16398 /* Check if the file is binary or text */
16399 if (s.strm.data_type === Z_UNKNOWN) {
16400 s.strm.data_type = detect_data_type(s);
16401 }
16402
16403 /* Construct the literal and distance trees */
16404 build_tree(s, s.l_desc);
16405 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
16406 // s->static_len));
16407
16408 build_tree(s, s.d_desc);
16409 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
16410 // s->static_len));
16411 /* At this point, opt_len and static_len are the total bit lengths of
16412 * the compressed block data, excluding the tree representations.
16413 */
16414
16415 /* Build the bit length tree for the above two trees, and get the index
16416 * in bl_order of the last bit length code to send.
16417 */
16418 max_blindex = build_bl_tree(s);
16419
16420 /* Determine the best encoding. Compute the block lengths in bytes. */
16421 opt_lenb = s.opt_len + 3 + 7 >>> 3;
16422 static_lenb = s.static_len + 3 + 7 >>> 3;
16423
16424 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
16425 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
16426 // s->last_lit));
16427
16428 if (static_lenb <= opt_lenb) {
16429 opt_lenb = static_lenb;
16430 }
16431
16432 } else {
16433 // Assert(buf != (char*)0, "lost buf");
16434 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
16435 }
16436
16437 if (stored_len + 4 <= opt_lenb && buf !== -1) {
16438 /* 4: two words for the lengths */
16439
16440 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
16441 * Otherwise we can't have processed more than WSIZE input bytes since
16442 * the last block flush, because compression would have been
16443 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
16444 * transform a block into a stored block.
16445 */
16446 _tr_stored_block(s, buf, stored_len, last);
16447
16448 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
16449
16450 send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
16451 compress_block(s, static_ltree, static_dtree);
16452
16453 } else {
16454 send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
16455 send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
16456 compress_block(s, s.dyn_ltree, s.dyn_dtree);
16457 }
16458 // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
16459 /* The above check is made mod 2^32, for files larger than 512 MB
16460 * and uLong implemented on 32 bits.
16461 */
16462 init_block(s);
16463
16464 if (last) {
16465 bi_windup(s);
16466 }
16467 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
16468 // s->compressed_len-7*last));
16469 }
16470
16471 /* ===========================================================================
16472 * Save the match info and tally the frequency counts. Return true if
16473 * the current block must be flushed.
16474 */
16475 function _tr_tally(s, dist, lc)
16476 // deflate_state *s;
16477 // unsigned dist; /* distance of matched string */
16478 // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
16479 {
16480 //var out_length, in_length, dcode;
16481
16482 s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 0xff;
16483 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
16484
16485 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
16486 s.last_lit++;
16487
16488 if (dist === 0) {
16489 /* lc is the unmatched char */
16490 s.dyn_ltree[lc * 2]/*.Freq*/++;
16491 } else {
16492 s.matches++;
16493 /* Here, lc is the match length - MIN_MATCH */
16494 dist--; /* dist = match distance - 1 */
16495 //Assert((ush)dist < (ush)MAX_DIST(s) &&
16496 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
16497 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
16498
16499 s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
16500 s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
16501 }
16502
16503 // (!) This block is disabled in zlib defaults,
16504 // don't enable it for binary compatibility
16505
16506 //#ifdef TRUNCATE_BLOCK
16507 // /* Try to guess if it is profitable to stop the current block here */
16508 // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
16509 // /* Compute an upper bound for the compressed length */
16510 // out_length = s.last_lit*8;
16511 // in_length = s.strstart - s.block_start;
16512 //
16513 // for (dcode = 0; dcode < D_CODES; dcode++) {
16514 // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
16515 // }
16516 // out_length >>>= 3;
16517 // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
16518 // // s->last_lit, in_length, out_length,
16519 // // 100L - out_length*100L/in_length));
16520 // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
16521 // return true;
16522 // }
16523 // }
16524 //#endif
16525
16526 return s.last_lit === s.lit_bufsize - 1;
16527 /* We avoid equality with lit_bufsize because of wraparound at 64K
16528 * on 16 bit machines and because stored blocks are restricted to
16529 * 64K-1 bytes.
16530 */
16531 }
16532
16533 // Note: adler32 takes 12% for level 0 and 2% for level 6.
16534 // It isn't worth it to make additional optimizations as in original.
16535 // Small size is preferable.
16536
16537 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
16538 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
16539 //
16540 // This software is provided 'as-is', without any express or implied
16541 // warranty. In no event will the authors be held liable for any damages
16542 // arising from the use of this software.
16543 //
16544 // Permission is granted to anyone to use this software for any purpose,
16545 // including commercial applications, and to alter it and redistribute it
16546 // freely, subject to the following restrictions:
16547 //
16548 // 1. The origin of this software must not be misrepresented; you must not
16549 // claim that you wrote the original software. If you use this software
16550 // in a product, an acknowledgment in the product documentation would be
16551 // appreciated but is not required.
16552 // 2. Altered source versions must be plainly marked as such, and must not be
16553 // misrepresented as being the original software.
16554 // 3. This notice may not be removed or altered from any source distribution.
16555
16556 function adler32(adler, buf, len, pos) {
16557 let s1 = adler & 0xffff |0,
16558 s2 = adler >>> 16 & 0xffff |0,
16559 n = 0;
16560
16561 while (len !== 0) {
16562 // Set limit ~ twice less than 5552, to keep
16563 // s2 in 31-bits, because we force signed ints.
16564 // in other case %= will fail.
16565 n = len > 2000 ? 2000 : len;
16566 len -= n;
16567
16568 do {
16569 s1 = s1 + buf[pos++] |0;
16570 s2 = s2 + s1 |0;
16571 } while (--n);
16572
16573 s1 %= 65521;
16574 s2 %= 65521;
16575 }
16576
16577 return s1 | s2 << 16 |0;
16578 }
16579
16580 // Note: we can't get significant speed boost here.
16581 // So write code to minimize size - no pregenerated tables
16582 // and array tools dependencies.
16583
16584 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
16585 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
16586 //
16587 // This software is provided 'as-is', without any express or implied
16588 // warranty. In no event will the authors be held liable for any damages
16589 // arising from the use of this software.
16590 //
16591 // Permission is granted to anyone to use this software for any purpose,
16592 // including commercial applications, and to alter it and redistribute it
16593 // freely, subject to the following restrictions:
16594 //
16595 // 1. The origin of this software must not be misrepresented; you must not
16596 // claim that you wrote the original software. If you use this software
16597 // in a product, an acknowledgment in the product documentation would be
16598 // appreciated but is not required.
16599 // 2. Altered source versions must be plainly marked as such, and must not be
16600 // misrepresented as being the original software.
16601 // 3. This notice may not be removed or altered from any source distribution.
16602
16603 // Use ordinary array, since untyped makes no boost here
16604 function makeTable() {
16605 let c;
16606 const table = [];
16607
16608 for (let n = 0; n < 256; n++) {
16609 c = n;
16610 for (let k = 0; k < 8; k++) {
16611 c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
16612 }
16613 table[n] = c;
16614 }
16615
16616 return table;
16617 }
16618
16619 // Create table on load. Just 255 signed longs. Not a problem.
16620 const crcTable = makeTable();
16621
16622
16623 function crc32(crc, buf, len, pos) {
16624 const t = crcTable,
16625 end = pos + len;
16626
16627 crc ^= -1;
16628
16629 for (let i = pos; i < end; i++) {
16630 crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF];
16631 }
16632
16633 return crc ^ -1; // >>> 0;
16634 }
16635
16636 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
16637 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
16638 //
16639 // This software is provided 'as-is', without any express or implied
16640 // warranty. In no event will the authors be held liable for any damages
16641 // arising from the use of this software.
16642 //
16643 // Permission is granted to anyone to use this software for any purpose,
16644 // including commercial applications, and to alter it and redistribute it
16645 // freely, subject to the following restrictions:
16646 //
16647 // 1. The origin of this software must not be misrepresented; you must not
16648 // claim that you wrote the original software. If you use this software
16649 // in a product, an acknowledgment in the product documentation would be
16650 // appreciated but is not required.
16651 // 2. Altered source versions must be plainly marked as such, and must not be
16652 // misrepresented as being the original software.
16653 // 3. This notice may not be removed or altered from any source distribution.
16654
16655 var msg = {
16656 2: "need dictionary", /* Z_NEED_DICT 2 */
16657 1: "stream end", /* Z_STREAM_END 1 */
16658 0: "", /* Z_OK 0 */
16659 "-1": "file error", /* Z_ERRNO (-1) */
16660 "-2": "stream error", /* Z_STREAM_ERROR (-2) */
16661 "-3": "data error", /* Z_DATA_ERROR (-3) */
16662 "-4": "insufficient memory", /* Z_MEM_ERROR (-4) */
16663 "-5": "buffer error", /* Z_BUF_ERROR (-5) */
16664 "-6": "incompatible version" /* Z_VERSION_ERROR (-6) */
16665 };
16666
16667 /*============================================================================*/
16668
16669
16670 const MAX_MEM_LEVEL = 9;
16671
16672
16673 const LENGTH_CODES$1 = 29;
16674 /* number of length codes, not counting the special END_BLOCK code */
16675 const LITERALS$1 = 256;
16676 /* number of literal bytes 0..255 */
16677 const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;
16678 /* number of Literal or Length codes, including the END_BLOCK code */
16679 const D_CODES$1 = 30;
16680 /* number of distance codes */
16681 const BL_CODES$1 = 19;
16682 /* number of codes used to transfer the bit lengths */
16683 const HEAP_SIZE$1 = 2 * L_CODES$1 + 1;
16684 /* maximum heap size */
16685 const MAX_BITS$1 = 15;
16686 /* All codes must not exceed MAX_BITS bits */
16687
16688 const MIN_MATCH$1 = 3;
16689 const MAX_MATCH$1 = 258;
16690 const MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1);
16691
16692 const PRESET_DICT = 0x20;
16693
16694 const INIT_STATE = 42;
16695 const EXTRA_STATE = 69;
16696 const NAME_STATE = 73;
16697 const COMMENT_STATE = 91;
16698 const HCRC_STATE = 103;
16699 const BUSY_STATE = 113;
16700 const FINISH_STATE = 666;
16701
16702 const BS_NEED_MORE = 1; /* block not completed, need more input or more output */
16703 const BS_BLOCK_DONE = 2; /* block flush performed */
16704 const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
16705 const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
16706
16707 const OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
16708
16709 function err(strm, errorCode) {
16710 strm.msg = msg[errorCode];
16711 return errorCode;
16712 }
16713
16714 function rank(f) {
16715 return ((f) << 1) - ((f) > 4 ? 9 : 0);
16716 }
16717
16718 function zero$2(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }
16719
16720
16721 /* =========================================================================
16722 * Flush as much pending output as possible. All deflate() output goes
16723 * through this function so some applications may wish to modify it
16724 * to avoid allocating a large strm->output buffer and copying into it.
16725 * (See also read_buf()).
16726 */
16727 function flush_pending(strm) {
16728 const s = strm.state;
16729
16730 //_tr_flush_bits(s);
16731 let len = s.pending;
16732 if (len > strm.avail_out) {
16733 len = strm.avail_out;
16734 }
16735 if (len === 0) { return; }
16736
16737 arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
16738 strm.next_out += len;
16739 s.pending_out += len;
16740 strm.total_out += len;
16741 strm.avail_out -= len;
16742 s.pending -= len;
16743 if (s.pending === 0) {
16744 s.pending_out = 0;
16745 }
16746 }
16747
16748
16749 function flush_block_only(s, last) {
16750 _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
16751 s.block_start = s.strstart;
16752 flush_pending(s.strm);
16753 }
16754
16755
16756 function put_byte(s, b) {
16757 s.pending_buf[s.pending++] = b;
16758 }
16759
16760
16761 /* =========================================================================
16762 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
16763 * IN assertion: the stream state is correct and there is enough room in
16764 * pending_buf.
16765 */
16766 function putShortMSB(s, b) {
16767 // put_byte(s, (Byte)(b >> 8));
16768 // put_byte(s, (Byte)(b & 0xff));
16769 s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
16770 s.pending_buf[s.pending++] = b & 0xff;
16771 }
16772
16773
16774 /* ===========================================================================
16775 * Read a new buffer from the current input stream, update the adler32
16776 * and total number of bytes read. All deflate() input goes through
16777 * this function so some applications may wish to modify it to avoid
16778 * allocating a large strm->input buffer and copying from it.
16779 * (See also flush_pending()).
16780 */
16781 function read_buf(strm, buf, start, size) {
16782 let len = strm.avail_in;
16783
16784 if (len > size) { len = size; }
16785 if (len === 0) { return 0; }
16786
16787 strm.avail_in -= len;
16788
16789 // zmemcpy(buf, strm->next_in, len);
16790 arraySet(buf, strm.input, strm.next_in, len, start);
16791 if (strm.state.wrap === 1) {
16792 strm.adler = adler32(strm.adler, buf, len, start);
16793 }
16794
16795 else if (strm.state.wrap === 2) {
16796 strm.adler = crc32(strm.adler, buf, len, start);
16797 }
16798
16799 strm.next_in += len;
16800 strm.total_in += len;
16801
16802 return len;
16803 }
16804
16805
16806 /* ===========================================================================
16807 * Set match_start to the longest match starting at the given string and
16808 * return its length. Matches shorter or equal to prev_length are discarded,
16809 * in which case the result is equal to prev_length and match_start is
16810 * garbage.
16811 * IN assertions: cur_match is the head of the hash chain for the current
16812 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
16813 * OUT assertion: the match length is not greater than s->lookahead.
16814 */
16815 function longest_match(s, cur_match) {
16816 let chain_length = s.max_chain_length; /* max hash chain length */
16817 let scan = s.strstart; /* current string */
16818 let match; /* matched string */
16819 let len; /* length of current match */
16820 let best_len = s.prev_length; /* best match length so far */
16821 let nice_match = s.nice_match; /* stop if match long enough */
16822 const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
16823 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
16824
16825 const _win = s.window; // shortcut
16826
16827 const wmask = s.w_mask;
16828 const prev = s.prev;
16829
16830 /* Stop when cur_match becomes <= limit. To simplify the code,
16831 * we prevent matches with the string of window index 0.
16832 */
16833
16834 const strend = s.strstart + MAX_MATCH$1;
16835 let scan_end1 = _win[scan + best_len - 1];
16836 let scan_end = _win[scan + best_len];
16837
16838 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
16839 * It is easy to get rid of this optimization if necessary.
16840 */
16841 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
16842
16843 /* Do not waste too much time if we already have a good match: */
16844 if (s.prev_length >= s.good_match) {
16845 chain_length >>= 2;
16846 }
16847 /* Do not look for matches beyond the end of the input. This is necessary
16848 * to make deflate deterministic.
16849 */
16850 if (nice_match > s.lookahead) { nice_match = s.lookahead; }
16851
16852 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
16853
16854 do {
16855 // Assert(cur_match < s->strstart, "no future");
16856 match = cur_match;
16857
16858 /* Skip to next match if the match length cannot increase
16859 * or if the match length is less than 2. Note that the checks below
16860 * for insufficient lookahead only occur occasionally for performance
16861 * reasons. Therefore uninitialized memory will be accessed, and
16862 * conditional jumps will be made that depend on those values.
16863 * However the length of the match is limited to the lookahead, so
16864 * the output of deflate is not affected by the uninitialized values.
16865 */
16866
16867 if (_win[match + best_len] !== scan_end ||
16868 _win[match + best_len - 1] !== scan_end1 ||
16869 _win[match] !== _win[scan] ||
16870 _win[++match] !== _win[scan + 1]) {
16871 continue;
16872 }
16873
16874 /* The check at best_len-1 can be removed because it will be made
16875 * again later. (This heuristic is not always a win.)
16876 * It is not necessary to compare scan[2] and match[2] since they
16877 * are always equal when the other bytes match, given that
16878 * the hash keys are equal and that HASH_BITS >= 8.
16879 */
16880 scan += 2;
16881 match++;
16882 // Assert(*scan == *match, "match[2]?");
16883
16884 /* We check for insufficient lookahead only every 8th comparison;
16885 * the 256th check will be made at strstart+258.
16886 */
16887 do {
16888 /*jshint noempty:false*/
16889 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
16890 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
16891 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
16892 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
16893 scan < strend);
16894
16895 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
16896
16897 len = MAX_MATCH$1 - (strend - scan);
16898 scan = strend - MAX_MATCH$1;
16899
16900 if (len > best_len) {
16901 s.match_start = cur_match;
16902 best_len = len;
16903 if (len >= nice_match) {
16904 break;
16905 }
16906 scan_end1 = _win[scan + best_len - 1];
16907 scan_end = _win[scan + best_len];
16908 }
16909 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
16910
16911 if (best_len <= s.lookahead) {
16912 return best_len;
16913 }
16914 return s.lookahead;
16915 }
16916
16917
16918 /* ===========================================================================
16919 * Fill the window when the lookahead becomes insufficient.
16920 * Updates strstart and lookahead.
16921 *
16922 * IN assertion: lookahead < MIN_LOOKAHEAD
16923 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
16924 * At least one byte has been read, or avail_in == 0; reads are
16925 * performed for at least two bytes (required for the zip translate_eol
16926 * option -- not supported here).
16927 */
16928 function fill_window(s) {
16929 const _w_size = s.w_size;
16930 let p, n, m, more, str;
16931
16932 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
16933
16934 do {
16935 more = s.window_size - s.lookahead - s.strstart;
16936
16937 // JS ints have 32 bit, block below not needed
16938 /* Deal with !@#$% 64K limit: */
16939 //if (sizeof(int) <= 2) {
16940 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
16941 // more = wsize;
16942 //
16943 // } else if (more == (unsigned)(-1)) {
16944 // /* Very unlikely, but possible on 16 bit machine if
16945 // * strstart == 0 && lookahead == 1 (input done a byte at time)
16946 // */
16947 // more--;
16948 // }
16949 //}
16950
16951
16952 /* If the window is almost full and there is insufficient lookahead,
16953 * move the upper half to the lower one to make room in the upper half.
16954 */
16955 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
16956
16957 arraySet(s.window, s.window, _w_size, _w_size, 0);
16958 s.match_start -= _w_size;
16959 s.strstart -= _w_size;
16960 /* we now have strstart >= MAX_DIST */
16961 s.block_start -= _w_size;
16962
16963 /* Slide the hash table (could be avoided with 32 bit values
16964 at the expense of memory usage). We slide even when level == 0
16965 to keep the hash table consistent if we switch back to level > 0
16966 later. (Using level 0 permanently is not an optimal usage of
16967 zlib, so we don't care about this pathological case.)
16968 */
16969
16970 n = s.hash_size;
16971 p = n;
16972 do {
16973 m = s.head[--p];
16974 s.head[p] = (m >= _w_size ? m - _w_size : 0);
16975 } while (--n);
16976
16977 n = _w_size;
16978 p = n;
16979 do {
16980 m = s.prev[--p];
16981 s.prev[p] = (m >= _w_size ? m - _w_size : 0);
16982 /* If n is not on any hash chain, prev[n] is garbage but
16983 * its value will never be used.
16984 */
16985 } while (--n);
16986
16987 more += _w_size;
16988 }
16989 if (s.strm.avail_in === 0) {
16990 break;
16991 }
16992
16993 /* If there was no sliding:
16994 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
16995 * more == window_size - lookahead - strstart
16996 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
16997 * => more >= window_size - 2*WSIZE + 2
16998 * In the BIG_MEM or MMAP case (not yet supported),
16999 * window_size == input_size + MIN_LOOKAHEAD &&
17000 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
17001 * Otherwise, window_size == 2*WSIZE so more >= 2.
17002 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
17003 */
17004 //Assert(more >= 2, "more < 2");
17005 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
17006 s.lookahead += n;
17007
17008 /* Initialize the hash value now that we have some input: */
17009 if (s.lookahead + s.insert >= MIN_MATCH$1) {
17010 str = s.strstart - s.insert;
17011 s.ins_h = s.window[str];
17012
17013 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
17014 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
17015 //#if MIN_MATCH != 3
17016 // Call update_hash() MIN_MATCH-3 more times
17017 //#endif
17018 while (s.insert) {
17019 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
17020 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;
17021
17022 s.prev[str & s.w_mask] = s.head[s.ins_h];
17023 s.head[s.ins_h] = str;
17024 str++;
17025 s.insert--;
17026 if (s.lookahead + s.insert < MIN_MATCH$1) {
17027 break;
17028 }
17029 }
17030 }
17031 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
17032 * but this is not important since only literal bytes will be emitted.
17033 */
17034
17035 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
17036
17037 /* If the WIN_INIT bytes after the end of the current data have never been
17038 * written, then zero those bytes in order to avoid memory check reports of
17039 * the use of uninitialized (or uninitialised as Julian writes) bytes by
17040 * the longest match routines. Update the high water mark for the next
17041 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
17042 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
17043 */
17044 // if (s.high_water < s.window_size) {
17045 // var curr = s.strstart + s.lookahead;
17046 // var init = 0;
17047 //
17048 // if (s.high_water < curr) {
17049 // /* Previous high water mark below current data -- zero WIN_INIT
17050 // * bytes or up to end of window, whichever is less.
17051 // */
17052 // init = s.window_size - curr;
17053 // if (init > WIN_INIT)
17054 // init = WIN_INIT;
17055 // zmemzero(s->window + curr, (unsigned)init);
17056 // s->high_water = curr + init;
17057 // }
17058 // else if (s->high_water < (ulg)curr + WIN_INIT) {
17059 // /* High water mark at or above current data, but below current data
17060 // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
17061 // * to end of window, whichever is less.
17062 // */
17063 // init = (ulg)curr + WIN_INIT - s->high_water;
17064 // if (init > s->window_size - s->high_water)
17065 // init = s->window_size - s->high_water;
17066 // zmemzero(s->window + s->high_water, (unsigned)init);
17067 // s->high_water += init;
17068 // }
17069 // }
17070 //
17071 // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
17072 // "not enough room for search");
17073 }
17074
17075 /* ===========================================================================
17076 * Copy without compression as much as possible from the input stream, return
17077 * the current block state.
17078 * This function does not insert new strings in the dictionary since
17079 * uncompressible data is probably not useful. This function is used
17080 * only for the level=0 compression option.
17081 * NOTE: this function should be optimized to avoid extra copying from
17082 * window to pending_buf.
17083 */
17084 function deflate_stored(s, flush) {
17085 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
17086 * to pending_buf_size, and each stored block has a 5 byte header:
17087 */
17088 let max_block_size = 0xffff;
17089
17090 if (max_block_size > s.pending_buf_size - 5) {
17091 max_block_size = s.pending_buf_size - 5;
17092 }
17093
17094 /* Copy as much as possible from input to output: */
17095 for (; ;) {
17096 /* Fill the window as much as possible: */
17097 if (s.lookahead <= 1) {
17098
17099 //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
17100 // s->block_start >= (long)s->w_size, "slide too late");
17101 // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
17102 // s.block_start >= s.w_size)) {
17103 // throw new Error("slide too late");
17104 // }
17105
17106 fill_window(s);
17107 if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
17108 return BS_NEED_MORE;
17109 }
17110
17111 if (s.lookahead === 0) {
17112 break;
17113 }
17114 /* flush the current block */
17115 }
17116 //Assert(s->block_start >= 0L, "block gone");
17117 // if (s.block_start < 0) throw new Error("block gone");
17118
17119 s.strstart += s.lookahead;
17120 s.lookahead = 0;
17121
17122 /* Emit a stored block if pending_buf will be full: */
17123 const max_start = s.block_start + max_block_size;
17124
17125 if (s.strstart === 0 || s.strstart >= max_start) {
17126 /* strstart == 0 is possible when wraparound on 16-bit machine */
17127 s.lookahead = s.strstart - max_start;
17128 s.strstart = max_start;
17129 /*** FLUSH_BLOCK(s, 0); ***/
17130 flush_block_only(s, false);
17131 if (s.strm.avail_out === 0) {
17132 return BS_NEED_MORE;
17133 }
17134 /***/
17135
17136
17137 }
17138 /* Flush if we may have to slide, otherwise block_start may become
17139 * negative and the data will be gone:
17140 */
17141 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
17142 /*** FLUSH_BLOCK(s, 0); ***/
17143 flush_block_only(s, false);
17144 if (s.strm.avail_out === 0) {
17145 return BS_NEED_MORE;
17146 }
17147 /***/
17148 }
17149 }
17150
17151 s.insert = 0;
17152
17153 if (flush === Z_FINISH) {
17154 /*** FLUSH_BLOCK(s, 1); ***/
17155 flush_block_only(s, true);
17156 if (s.strm.avail_out === 0) {
17157 return BS_FINISH_STARTED;
17158 }
17159 /***/
17160 return BS_FINISH_DONE;
17161 }
17162
17163 if (s.strstart > s.block_start) {
17164 /*** FLUSH_BLOCK(s, 0); ***/
17165 flush_block_only(s, false);
17166 if (s.strm.avail_out === 0) {
17167 return BS_NEED_MORE;
17168 }
17169 /***/
17170 }
17171
17172 return BS_NEED_MORE;
17173 }
17174
17175 /* ===========================================================================
17176 * Compress as much as possible from the input stream, return the current
17177 * block state.
17178 * This function does not perform lazy evaluation of matches and inserts
17179 * new strings in the dictionary only for unmatched strings or for short
17180 * matches. It is used only for the fast compression options.
17181 */
17182 function deflate_fast(s, flush) {
17183 let hash_head; /* head of the hash chain */
17184 let bflush; /* set if current block must be flushed */
17185
17186 for (; ;) {
17187 /* Make sure that we always have enough lookahead, except
17188 * at the end of the input file. We need MAX_MATCH bytes
17189 * for the next match, plus MIN_MATCH bytes to insert the
17190 * string following the next match.
17191 */
17192 if (s.lookahead < MIN_LOOKAHEAD) {
17193 fill_window(s);
17194 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
17195 return BS_NEED_MORE;
17196 }
17197 if (s.lookahead === 0) {
17198 break; /* flush the current block */
17199 }
17200 }
17201
17202 /* Insert the string window[strstart .. strstart+2] in the
17203 * dictionary, and set hash_head to the head of the hash chain:
17204 */
17205 hash_head = 0/*NIL*/;
17206 if (s.lookahead >= MIN_MATCH$1) {
17207 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
17208 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
17209 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
17210 s.head[s.ins_h] = s.strstart;
17211 /***/
17212 }
17213
17214 /* Find the longest match, discarding those <= prev_length.
17215 * At this point we have always match_length < MIN_MATCH
17216 */
17217 if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
17218 /* To simplify the code, we prevent matches with the string
17219 * of window index 0 (in particular we have to avoid a match
17220 * of the string with itself at the start of the input file).
17221 */
17222 s.match_length = longest_match(s, hash_head);
17223 /* longest_match() sets match_start */
17224 }
17225 if (s.match_length >= MIN_MATCH$1) {
17226 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
17227
17228 /*** _tr_tally_dist(s, s.strstart - s.match_start,
17229 s.match_length - MIN_MATCH, bflush); ***/
17230 bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1);
17231
17232 s.lookahead -= s.match_length;
17233
17234 /* Insert new strings in the hash table only if the match length
17235 * is not too large. This saves time but degrades compression.
17236 */
17237 if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) {
17238 s.match_length--; /* string at strstart already in table */
17239 do {
17240 s.strstart++;
17241 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
17242 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
17243 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
17244 s.head[s.ins_h] = s.strstart;
17245 /***/
17246 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
17247 * always MIN_MATCH bytes ahead.
17248 */
17249 } while (--s.match_length !== 0);
17250 s.strstart++;
17251 } else {
17252 s.strstart += s.match_length;
17253 s.match_length = 0;
17254 s.ins_h = s.window[s.strstart];
17255 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
17256 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
17257
17258 //#if MIN_MATCH != 3
17259 // Call UPDATE_HASH() MIN_MATCH-3 more times
17260 //#endif
17261 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
17262 * matter since it will be recomputed at next deflate call.
17263 */
17264 }
17265 } else {
17266 /* No match, output a literal byte */
17267 //Tracevv((stderr,"%c", s.window[s.strstart]));
17268 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
17269 bflush = _tr_tally(s, 0, s.window[s.strstart]);
17270
17271 s.lookahead--;
17272 s.strstart++;
17273 }
17274 if (bflush) {
17275 /*** FLUSH_BLOCK(s, 0); ***/
17276 flush_block_only(s, false);
17277 if (s.strm.avail_out === 0) {
17278 return BS_NEED_MORE;
17279 }
17280 /***/
17281 }
17282 }
17283 s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1);
17284 if (flush === Z_FINISH) {
17285 /*** FLUSH_BLOCK(s, 1); ***/
17286 flush_block_only(s, true);
17287 if (s.strm.avail_out === 0) {
17288 return BS_FINISH_STARTED;
17289 }
17290 /***/
17291 return BS_FINISH_DONE;
17292 }
17293 if (s.last_lit) {
17294 /*** FLUSH_BLOCK(s, 0); ***/
17295 flush_block_only(s, false);
17296 if (s.strm.avail_out === 0) {
17297 return BS_NEED_MORE;
17298 }
17299 /***/
17300 }
17301 return BS_BLOCK_DONE;
17302 }
17303
17304 /* ===========================================================================
17305 * Same as above, but achieves better compression. We use a lazy
17306 * evaluation for matches: a match is finally adopted only if there is
17307 * no better match at the next window position.
17308 */
17309 function deflate_slow(s, flush) {
17310 let hash_head; /* head of hash chain */
17311 let bflush; /* set if current block must be flushed */
17312
17313 let max_insert;
17314
17315 /* Process the input block. */
17316 for (; ;) {
17317 /* Make sure that we always have enough lookahead, except
17318 * at the end of the input file. We need MAX_MATCH bytes
17319 * for the next match, plus MIN_MATCH bytes to insert the
17320 * string following the next match.
17321 */
17322 if (s.lookahead < MIN_LOOKAHEAD) {
17323 fill_window(s);
17324 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
17325 return BS_NEED_MORE;
17326 }
17327 if (s.lookahead === 0) { break; } /* flush the current block */
17328 }
17329
17330 /* Insert the string window[strstart .. strstart+2] in the
17331 * dictionary, and set hash_head to the head of the hash chain:
17332 */
17333 hash_head = 0/*NIL*/;
17334 if (s.lookahead >= MIN_MATCH$1) {
17335 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
17336 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
17337 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
17338 s.head[s.ins_h] = s.strstart;
17339 /***/
17340 }
17341
17342 /* Find the longest match, discarding those <= prev_length.
17343 */
17344 s.prev_length = s.match_length;
17345 s.prev_match = s.match_start;
17346 s.match_length = MIN_MATCH$1 - 1;
17347
17348 if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
17349 s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
17350 /* To simplify the code, we prevent matches with the string
17351 * of window index 0 (in particular we have to avoid a match
17352 * of the string with itself at the start of the input file).
17353 */
17354 s.match_length = longest_match(s, hash_head);
17355 /* longest_match() sets match_start */
17356
17357 if (s.match_length <= 5 &&
17358 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
17359
17360 /* If prev_match is also MIN_MATCH, match_start is garbage
17361 * but we will ignore the current match anyway.
17362 */
17363 s.match_length = MIN_MATCH$1 - 1;
17364 }
17365 }
17366 /* If there was a match at the previous step and the current
17367 * match is not better, output the previous match:
17368 */
17369 if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) {
17370 max_insert = s.strstart + s.lookahead - MIN_MATCH$1;
17371 /* Do not insert strings in hash table beyond this. */
17372
17373 //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
17374
17375 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
17376 s.prev_length - MIN_MATCH, bflush);***/
17377 bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1);
17378 /* Insert in hash table all strings up to the end of the match.
17379 * strstart-1 and strstart are already inserted. If there is not
17380 * enough lookahead, the last two strings are not inserted in
17381 * the hash table.
17382 */
17383 s.lookahead -= s.prev_length - 1;
17384 s.prev_length -= 2;
17385 do {
17386 if (++s.strstart <= max_insert) {
17387 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
17388 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask;
17389 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
17390 s.head[s.ins_h] = s.strstart;
17391 /***/
17392 }
17393 } while (--s.prev_length !== 0);
17394 s.match_available = 0;
17395 s.match_length = MIN_MATCH$1 - 1;
17396 s.strstart++;
17397
17398 if (bflush) {
17399 /*** FLUSH_BLOCK(s, 0); ***/
17400 flush_block_only(s, false);
17401 if (s.strm.avail_out === 0) {
17402 return BS_NEED_MORE;
17403 }
17404 /***/
17405 }
17406
17407 } else if (s.match_available) {
17408 /* If there was no match at the previous position, output a
17409 * single literal. If there was a match but the current match
17410 * is longer, truncate the previous match to a single literal.
17411 */
17412 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
17413 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
17414 bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
17415
17416 if (bflush) {
17417 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
17418 flush_block_only(s, false);
17419 /***/
17420 }
17421 s.strstart++;
17422 s.lookahead--;
17423 if (s.strm.avail_out === 0) {
17424 return BS_NEED_MORE;
17425 }
17426 } else {
17427 /* There is no previous match to compare with, wait for
17428 * the next step to decide.
17429 */
17430 s.match_available = 1;
17431 s.strstart++;
17432 s.lookahead--;
17433 }
17434 }
17435 //Assert (flush != Z_NO_FLUSH, "no flush?");
17436 if (s.match_available) {
17437 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
17438 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
17439 bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);
17440
17441 s.match_available = 0;
17442 }
17443 s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1;
17444 if (flush === Z_FINISH) {
17445 /*** FLUSH_BLOCK(s, 1); ***/
17446 flush_block_only(s, true);
17447 if (s.strm.avail_out === 0) {
17448 return BS_FINISH_STARTED;
17449 }
17450 /***/
17451 return BS_FINISH_DONE;
17452 }
17453 if (s.last_lit) {
17454 /*** FLUSH_BLOCK(s, 0); ***/
17455 flush_block_only(s, false);
17456 if (s.strm.avail_out === 0) {
17457 return BS_NEED_MORE;
17458 }
17459 /***/
17460 }
17461
17462 return BS_BLOCK_DONE;
17463 }
17464
17465
17466 /* ===========================================================================
17467 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
17468 * one. Do not maintain a hash table. (It will be regenerated if this run of
17469 * deflate switches away from Z_RLE.)
17470 */
17471 function deflate_rle(s, flush) {
17472 let bflush; /* set if current block must be flushed */
17473 let prev; /* byte at distance one to match */
17474 let scan, strend; /* scan goes up to strend for length of run */
17475
17476 const _win = s.window;
17477
17478 for (; ;) {
17479 /* Make sure that we always have enough lookahead, except
17480 * at the end of the input file. We need MAX_MATCH bytes
17481 * for the longest run, plus one for the unrolled loop.
17482 */
17483 if (s.lookahead <= MAX_MATCH$1) {
17484 fill_window(s);
17485 if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) {
17486 return BS_NEED_MORE;
17487 }
17488 if (s.lookahead === 0) { break; } /* flush the current block */
17489 }
17490
17491 /* See how many times the previous byte repeats */
17492 s.match_length = 0;
17493 if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) {
17494 scan = s.strstart - 1;
17495 prev = _win[scan];
17496 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
17497 strend = s.strstart + MAX_MATCH$1;
17498 do {
17499 /*jshint noempty:false*/
17500 } while (prev === _win[++scan] && prev === _win[++scan] &&
17501 prev === _win[++scan] && prev === _win[++scan] &&
17502 prev === _win[++scan] && prev === _win[++scan] &&
17503 prev === _win[++scan] && prev === _win[++scan] &&
17504 scan < strend);
17505 s.match_length = MAX_MATCH$1 - (strend - scan);
17506 if (s.match_length > s.lookahead) {
17507 s.match_length = s.lookahead;
17508 }
17509 }
17510 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
17511 }
17512
17513 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
17514 if (s.match_length >= MIN_MATCH$1) {
17515 //check_match(s, s.strstart, s.strstart - 1, s.match_length);
17516
17517 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
17518 bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH$1);
17519
17520 s.lookahead -= s.match_length;
17521 s.strstart += s.match_length;
17522 s.match_length = 0;
17523 } else {
17524 /* No match, output a literal byte */
17525 //Tracevv((stderr,"%c", s->window[s->strstart]));
17526 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
17527 bflush = _tr_tally(s, 0, s.window[s.strstart]);
17528
17529 s.lookahead--;
17530 s.strstart++;
17531 }
17532 if (bflush) {
17533 /*** FLUSH_BLOCK(s, 0); ***/
17534 flush_block_only(s, false);
17535 if (s.strm.avail_out === 0) {
17536 return BS_NEED_MORE;
17537 }
17538 /***/
17539 }
17540 }
17541 s.insert = 0;
17542 if (flush === Z_FINISH) {
17543 /*** FLUSH_BLOCK(s, 1); ***/
17544 flush_block_only(s, true);
17545 if (s.strm.avail_out === 0) {
17546 return BS_FINISH_STARTED;
17547 }
17548 /***/
17549 return BS_FINISH_DONE;
17550 }
17551 if (s.last_lit) {
17552 /*** FLUSH_BLOCK(s, 0); ***/
17553 flush_block_only(s, false);
17554 if (s.strm.avail_out === 0) {
17555 return BS_NEED_MORE;
17556 }
17557 /***/
17558 }
17559 return BS_BLOCK_DONE;
17560 }
17561
17562 /* ===========================================================================
17563 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
17564 * (It will be regenerated if this run of deflate switches away from Huffman.)
17565 */
17566 function deflate_huff(s, flush) {
17567 let bflush; /* set if current block must be flushed */
17568
17569 for (; ;) {
17570 /* Make sure that we have a literal to write. */
17571 if (s.lookahead === 0) {
17572 fill_window(s);
17573 if (s.lookahead === 0) {
17574 if (flush === Z_NO_FLUSH) {
17575 return BS_NEED_MORE;
17576 }
17577 break; /* flush the current block */
17578 }
17579 }
17580
17581 /* Output a literal byte */
17582 s.match_length = 0;
17583 //Tracevv((stderr,"%c", s->window[s->strstart]));
17584 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
17585 bflush = _tr_tally(s, 0, s.window[s.strstart]);
17586 s.lookahead--;
17587 s.strstart++;
17588 if (bflush) {
17589 /*** FLUSH_BLOCK(s, 0); ***/
17590 flush_block_only(s, false);
17591 if (s.strm.avail_out === 0) {
17592 return BS_NEED_MORE;
17593 }
17594 /***/
17595 }
17596 }
17597 s.insert = 0;
17598 if (flush === Z_FINISH) {
17599 /*** FLUSH_BLOCK(s, 1); ***/
17600 flush_block_only(s, true);
17601 if (s.strm.avail_out === 0) {
17602 return BS_FINISH_STARTED;
17603 }
17604 /***/
17605 return BS_FINISH_DONE;
17606 }
17607 if (s.last_lit) {
17608 /*** FLUSH_BLOCK(s, 0); ***/
17609 flush_block_only(s, false);
17610 if (s.strm.avail_out === 0) {
17611 return BS_NEED_MORE;
17612 }
17613 /***/
17614 }
17615 return BS_BLOCK_DONE;
17616 }
17617
17618 /* Values for max_lazy_match, good_match and max_chain_length, depending on
17619 * the desired pack level (0..9). The values given below have been tuned to
17620 * exclude worst case performance for pathological files. Better values may be
17621 * found for specific files.
17622 */
17623 class Config {
17624 constructor(good_length, max_lazy, nice_length, max_chain, func) {
17625 this.good_length = good_length;
17626 this.max_lazy = max_lazy;
17627 this.nice_length = nice_length;
17628 this.max_chain = max_chain;
17629 this.func = func;
17630 }
17631 }
17632 const configuration_table = [
17633 /* good lazy nice chain */
17634 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
17635 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
17636 new Config(4, 5, 16, 8, deflate_fast), /* 2 */
17637 new Config(4, 6, 32, 32, deflate_fast), /* 3 */
17638
17639 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
17640 new Config(8, 16, 32, 32, deflate_slow), /* 5 */
17641 new Config(8, 16, 128, 128, deflate_slow), /* 6 */
17642 new Config(8, 32, 128, 256, deflate_slow), /* 7 */
17643 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
17644 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
17645 ];
17646
17647
17648 /* ===========================================================================
17649 * Initialize the "longest match" routines for a new zlib stream
17650 */
17651 function lm_init(s) {
17652 s.window_size = 2 * s.w_size;
17653
17654 /*** CLEAR_HASH(s); ***/
17655 zero$2(s.head); // Fill with NIL (= 0);
17656
17657 /* Set the default configuration parameters:
17658 */
17659 s.max_lazy_match = configuration_table[s.level].max_lazy;
17660 s.good_match = configuration_table[s.level].good_length;
17661 s.nice_match = configuration_table[s.level].nice_length;
17662 s.max_chain_length = configuration_table[s.level].max_chain;
17663
17664 s.strstart = 0;
17665 s.block_start = 0;
17666 s.lookahead = 0;
17667 s.insert = 0;
17668 s.match_length = s.prev_length = MIN_MATCH$1 - 1;
17669 s.match_available = 0;
17670 s.ins_h = 0;
17671 }
17672
17673 class DeflateState {
17674 constructor() {
17675 this.strm = null; /* pointer back to this zlib stream */
17676 this.status = 0; /* as the name implies */
17677 this.pending_buf = null; /* output still pending */
17678 this.pending_buf_size = 0; /* size of pending_buf */
17679 this.pending_out = 0; /* next pending byte to output to the stream */
17680 this.pending = 0; /* nb of bytes in the pending buffer */
17681 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
17682 this.gzhead = null; /* gzip header information to write */
17683 this.gzindex = 0; /* where in extra, name, or comment */
17684 this.method = Z_DEFLATED; /* can only be DEFLATED */
17685 this.last_flush = -1; /* value of flush param for previous deflate call */
17686
17687 this.w_size = 0; /* LZ77 window size (32K by default) */
17688 this.w_bits = 0; /* log2(w_size) (8..16) */
17689 this.w_mask = 0; /* w_size - 1 */
17690
17691 this.window = null;
17692 /* Sliding window. Input bytes are read into the second half of the window,
17693 * and move to the first half later to keep a dictionary of at least wSize
17694 * bytes. With this organization, matches are limited to a distance of
17695 * wSize-MAX_MATCH bytes, but this ensures that IO is always
17696 * performed with a length multiple of the block size.
17697 */
17698
17699 this.window_size = 0;
17700 /* Actual size of window: 2*wSize, except when the user input buffer
17701 * is directly used as sliding window.
17702 */
17703
17704 this.prev = null;
17705 /* Link to older string with same hash index. To limit the size of this
17706 * array to 64K, this link is maintained only for the last 32K strings.
17707 * An index in this array is thus a window index modulo 32K.
17708 */
17709
17710 this.head = null; /* Heads of the hash chains or NIL. */
17711
17712 this.ins_h = 0; /* hash index of string to be inserted */
17713 this.hash_size = 0; /* number of elements in hash table */
17714 this.hash_bits = 0; /* log2(hash_size) */
17715 this.hash_mask = 0; /* hash_size-1 */
17716
17717 this.hash_shift = 0;
17718 /* Number of bits by which ins_h must be shifted at each input
17719 * step. It must be such that after MIN_MATCH steps, the oldest
17720 * byte no longer takes part in the hash key, that is:
17721 * hash_shift * MIN_MATCH >= hash_bits
17722 */
17723
17724 this.block_start = 0;
17725 /* Window position at the beginning of the current output block. Gets
17726 * negative when the window is moved backwards.
17727 */
17728
17729 this.match_length = 0; /* length of best match */
17730 this.prev_match = 0; /* previous match */
17731 this.match_available = 0; /* set if previous match exists */
17732 this.strstart = 0; /* start of string to insert */
17733 this.match_start = 0; /* start of matching string */
17734 this.lookahead = 0; /* number of valid bytes ahead in window */
17735
17736 this.prev_length = 0;
17737 /* Length of the best match at previous step. Matches not greater than this
17738 * are discarded. This is used in the lazy match evaluation.
17739 */
17740
17741 this.max_chain_length = 0;
17742 /* To speed up deflation, hash chains are never searched beyond this
17743 * length. A higher limit improves compression ratio but degrades the
17744 * speed.
17745 */
17746
17747 this.max_lazy_match = 0;
17748 /* Attempt to find a better match only when the current match is strictly
17749 * smaller than this value. This mechanism is used only for compression
17750 * levels >= 4.
17751 */
17752 // That's alias to max_lazy_match, don't use directly
17753 //this.max_insert_length = 0;
17754 /* Insert new strings in the hash table only if the match length is not
17755 * greater than this length. This saves time but degrades compression.
17756 * max_insert_length is used only for compression levels <= 3.
17757 */
17758
17759 this.level = 0; /* compression level (1..9) */
17760 this.strategy = 0; /* favor or force Huffman coding*/
17761
17762 this.good_match = 0;
17763 /* Use a faster search when the previous match is longer than this */
17764
17765 this.nice_match = 0; /* Stop searching when current match exceeds this */
17766
17767 /* used by trees.c: */
17768
17769 /* Didn't use ct_data typedef below to suppress compiler warning */
17770
17771 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
17772 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
17773 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
17774
17775 // Use flat array of DOUBLE size, with interleaved fata,
17776 // because JS does not support effective
17777 this.dyn_ltree = new Buf16(HEAP_SIZE$1 * 2);
17778 this.dyn_dtree = new Buf16((2 * D_CODES$1 + 1) * 2);
17779 this.bl_tree = new Buf16((2 * BL_CODES$1 + 1) * 2);
17780 zero$2(this.dyn_ltree);
17781 zero$2(this.dyn_dtree);
17782 zero$2(this.bl_tree);
17783
17784 this.l_desc = null; /* desc. for literal tree */
17785 this.d_desc = null; /* desc. for distance tree */
17786 this.bl_desc = null; /* desc. for bit length tree */
17787
17788 //ush bl_count[MAX_BITS+1];
17789 this.bl_count = new Buf16(MAX_BITS$1 + 1);
17790 /* number of codes at each bit length for an optimal tree */
17791
17792 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
17793 this.heap = new Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */
17794 zero$2(this.heap);
17795
17796 this.heap_len = 0; /* number of elements in the heap */
17797 this.heap_max = 0; /* element of largest frequency */
17798 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
17799 * The same heap array is used to build all trees.
17800 */
17801
17802 this.depth = new Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1];
17803 zero$2(this.depth);
17804 /* Depth of each subtree used as tie breaker for trees of equal frequency
17805 */
17806
17807 this.l_buf = 0; /* buffer index for literals or lengths */
17808
17809 this.lit_bufsize = 0;
17810 /* Size of match buffer for literals/lengths. There are 4 reasons for
17811 * limiting lit_bufsize to 64K:
17812 * - frequencies can be kept in 16 bit counters
17813 * - if compression is not successful for the first block, all input
17814 * data is still in the window so we can still emit a stored block even
17815 * when input comes from standard input. (This can also be done for
17816 * all blocks if lit_bufsize is not greater than 32K.)
17817 * - if compression is not successful for a file smaller than 64K, we can
17818 * even emit a stored file instead of a stored block (saving 5 bytes).
17819 * This is applicable only for zip (not gzip or zlib).
17820 * - creating new Huffman trees less frequently may not provide fast
17821 * adaptation to changes in the input data statistics. (Take for
17822 * example a binary file with poorly compressible code followed by
17823 * a highly compressible string table.) Smaller buffer sizes give
17824 * fast adaptation but have of course the overhead of transmitting
17825 * trees more frequently.
17826 * - I can't count above 4
17827 */
17828
17829 this.last_lit = 0; /* running index in l_buf */
17830
17831 this.d_buf = 0;
17832 /* Buffer index for distances. To simplify the code, d_buf and l_buf have
17833 * the same number of elements. To use different lengths, an extra flag
17834 * array would be necessary.
17835 */
17836
17837 this.opt_len = 0; /* bit length of current block with optimal trees */
17838 this.static_len = 0; /* bit length of current block with static trees */
17839 this.matches = 0; /* number of string matches in current block */
17840 this.insert = 0; /* bytes at end of window left to insert */
17841
17842
17843 this.bi_buf = 0;
17844 /* Output buffer. bits are inserted starting at the bottom (least
17845 * significant bits).
17846 */
17847 this.bi_valid = 0;
17848 /* Number of valid bits in bi_buf. All bits above the last valid bit
17849 * are always zero.
17850 */
17851
17852 // Used for window memory init. We safely ignore it for JS. That makes
17853 // sense only for pointers and memory check tools.
17854 //this.high_water = 0;
17855 /* High water mark offset in window for initialized bytes -- bytes above
17856 * this are set to zero in order to avoid memory check warnings when
17857 * longest match routines access bytes past the input. This is then
17858 * updated to the new high water mark.
17859 */
17860 }
17861 }
17862
17863 function deflateResetKeep(strm) {
17864 let s;
17865
17866 if (!strm || !strm.state) {
17867 return err(strm, Z_STREAM_ERROR);
17868 }
17869
17870 strm.total_in = strm.total_out = 0;
17871 strm.data_type = Z_UNKNOWN;
17872
17873 s = strm.state;
17874 s.pending = 0;
17875 s.pending_out = 0;
17876
17877 if (s.wrap < 0) {
17878 s.wrap = -s.wrap;
17879 /* was made negative by deflate(..., Z_FINISH); */
17880 }
17881 s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
17882 strm.adler = (s.wrap === 2) ?
17883 0 // crc32(0, Z_NULL, 0)
17884 :
17885 1; // adler32(0, Z_NULL, 0)
17886 s.last_flush = Z_NO_FLUSH;
17887 _tr_init(s);
17888 return Z_OK;
17889 }
17890
17891
17892 function deflateReset(strm) {
17893 const ret = deflateResetKeep(strm);
17894 if (ret === Z_OK) {
17895 lm_init(strm.state);
17896 }
17897 return ret;
17898 }
17899
17900
17901 function deflateSetHeader(strm, head) {
17902 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
17903 if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
17904 strm.state.gzhead = head;
17905 return Z_OK;
17906 }
17907
17908
17909 function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
17910 if (!strm) { // === Z_NULL
17911 return Z_STREAM_ERROR;
17912 }
17913 let wrap = 1;
17914
17915 if (level === Z_DEFAULT_COMPRESSION) {
17916 level = 6;
17917 }
17918
17919 if (windowBits < 0) { /* suppress zlib wrapper */
17920 wrap = 0;
17921 windowBits = -windowBits;
17922 }
17923
17924 else if (windowBits > 15) {
17925 wrap = 2; /* write gzip wrapper instead */
17926 windowBits -= 16;
17927 }
17928
17929
17930 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
17931 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
17932 strategy < 0 || strategy > Z_FIXED) {
17933 return err(strm, Z_STREAM_ERROR);
17934 }
17935
17936
17937 if (windowBits === 8) {
17938 windowBits = 9;
17939 }
17940 /* until 256-byte window bug fixed */
17941
17942 const s = new DeflateState();
17943
17944 strm.state = s;
17945 s.strm = strm;
17946
17947 s.wrap = wrap;
17948 s.gzhead = null;
17949 s.w_bits = windowBits;
17950 s.w_size = 1 << s.w_bits;
17951 s.w_mask = s.w_size - 1;
17952
17953 s.hash_bits = memLevel + 7;
17954 s.hash_size = 1 << s.hash_bits;
17955 s.hash_mask = s.hash_size - 1;
17956 s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1);
17957 s.window = new Buf8(s.w_size * 2);
17958 s.head = new Buf16(s.hash_size);
17959 s.prev = new Buf16(s.w_size);
17960
17961 // Don't need mem init magic for JS.
17962 //s.high_water = 0; /* nothing written to s->window yet */
17963
17964 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
17965
17966 s.pending_buf_size = s.lit_bufsize * 4;
17967
17968 //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
17969 //s->pending_buf = (uchf *) overlay;
17970 s.pending_buf = new Buf8(s.pending_buf_size);
17971
17972 // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
17973 //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
17974 s.d_buf = 1 * s.lit_bufsize;
17975
17976 //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
17977 s.l_buf = (1 + 2) * s.lit_bufsize;
17978
17979 s.level = level;
17980 s.strategy = strategy;
17981 s.method = method;
17982
17983 return deflateReset(strm);
17984 }
17985
17986
17987 function deflate(strm, flush) {
17988 let old_flush, s;
17989 let beg, val; // for gzip header write only
17990
17991 if (!strm || !strm.state ||
17992 flush > Z_BLOCK || flush < 0) {
17993 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
17994 }
17995
17996 s = strm.state;
17997
17998 if (!strm.output ||
17999 (!strm.input && strm.avail_in !== 0) ||
18000 (s.status === FINISH_STATE && flush !== Z_FINISH)) {
18001 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
18002 }
18003
18004 s.strm = strm; /* just in case */
18005 old_flush = s.last_flush;
18006 s.last_flush = flush;
18007
18008 /* Write the header */
18009 if (s.status === INIT_STATE) {
18010
18011 if (s.wrap === 2) { // GZIP header
18012 strm.adler = 0; //crc32(0L, Z_NULL, 0);
18013 put_byte(s, 31);
18014 put_byte(s, 139);
18015 put_byte(s, 8);
18016 if (!s.gzhead) { // s->gzhead == Z_NULL
18017 put_byte(s, 0);
18018 put_byte(s, 0);
18019 put_byte(s, 0);
18020 put_byte(s, 0);
18021 put_byte(s, 0);
18022 put_byte(s, s.level === 9 ? 2 :
18023 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
18024 4 : 0));
18025 put_byte(s, OS_CODE);
18026 s.status = BUSY_STATE;
18027 }
18028 else {
18029 put_byte(s, (s.gzhead.text ? 1 : 0) +
18030 (s.gzhead.hcrc ? 2 : 0) +
18031 (!s.gzhead.extra ? 0 : 4) +
18032 (!s.gzhead.name ? 0 : 8) +
18033 (!s.gzhead.comment ? 0 : 16)
18034 );
18035 put_byte(s, s.gzhead.time & 0xff);
18036 put_byte(s, (s.gzhead.time >> 8) & 0xff);
18037 put_byte(s, (s.gzhead.time >> 16) & 0xff);
18038 put_byte(s, (s.gzhead.time >> 24) & 0xff);
18039 put_byte(s, s.level === 9 ? 2 :
18040 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
18041 4 : 0));
18042 put_byte(s, s.gzhead.os & 0xff);
18043 if (s.gzhead.extra && s.gzhead.extra.length) {
18044 put_byte(s, s.gzhead.extra.length & 0xff);
18045 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
18046 }
18047 if (s.gzhead.hcrc) {
18048 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
18049 }
18050 s.gzindex = 0;
18051 s.status = EXTRA_STATE;
18052 }
18053 }
18054 else // DEFLATE header
18055 {
18056 let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
18057 let level_flags = -1;
18058
18059 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
18060 level_flags = 0;
18061 } else if (s.level < 6) {
18062 level_flags = 1;
18063 } else if (s.level === 6) {
18064 level_flags = 2;
18065 } else {
18066 level_flags = 3;
18067 }
18068 header |= (level_flags << 6);
18069 if (s.strstart !== 0) { header |= PRESET_DICT; }
18070 header += 31 - (header % 31);
18071
18072 s.status = BUSY_STATE;
18073 putShortMSB(s, header);
18074
18075 /* Save the adler32 of the preset dictionary: */
18076 if (s.strstart !== 0) {
18077 putShortMSB(s, strm.adler >>> 16);
18078 putShortMSB(s, strm.adler & 0xffff);
18079 }
18080 strm.adler = 1; // adler32(0L, Z_NULL, 0);
18081 }
18082 }
18083
18084 //#ifdef GZIP
18085 if (s.status === EXTRA_STATE) {
18086 if (s.gzhead.extra/* != Z_NULL*/) {
18087 beg = s.pending; /* start of bytes to update crc */
18088
18089 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
18090 if (s.pending === s.pending_buf_size) {
18091 if (s.gzhead.hcrc && s.pending > beg) {
18092 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18093 }
18094 flush_pending(strm);
18095 beg = s.pending;
18096 if (s.pending === s.pending_buf_size) {
18097 break;
18098 }
18099 }
18100 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
18101 s.gzindex++;
18102 }
18103 if (s.gzhead.hcrc && s.pending > beg) {
18104 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18105 }
18106 if (s.gzindex === s.gzhead.extra.length) {
18107 s.gzindex = 0;
18108 s.status = NAME_STATE;
18109 }
18110 }
18111 else {
18112 s.status = NAME_STATE;
18113 }
18114 }
18115 if (s.status === NAME_STATE) {
18116 if (s.gzhead.name/* != Z_NULL*/) {
18117 beg = s.pending; /* start of bytes to update crc */
18118 //int val;
18119
18120 do {
18121 if (s.pending === s.pending_buf_size) {
18122 if (s.gzhead.hcrc && s.pending > beg) {
18123 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18124 }
18125 flush_pending(strm);
18126 beg = s.pending;
18127 if (s.pending === s.pending_buf_size) {
18128 val = 1;
18129 break;
18130 }
18131 }
18132 // JS specific: little magic to add zero terminator to end of string
18133 if (s.gzindex < s.gzhead.name.length) {
18134 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
18135 } else {
18136 val = 0;
18137 }
18138 put_byte(s, val);
18139 } while (val !== 0);
18140
18141 if (s.gzhead.hcrc && s.pending > beg) {
18142 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18143 }
18144 if (val === 0) {
18145 s.gzindex = 0;
18146 s.status = COMMENT_STATE;
18147 }
18148 }
18149 else {
18150 s.status = COMMENT_STATE;
18151 }
18152 }
18153 if (s.status === COMMENT_STATE) {
18154 if (s.gzhead.comment/* != Z_NULL*/) {
18155 beg = s.pending; /* start of bytes to update crc */
18156 //int val;
18157
18158 do {
18159 if (s.pending === s.pending_buf_size) {
18160 if (s.gzhead.hcrc && s.pending > beg) {
18161 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18162 }
18163 flush_pending(strm);
18164 beg = s.pending;
18165 if (s.pending === s.pending_buf_size) {
18166 val = 1;
18167 break;
18168 }
18169 }
18170 // JS specific: little magic to add zero terminator to end of string
18171 if (s.gzindex < s.gzhead.comment.length) {
18172 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
18173 } else {
18174 val = 0;
18175 }
18176 put_byte(s, val);
18177 } while (val !== 0);
18178
18179 if (s.gzhead.hcrc && s.pending > beg) {
18180 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
18181 }
18182 if (val === 0) {
18183 s.status = HCRC_STATE;
18184 }
18185 }
18186 else {
18187 s.status = HCRC_STATE;
18188 }
18189 }
18190 if (s.status === HCRC_STATE) {
18191 if (s.gzhead.hcrc) {
18192 if (s.pending + 2 > s.pending_buf_size) {
18193 flush_pending(strm);
18194 }
18195 if (s.pending + 2 <= s.pending_buf_size) {
18196 put_byte(s, strm.adler & 0xff);
18197 put_byte(s, (strm.adler >> 8) & 0xff);
18198 strm.adler = 0; //crc32(0L, Z_NULL, 0);
18199 s.status = BUSY_STATE;
18200 }
18201 }
18202 else {
18203 s.status = BUSY_STATE;
18204 }
18205 }
18206 //#endif
18207
18208 /* Flush as much pending output as possible */
18209 if (s.pending !== 0) {
18210 flush_pending(strm);
18211 if (strm.avail_out === 0) {
18212 /* Since avail_out is 0, deflate will be called again with
18213 * more output space, but possibly with both pending and
18214 * avail_in equal to zero. There won't be anything to do,
18215 * but this is not an error situation so make sure we
18216 * return OK instead of BUF_ERROR at next call of deflate:
18217 */
18218 s.last_flush = -1;
18219 return Z_OK;
18220 }
18221
18222 /* Make sure there is something to do and avoid duplicate consecutive
18223 * flushes. For repeated and useless calls with Z_FINISH, we keep
18224 * returning Z_STREAM_END instead of Z_BUF_ERROR.
18225 */
18226 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
18227 flush !== Z_FINISH) {
18228 return err(strm, Z_BUF_ERROR);
18229 }
18230
18231 /* User must not provide more input after the first FINISH: */
18232 if (s.status === FINISH_STATE && strm.avail_in !== 0) {
18233 return err(strm, Z_BUF_ERROR);
18234 }
18235
18236 /* Start a new block or continue the current one.
18237 */
18238 if (strm.avail_in !== 0 || s.lookahead !== 0 ||
18239 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
18240 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
18241 (s.strategy === Z_RLE ? deflate_rle(s, flush) :
18242 configuration_table[s.level].func(s, flush));
18243
18244 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
18245 s.status = FINISH_STATE;
18246 }
18247 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
18248 if (strm.avail_out === 0) {
18249 s.last_flush = -1;
18250 /* avoid BUF_ERROR next call, see above */
18251 }
18252 return Z_OK;
18253 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
18254 * of deflate should use the same flush parameter to make sure
18255 * that the flush is complete. So we don't have to output an
18256 * empty block here, this will be done at next call. This also
18257 * ensures that for a very small output buffer, we emit at most
18258 * one empty block.
18259 */
18260 }
18261 if (bstate === BS_BLOCK_DONE) {
18262 if (flush === Z_PARTIAL_FLUSH) {
18263 _tr_align(s);
18264 }
18265 else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
18266
18267 _tr_stored_block(s, 0, 0, false);
18268 /* For a full flush, this empty block will be recognized
18269 * as a special marker by inflate_sync().
18270 */
18271 if (flush === Z_FULL_FLUSH) {
18272 /*** CLEAR_HASH(s); ***/ /* forget history */
18273 zero$2(s.head); // Fill with NIL (= 0);
18274
18275 if (s.lookahead === 0) {
18276 s.strstart = 0;
18277 s.block_start = 0;
18278 s.insert = 0;
18279 }
18280 }
18281 }
18282 flush_pending(strm);
18283 if (strm.avail_out === 0) {
18284 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
18285 return Z_OK;
18286 }
18287 }
18288 }
18289 //Assert(strm->avail_out > 0, "bug2");
18290 //if (strm.avail_out <= 0) { throw new Error("bug2");}
18291
18292 if (flush !== Z_FINISH) { return Z_OK; }
18293 if (s.wrap <= 0) { return Z_STREAM_END; }
18294
18295 /* Write the trailer */
18296 if (s.wrap === 2) {
18297 put_byte(s, strm.adler & 0xff);
18298 put_byte(s, (strm.adler >> 8) & 0xff);
18299 put_byte(s, (strm.adler >> 16) & 0xff);
18300 put_byte(s, (strm.adler >> 24) & 0xff);
18301 put_byte(s, strm.total_in & 0xff);
18302 put_byte(s, (strm.total_in >> 8) & 0xff);
18303 put_byte(s, (strm.total_in >> 16) & 0xff);
18304 put_byte(s, (strm.total_in >> 24) & 0xff);
18305 }
18306 else {
18307 putShortMSB(s, strm.adler >>> 16);
18308 putShortMSB(s, strm.adler & 0xffff);
18309 }
18310
18311 flush_pending(strm);
18312 /* If avail_out is zero, the application will call deflate again
18313 * to flush the rest.
18314 */
18315 if (s.wrap > 0) { s.wrap = -s.wrap; }
18316 /* write the trailer only once! */
18317 return s.pending !== 0 ? Z_OK : Z_STREAM_END;
18318 }
18319
18320 function deflateEnd(strm) {
18321 let status;
18322
18323 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
18324 return Z_STREAM_ERROR;
18325 }
18326
18327 status = strm.state.status;
18328 if (status !== INIT_STATE &&
18329 status !== EXTRA_STATE &&
18330 status !== NAME_STATE &&
18331 status !== COMMENT_STATE &&
18332 status !== HCRC_STATE &&
18333 status !== BUSY_STATE &&
18334 status !== FINISH_STATE
18335 ) {
18336 return err(strm, Z_STREAM_ERROR);
18337 }
18338
18339 strm.state = null;
18340
18341 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
18342 }
18343
18344
18345 /* =========================================================================
18346 * Initializes the compression dictionary from the given byte
18347 * sequence without producing any compressed output.
18348 */
18349 function deflateSetDictionary(strm, dictionary) {
18350 let dictLength = dictionary.length;
18351
18352 let s;
18353 let str, n;
18354 let wrap;
18355 let avail;
18356 let next;
18357 let input;
18358 let tmpDict;
18359
18360 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
18361 return Z_STREAM_ERROR;
18362 }
18363
18364 s = strm.state;
18365 wrap = s.wrap;
18366
18367 if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
18368 return Z_STREAM_ERROR;
18369 }
18370
18371 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
18372 if (wrap === 1) {
18373 /* adler32(strm->adler, dictionary, dictLength); */
18374 strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
18375 }
18376
18377 s.wrap = 0; /* avoid computing Adler-32 in read_buf */
18378
18379 /* if dictionary would fill window, just replace the history */
18380 if (dictLength >= s.w_size) {
18381 if (wrap === 0) { /* already empty otherwise */
18382 /*** CLEAR_HASH(s); ***/
18383 zero$2(s.head); // Fill with NIL (= 0);
18384 s.strstart = 0;
18385 s.block_start = 0;
18386 s.insert = 0;
18387 }
18388 /* use the tail */
18389 // dictionary = dictionary.slice(dictLength - s.w_size);
18390 tmpDict = new Buf8(s.w_size);
18391 arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
18392 dictionary = tmpDict;
18393 dictLength = s.w_size;
18394 }
18395 /* insert dictionary into window and hash */
18396 avail = strm.avail_in;
18397 next = strm.next_in;
18398 input = strm.input;
18399 strm.avail_in = dictLength;
18400 strm.next_in = 0;
18401 strm.input = dictionary;
18402 fill_window(s);
18403 while (s.lookahead >= MIN_MATCH$1) {
18404 str = s.strstart;
18405 n = s.lookahead - (MIN_MATCH$1 - 1);
18406 do {
18407 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
18408 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask;
18409
18410 s.prev[str & s.w_mask] = s.head[s.ins_h];
18411
18412 s.head[s.ins_h] = str;
18413 str++;
18414 } while (--n);
18415 s.strstart = str;
18416 s.lookahead = MIN_MATCH$1 - 1;
18417 fill_window(s);
18418 }
18419 s.strstart += s.lookahead;
18420 s.block_start = s.strstart;
18421 s.insert = s.lookahead;
18422 s.lookahead = 0;
18423 s.match_length = s.prev_length = MIN_MATCH$1 - 1;
18424 s.match_available = 0;
18425 strm.next_in = next;
18426 strm.input = input;
18427 strm.avail_in = avail;
18428 s.wrap = wrap;
18429 return Z_OK;
18430 }
18431
18432 /* Not implemented
18433 exports.deflateBound = deflateBound;
18434 exports.deflateCopy = deflateCopy;
18435 exports.deflateParams = deflateParams;
18436 exports.deflatePending = deflatePending;
18437 exports.deflatePrime = deflatePrime;
18438 exports.deflateTune = deflateTune;
18439 */
18440
18441 // String encode/decode helpers
18442
18443 try {
18444 String.fromCharCode.apply(null, [ 0 ]);
18445 } catch (__) {
18446 }
18447 try {
18448 String.fromCharCode.apply(null, new Uint8Array(1));
18449 } catch (__) {
18450 }
18451
18452
18453 // Table with utf8 lengths (calculated by first byte of sequence)
18454 // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
18455 // because max possible codepoint is 0x10ffff
18456 const _utf8len = new Buf8(256);
18457 for (let q = 0; q < 256; q++) {
18458 _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;
18459 }
18460 _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
18461
18462
18463 // convert string to array (typed, when possible)
18464 function string2buf (str) {
18465 let c, c2, m_pos, i, buf_len = 0;
18466 const str_len = str.length;
18467
18468 // count binary size
18469 for (m_pos = 0; m_pos < str_len; m_pos++) {
18470 c = str.charCodeAt(m_pos);
18471 if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
18472 c2 = str.charCodeAt(m_pos + 1);
18473 if ((c2 & 0xfc00) === 0xdc00) {
18474 c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
18475 m_pos++;
18476 }
18477 }
18478 buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
18479 }
18480
18481 // allocate buffer
18482 const buf = new Buf8(buf_len);
18483
18484 // convert
18485 for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
18486 c = str.charCodeAt(m_pos);
18487 if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
18488 c2 = str.charCodeAt(m_pos + 1);
18489 if ((c2 & 0xfc00) === 0xdc00) {
18490 c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
18491 m_pos++;
18492 }
18493 }
18494 if (c < 0x80) {
18495 /* one byte */
18496 buf[i++] = c;
18497 } else if (c < 0x800) {
18498 /* two bytes */
18499 buf[i++] = 0xC0 | c >>> 6;
18500 buf[i++] = 0x80 | c & 0x3f;
18501 } else if (c < 0x10000) {
18502 /* three bytes */
18503 buf[i++] = 0xE0 | c >>> 12;
18504 buf[i++] = 0x80 | c >>> 6 & 0x3f;
18505 buf[i++] = 0x80 | c & 0x3f;
18506 } else {
18507 /* four bytes */
18508 buf[i++] = 0xf0 | c >>> 18;
18509 buf[i++] = 0x80 | c >>> 12 & 0x3f;
18510 buf[i++] = 0x80 | c >>> 6 & 0x3f;
18511 buf[i++] = 0x80 | c & 0x3f;
18512 }
18513 }
18514
18515 return buf;
18516 }
18517
18518
18519 // Convert binary string (typed, when possible)
18520 function binstring2buf (str) {
18521 const buf = new Buf8(str.length);
18522 for (let i = 0, len = buf.length; i < len; i++) {
18523 buf[i] = str.charCodeAt(i);
18524 }
18525 return buf;
18526 }
18527
18528 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
18529 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
18530 //
18531 // This software is provided 'as-is', without any express or implied
18532 // warranty. In no event will the authors be held liable for any damages
18533 // arising from the use of this software.
18534 //
18535 // Permission is granted to anyone to use this software for any purpose,
18536 // including commercial applications, and to alter it and redistribute it
18537 // freely, subject to the following restrictions:
18538 //
18539 // 1. The origin of this software must not be misrepresented; you must not
18540 // claim that you wrote the original software. If you use this software
18541 // in a product, an acknowledgment in the product documentation would be
18542 // appreciated but is not required.
18543 // 2. Altered source versions must be plainly marked as such, and must not be
18544 // misrepresented as being the original software.
18545 // 3. This notice may not be removed or altered from any source distribution.
18546
18547 class ZStream {
18548 constructor() {
18549 /* next input byte */
18550 this.input = null; // JS specific, because we have no pointers
18551 this.next_in = 0;
18552 /* number of bytes available at input */
18553 this.avail_in = 0;
18554 /* total number of input bytes read so far */
18555 this.total_in = 0;
18556 /* next output byte should be put there */
18557 this.output = null; // JS specific, because we have no pointers
18558 this.next_out = 0;
18559 /* remaining free space at output */
18560 this.avail_out = 0;
18561 /* total number of bytes output so far */
18562 this.total_out = 0;
18563 /* last error message, NULL if no error */
18564 this.msg = ''/*Z_NULL*/;
18565 /* not visible by applications */
18566 this.state = null;
18567 /* best guess about the data type: binary or text */
18568 this.data_type = 2/*Z_UNKNOWN*/;
18569 /* adler32 value of the uncompressed data */
18570 this.adler = 0;
18571 }
18572 }
18573
18574 /* ===========================================================================*/
18575
18576
18577 /**
18578 * class Deflate
18579 *
18580 * Generic JS-style wrapper for zlib calls. If you don't need
18581 * streaming behaviour - use more simple functions: [[deflate]],
18582 * [[deflateRaw]] and [[gzip]].
18583 **/
18584
18585 /* internal
18586 * Deflate.chunks -> Array
18587 *
18588 * Chunks of output data, if [[Deflate#onData]] not overridden.
18589 **/
18590
18591 /**
18592 * Deflate.result -> Uint8Array|Array
18593 *
18594 * Compressed result, generated by default [[Deflate#onData]]
18595 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
18596 * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
18597 * push a chunk with explicit flush (call [[Deflate#push]] with
18598 * `Z_SYNC_FLUSH` param).
18599 **/
18600
18601 /**
18602 * Deflate.err -> Number
18603 *
18604 * Error code after deflate finished. 0 (Z_OK) on success.
18605 * You will not need it in real life, because deflate errors
18606 * are possible only on wrong options or bad `onData` / `onEnd`
18607 * custom handlers.
18608 **/
18609
18610 /**
18611 * Deflate.msg -> String
18612 *
18613 * Error message, if [[Deflate.err]] != 0
18614 **/
18615
18616
18617 /**
18618 * new Deflate(options)
18619 * - options (Object): zlib deflate options.
18620 *
18621 * Creates new deflator instance with specified params. Throws exception
18622 * on bad params. Supported options:
18623 *
18624 * - `level`
18625 * - `windowBits`
18626 * - `memLevel`
18627 * - `strategy`
18628 * - `dictionary`
18629 *
18630 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
18631 * for more information on these.
18632 *
18633 * Additional options, for internal needs:
18634 *
18635 * - `chunkSize` - size of generated data chunks (16K by default)
18636 * - `raw` (Boolean) - do raw deflate
18637 * - `gzip` (Boolean) - create gzip wrapper
18638 * - `to` (String) - if equal to 'string', then result will be "binary string"
18639 * (each char code [0..255])
18640 * - `header` (Object) - custom header for gzip
18641 * - `text` (Boolean) - true if compressed data believed to be text
18642 * - `time` (Number) - modification time, unix timestamp
18643 * - `os` (Number) - operation system code
18644 * - `extra` (Array) - array of bytes with extra data (max 65536)
18645 * - `name` (String) - file name (binary string)
18646 * - `comment` (String) - comment (binary string)
18647 * - `hcrc` (Boolean) - true if header crc should be added
18648 *
18649 * ##### Example:
18650 *
18651 * ```javascript
18652 * var pako = void('pako')
18653 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
18654 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
18655 *
18656 * var deflate = new pako.Deflate({ level: 3});
18657 *
18658 * deflate.push(chunk1, false);
18659 * deflate.push(chunk2, true); // true -> last chunk
18660 *
18661 * if (deflate.err) { throw new Error(deflate.err); }
18662 *
18663 * console.log(deflate.result);
18664 * ```
18665 **/
18666
18667 class Deflate {
18668 constructor(options) {
18669 this.options = {
18670 level: Z_DEFAULT_COMPRESSION,
18671 method: Z_DEFLATED,
18672 chunkSize: 16384,
18673 windowBits: 15,
18674 memLevel: 8,
18675 strategy: Z_DEFAULT_STRATEGY,
18676 ...(options || {})
18677 };
18678
18679 const opt = this.options;
18680
18681 if (opt.raw && (opt.windowBits > 0)) {
18682 opt.windowBits = -opt.windowBits;
18683 }
18684
18685 else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
18686 opt.windowBits += 16;
18687 }
18688
18689 this.err = 0; // error code, if happens (0 = Z_OK)
18690 this.msg = ''; // error message
18691 this.ended = false; // used to avoid multiple onEnd() calls
18692 this.chunks = []; // chunks of compressed data
18693
18694 this.strm = new ZStream();
18695 this.strm.avail_out = 0;
18696
18697 var status = deflateInit2(
18698 this.strm,
18699 opt.level,
18700 opt.method,
18701 opt.windowBits,
18702 opt.memLevel,
18703 opt.strategy
18704 );
18705
18706 if (status !== Z_OK) {
18707 throw new Error(msg[status]);
18708 }
18709
18710 if (opt.header) {
18711 deflateSetHeader(this.strm, opt.header);
18712 }
18713
18714 if (opt.dictionary) {
18715 let dict;
18716 // Convert data if needed
18717 if (typeof opt.dictionary === 'string') {
18718 // If we need to compress text, change encoding to utf8.
18719 dict = string2buf(opt.dictionary);
18720 } else if (opt.dictionary instanceof ArrayBuffer) {
18721 dict = new Uint8Array(opt.dictionary);
18722 } else {
18723 dict = opt.dictionary;
18724 }
18725
18726 status = deflateSetDictionary(this.strm, dict);
18727
18728 if (status !== Z_OK) {
18729 throw new Error(msg[status]);
18730 }
18731
18732 this._dict_set = true;
18733 }
18734 }
18735
18736 /**
18737 * Deflate#push(data[, mode]) -> Boolean
18738 * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
18739 * converted to utf8 byte sequence.
18740 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
18741 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
18742 *
18743 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
18744 * new compressed chunks. Returns `true` on success. The last data block must have
18745 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
18746 * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
18747 * can use mode Z_SYNC_FLUSH, keeping the compression context.
18748 *
18749 * On fail call [[Deflate#onEnd]] with error code and return false.
18750 *
18751 * We strongly recommend to use `Uint8Array` on input for best speed (output
18752 * array format is detected automatically). Also, don't skip last param and always
18753 * use the same type in your code (boolean or number). That will improve JS speed.
18754 *
18755 * For regular `Array`-s make sure all elements are [0..255].
18756 *
18757 * ##### Example
18758 *
18759 * ```javascript
18760 * push(chunk, false); // push one of data chunks
18761 * ...
18762 * push(chunk, true); // push last chunk
18763 * ```
18764 **/
18765 push(data, mode) {
18766 const { strm, options: { chunkSize } } = this;
18767 var status, _mode;
18768
18769 if (this.ended) { return false; }
18770
18771 _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
18772
18773 // Convert data if needed
18774 if (typeof data === 'string') {
18775 // If we need to compress text, change encoding to utf8.
18776 strm.input = string2buf(data);
18777 } else if (data instanceof ArrayBuffer) {
18778 strm.input = new Uint8Array(data);
18779 } else {
18780 strm.input = data;
18781 }
18782
18783 strm.next_in = 0;
18784 strm.avail_in = strm.input.length;
18785
18786 do {
18787 if (strm.avail_out === 0) {
18788 strm.output = new Buf8(chunkSize);
18789 strm.next_out = 0;
18790 strm.avail_out = chunkSize;
18791 }
18792 status = deflate(strm, _mode); /* no bad return value */
18793
18794 if (status !== Z_STREAM_END && status !== Z_OK) {
18795 this.onEnd(status);
18796 this.ended = true;
18797 return false;
18798 }
18799 if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
18800 this.onData(shrinkBuf(strm.output, strm.next_out));
18801 }
18802 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
18803
18804 // Finalize on the last chunk.
18805 if (_mode === Z_FINISH) {
18806 status = deflateEnd(this.strm);
18807 this.onEnd(status);
18808 this.ended = true;
18809 return status === Z_OK;
18810 }
18811
18812 // callback interim results if Z_SYNC_FLUSH.
18813 if (_mode === Z_SYNC_FLUSH) {
18814 this.onEnd(Z_OK);
18815 strm.avail_out = 0;
18816 return true;
18817 }
18818
18819 return true;
18820 };
18821 /**
18822 * Deflate#onData(chunk) -> Void
18823 * - chunk (Uint8Array|Array|String): output data. Type of array depends
18824 * on js engine support. When string output requested, each chunk
18825 * will be string.
18826 *
18827 * By default, stores data blocks in `chunks[]` property and glue
18828 * those in `onEnd`. Override this handler, if you need another behaviour.
18829 **/
18830 onData(chunk) {
18831 this.chunks.push(chunk);
18832 };
18833
18834 /**
18835 * Deflate#onEnd(status) -> Void
18836 * - status (Number): deflate status. 0 (Z_OK) on success,
18837 * other if not.
18838 *
18839 * Called once after you tell deflate that the input stream is
18840 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
18841 * or if an error happened. By default - join collected chunks,
18842 * free memory and fill `results` / `err` properties.
18843 **/
18844 onEnd(status) {
18845 // On success - join
18846 if (status === Z_OK) {
18847 this.result = flattenChunks(this.chunks);
18848 }
18849 this.chunks = [];
18850 this.err = status;
18851 this.msg = this.strm.msg;
18852 };
18853 }
18854
18855 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
18856 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
18857 //
18858 // This software is provided 'as-is', without any express or implied
18859 // warranty. In no event will the authors be held liable for any damages
18860 // arising from the use of this software.
18861 //
18862 // Permission is granted to anyone to use this software for any purpose,
18863 // including commercial applications, and to alter it and redistribute it
18864 // freely, subject to the following restrictions:
18865 //
18866 // 1. The origin of this software must not be misrepresented; you must not
18867 // claim that you wrote the original software. If you use this software
18868 // in a product, an acknowledgment in the product documentation would be
18869 // appreciated but is not required.
18870 // 2. Altered source versions must be plainly marked as such, and must not be
18871 // misrepresented as being the original software.
18872 // 3. This notice may not be removed or altered from any source distribution.
18873
18874 // See state defs from inflate.js
18875 const BAD = 30; /* got a data error -- remain here until reset */
18876 const TYPE = 12; /* i: waiting for type bits, including last-flag bit */
18877
18878 /*
18879 Decode literal, length, and distance codes and write out the resulting
18880 literal and match bytes until either not enough input or output is
18881 available, an end-of-block is encountered, or a data error is encountered.
18882 When large enough input and output buffers are supplied to inflate(), for
18883 example, a 16K input buffer and a 64K output buffer, more than 95% of the
18884 inflate execution time is spent in this routine.
18885
18886 Entry assumptions:
18887
18888 state.mode === LEN
18889 strm.avail_in >= 6
18890 strm.avail_out >= 258
18891 start >= strm.avail_out
18892 state.bits < 8
18893
18894 On return, state.mode is one of:
18895
18896 LEN -- ran out of enough output space or enough available input
18897 TYPE -- reached end of block code, inflate() to interpret next block
18898 BAD -- error in block data
18899
18900 Notes:
18901
18902 - The maximum input bits used by a length/distance pair is 15 bits for the
18903 length code, 5 bits for the length extra, 15 bits for the distance code,
18904 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
18905 Therefore if strm.avail_in >= 6, then there is enough input to avoid
18906 checking for available input while decoding.
18907
18908 - The maximum bytes that a single length/distance pair can output is 258
18909 bytes, which is the maximum length that can be coded. inflate_fast()
18910 requires strm.avail_out >= 258 for each loop to avoid checking for
18911 output space.
18912 */
18913 function inflate_fast(strm, start) {
18914 let _in; /* local strm.input */
18915 let _out; /* local strm.output */
18916 // Use `s_window` instead `window`, avoid conflict with instrumentation tools
18917 let hold; /* local strm.hold */
18918 let bits; /* local strm.bits */
18919 let here; /* retrieved table entry */
18920 let op; /* code bits, operation, extra bits, or */
18921 /* window position, window bytes to copy */
18922 let len; /* match length, unused bytes */
18923 let dist; /* match distance */
18924 let from; /* where to copy match from */
18925 let from_source;
18926
18927
18928
18929 /* copy state to local variables */
18930 const state = strm.state;
18931 //here = state.here;
18932 _in = strm.next_in;
18933 const input = strm.input;
18934 const last = _in + (strm.avail_in - 5);
18935 _out = strm.next_out;
18936 const output = strm.output;
18937 const beg = _out - (start - strm.avail_out);
18938 const end = _out + (strm.avail_out - 257);
18939 //#ifdef INFLATE_STRICT
18940 const dmax = state.dmax;
18941 //#endif
18942 const wsize = state.wsize;
18943 const whave = state.whave;
18944 const wnext = state.wnext;
18945 const s_window = state.window;
18946 hold = state.hold;
18947 bits = state.bits;
18948 const lcode = state.lencode;
18949 const dcode = state.distcode;
18950 const lmask = (1 << state.lenbits) - 1;
18951 const dmask = (1 << state.distbits) - 1;
18952
18953
18954 /* decode literals and length/distances until end-of-block or not enough
18955 input data or output space */
18956
18957 top:
18958 do {
18959 if (bits < 15) {
18960 hold += input[_in++] << bits;
18961 bits += 8;
18962 hold += input[_in++] << bits;
18963 bits += 8;
18964 }
18965
18966 here = lcode[hold & lmask];
18967
18968 dolen:
18969 for (;;) { // Goto emulation
18970 op = here >>> 24/*here.bits*/;
18971 hold >>>= op;
18972 bits -= op;
18973 op = here >>> 16 & 0xff/*here.op*/;
18974 if (op === 0) { /* literal */
18975 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
18976 // "inflate: literal '%c'\n" :
18977 // "inflate: literal 0x%02x\n", here.val));
18978 output[_out++] = here & 0xffff/*here.val*/;
18979 } else if (op & 16) { /* length base */
18980 len = here & 0xffff/*here.val*/;
18981 op &= 15; /* number of extra bits */
18982 if (op) {
18983 if (bits < op) {
18984 hold += input[_in++] << bits;
18985 bits += 8;
18986 }
18987 len += hold & (1 << op) - 1;
18988 hold >>>= op;
18989 bits -= op;
18990 }
18991 //Tracevv((stderr, "inflate: length %u\n", len));
18992 if (bits < 15) {
18993 hold += input[_in++] << bits;
18994 bits += 8;
18995 hold += input[_in++] << bits;
18996 bits += 8;
18997 }
18998 here = dcode[hold & dmask];
18999
19000 dodist:
19001 for (;;) { // goto emulation
19002 op = here >>> 24/*here.bits*/;
19003 hold >>>= op;
19004 bits -= op;
19005 op = here >>> 16 & 0xff/*here.op*/;
19006
19007 if (op & 16) { /* distance base */
19008 dist = here & 0xffff/*here.val*/;
19009 op &= 15; /* number of extra bits */
19010 if (bits < op) {
19011 hold += input[_in++] << bits;
19012 bits += 8;
19013 if (bits < op) {
19014 hold += input[_in++] << bits;
19015 bits += 8;
19016 }
19017 }
19018 dist += hold & (1 << op) - 1;
19019 //#ifdef INFLATE_STRICT
19020 if (dist > dmax) {
19021 strm.msg = "invalid distance too far back";
19022 state.mode = BAD;
19023 break top;
19024 }
19025 //#endif
19026 hold >>>= op;
19027 bits -= op;
19028 //Tracevv((stderr, "inflate: distance %u\n", dist));
19029 op = _out - beg; /* max distance in output */
19030 if (dist > op) { /* see if copy from window */
19031 op = dist - op; /* distance back in window */
19032 if (op > whave) {
19033 if (state.sane) {
19034 strm.msg = "invalid distance too far back";
19035 state.mode = BAD;
19036 break top;
19037 }
19038
19039 // (!) This block is disabled in zlib defaults,
19040 // don't enable it for binary compatibility
19041 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
19042 // if (len <= op - whave) {
19043 // do {
19044 // output[_out++] = 0;
19045 // } while (--len);
19046 // continue top;
19047 // }
19048 // len -= op - whave;
19049 // do {
19050 // output[_out++] = 0;
19051 // } while (--op > whave);
19052 // if (op === 0) {
19053 // from = _out - dist;
19054 // do {
19055 // output[_out++] = output[from++];
19056 // } while (--len);
19057 // continue top;
19058 // }
19059 //#endif
19060 }
19061 from = 0; // window index
19062 from_source = s_window;
19063 if (wnext === 0) { /* very common case */
19064 from += wsize - op;
19065 if (op < len) { /* some from window */
19066 len -= op;
19067 do {
19068 output[_out++] = s_window[from++];
19069 } while (--op);
19070 from = _out - dist; /* rest from output */
19071 from_source = output;
19072 }
19073 } else if (wnext < op) { /* wrap around window */
19074 from += wsize + wnext - op;
19075 op -= wnext;
19076 if (op < len) { /* some from end of window */
19077 len -= op;
19078 do {
19079 output[_out++] = s_window[from++];
19080 } while (--op);
19081 from = 0;
19082 if (wnext < len) { /* some from start of window */
19083 op = wnext;
19084 len -= op;
19085 do {
19086 output[_out++] = s_window[from++];
19087 } while (--op);
19088 from = _out - dist; /* rest from output */
19089 from_source = output;
19090 }
19091 }
19092 } else { /* contiguous in window */
19093 from += wnext - op;
19094 if (op < len) { /* some from window */
19095 len -= op;
19096 do {
19097 output[_out++] = s_window[from++];
19098 } while (--op);
19099 from = _out - dist; /* rest from output */
19100 from_source = output;
19101 }
19102 }
19103 while (len > 2) {
19104 output[_out++] = from_source[from++];
19105 output[_out++] = from_source[from++];
19106 output[_out++] = from_source[from++];
19107 len -= 3;
19108 }
19109 if (len) {
19110 output[_out++] = from_source[from++];
19111 if (len > 1) {
19112 output[_out++] = from_source[from++];
19113 }
19114 }
19115 } else {
19116 from = _out - dist; /* copy direct from output */
19117 do { /* minimum length is three */
19118 output[_out++] = output[from++];
19119 output[_out++] = output[from++];
19120 output[_out++] = output[from++];
19121 len -= 3;
19122 } while (len > 2);
19123 if (len) {
19124 output[_out++] = output[from++];
19125 if (len > 1) {
19126 output[_out++] = output[from++];
19127 }
19128 }
19129 }
19130 } else if ((op & 64) === 0) { /* 2nd level distance code */
19131 here = dcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];
19132 continue dodist;
19133 } else {
19134 strm.msg = "invalid distance code";
19135 state.mode = BAD;
19136 break top;
19137 }
19138
19139 break; // need to emulate goto via "continue"
19140 }
19141 } else if ((op & 64) === 0) { /* 2nd level length code */
19142 here = lcode[(here & 0xffff)/*here.val*/ + (hold & (1 << op) - 1)];
19143 continue dolen;
19144 } else if (op & 32) { /* end-of-block */
19145 //Tracevv((stderr, "inflate: end of block\n"));
19146 state.mode = TYPE;
19147 break top;
19148 } else {
19149 strm.msg = "invalid literal/length code";
19150 state.mode = BAD;
19151 break top;
19152 }
19153
19154 break; // need to emulate goto via "continue"
19155 }
19156 } while (_in < last && _out < end);
19157
19158 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
19159 len = bits >> 3;
19160 _in -= len;
19161 bits -= len << 3;
19162 hold &= (1 << bits) - 1;
19163
19164 /* update state and return */
19165 strm.next_in = _in;
19166 strm.next_out = _out;
19167 strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);
19168 strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);
19169 state.hold = hold;
19170 state.bits = bits;
19171 return;
19172 }
19173
19174 const MAXBITS = 15;
19175 const ENOUGH_LENS = 852;
19176 const ENOUGH_DISTS = 592;
19177 //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
19178
19179 const CODES = 0;
19180 const LENS = 1;
19181 const DISTS = 2;
19182
19183 const lbase = [ /* Length codes 257..285 base */
19184 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
19185 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
19186 ];
19187
19188 const lext = [ /* Length codes 257..285 extra */
19189 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19190 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
19191 ];
19192
19193 const dbase = [ /* Distance codes 0..29 base */
19194 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
19195 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
19196 8193, 12289, 16385, 24577, 0, 0
19197 ];
19198
19199 const dext = [ /* Distance codes 0..29 extra */
19200 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
19201 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
19202 28, 28, 29, 29, 64, 64
19203 ];
19204
19205 function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {
19206 const bits = opts.bits;
19207 //here = opts.here; /* table entry for duplication */
19208
19209 let len = 0; /* a code's length in bits */
19210 let sym = 0; /* index of code symbols */
19211 let min = 0, max = 0; /* minimum and maximum code lengths */
19212 let root = 0; /* number of index bits for root table */
19213 let curr = 0; /* number of index bits for current table */
19214 let drop = 0; /* code bits to drop for sub-table */
19215 let left = 0; /* number of prefix codes available */
19216 let used = 0; /* code entries in table used */
19217 let huff = 0; /* Huffman code */
19218 let incr; /* for incrementing code, index */
19219 let fill; /* index for replicating entries */
19220 let low; /* low bits for current root entry */
19221 let next; /* next available space in table */
19222 let base = null; /* base value table to use */
19223 let base_index = 0;
19224 // var shoextra; /* extra bits table to use */
19225 let end; /* use base and extra for symbol > end */
19226 const count = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
19227 const offs = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
19228 let extra = null;
19229 let extra_index = 0;
19230
19231 let here_bits, here_op, here_val;
19232
19233 /*
19234 Process a set of code lengths to create a canonical Huffman code. The
19235 code lengths are lens[0..codes-1]. Each length corresponds to the
19236 symbols 0..codes-1. The Huffman code is generated by first sorting the
19237 symbols by length from short to long, and retaining the symbol order
19238 for codes with equal lengths. Then the code starts with all zero bits
19239 for the first code of the shortest length, and the codes are integer
19240 increments for the same length, and zeros are appended as the length
19241 increases. For the deflate format, these bits are stored backwards
19242 from their more natural integer increment ordering, and so when the
19243 decoding tables are built in the large loop below, the integer codes
19244 are incremented backwards.
19245
19246 This routine assumes, but does not check, that all of the entries in
19247 lens[] are in the range 0..MAXBITS. The caller must assure this.
19248 1..MAXBITS is interpreted as that code length. zero means that that
19249 symbol does not occur in this code.
19250
19251 The codes are sorted by computing a count of codes for each length,
19252 creating from that a table of starting indices for each length in the
19253 sorted table, and then entering the symbols in order in the sorted
19254 table. The sorted table is work[], with that space being provided by
19255 the caller.
19256
19257 The length counts are used for other purposes as well, i.e. finding
19258 the minimum and maximum length codes, determining if there are any
19259 codes at all, checking for a valid set of lengths, and looking ahead
19260 at length counts to determine sub-table sizes when building the
19261 decoding tables.
19262 */
19263
19264 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
19265 for (len = 0; len <= MAXBITS; len++) {
19266 count[len] = 0;
19267 }
19268 for (sym = 0; sym < codes; sym++) {
19269 count[lens[lens_index + sym]]++;
19270 }
19271
19272 /* bound code lengths, force root to be within code lengths */
19273 root = bits;
19274 for (max = MAXBITS; max >= 1; max--) {
19275 if (count[max] !== 0) {
19276 break;
19277 }
19278 }
19279 if (root > max) {
19280 root = max;
19281 }
19282 if (max === 0) { /* no symbols to code at all */
19283 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
19284 //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
19285 //table.val[opts.table_index++] = 0; //here.val = (var short)0;
19286 table[table_index++] = 1 << 24 | 64 << 16 | 0;
19287
19288
19289 //table.op[opts.table_index] = 64;
19290 //table.bits[opts.table_index] = 1;
19291 //table.val[opts.table_index++] = 0;
19292 table[table_index++] = 1 << 24 | 64 << 16 | 0;
19293
19294 opts.bits = 1;
19295 return 0; /* no symbols, but wait for decoding to report error */
19296 }
19297 for (min = 1; min < max; min++) {
19298 if (count[min] !== 0) {
19299 break;
19300 }
19301 }
19302 if (root < min) {
19303 root = min;
19304 }
19305
19306 /* check for an over-subscribed or incomplete set of lengths */
19307 left = 1;
19308 for (len = 1; len <= MAXBITS; len++) {
19309 left <<= 1;
19310 left -= count[len];
19311 if (left < 0) {
19312 return -1;
19313 } /* over-subscribed */
19314 }
19315 if (left > 0 && (type === CODES || max !== 1)) {
19316 return -1; /* incomplete set */
19317 }
19318
19319 /* generate offsets into symbol table for each length for sorting */
19320 offs[1] = 0;
19321 for (len = 1; len < MAXBITS; len++) {
19322 offs[len + 1] = offs[len] + count[len];
19323 }
19324
19325 /* sort symbols by length, by symbol order within each length */
19326 for (sym = 0; sym < codes; sym++) {
19327 if (lens[lens_index + sym] !== 0) {
19328 work[offs[lens[lens_index + sym]]++] = sym;
19329 }
19330 }
19331
19332 /*
19333 Create and fill in decoding tables. In this loop, the table being
19334 filled is at next and has curr index bits. The code being used is huff
19335 with length len. That code is converted to an index by dropping drop
19336 bits off of the bottom. For codes where len is less than drop + curr,
19337 those top drop + curr - len bits are incremented through all values to
19338 fill the table with replicated entries.
19339
19340 root is the number of index bits for the root table. When len exceeds
19341 root, sub-tables are created pointed to by the root entry with an index
19342 of the low root bits of huff. This is saved in low to check for when a
19343 new sub-table should be started. drop is zero when the root table is
19344 being filled, and drop is root when sub-tables are being filled.
19345
19346 When a new sub-table is needed, it is necessary to look ahead in the
19347 code lengths to determine what size sub-table is needed. The length
19348 counts are used for this, and so count[] is decremented as codes are
19349 entered in the tables.
19350
19351 used keeps track of how many table entries have been allocated from the
19352 provided *table space. It is checked for LENS and DIST tables against
19353 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
19354 the initial root table size constants. See the comments in inftrees.h
19355 for more information.
19356
19357 sym increments through all symbols, and the loop terminates when
19358 all codes of length max, i.e. all codes, have been processed. This
19359 routine permits incomplete codes, so another loop after this one fills
19360 in the rest of the decoding tables with invalid code markers.
19361 */
19362
19363 /* set up for code type */
19364 // poor man optimization - use if-else instead of switch,
19365 // to avoid deopts in old v8
19366 if (type === CODES) {
19367 base = extra = work; /* dummy value--not used */
19368 end = 19;
19369
19370 } else if (type === LENS) {
19371 base = lbase;
19372 base_index -= 257;
19373 extra = lext;
19374 extra_index -= 257;
19375 end = 256;
19376
19377 } else { /* DISTS */
19378 base = dbase;
19379 extra = dext;
19380 end = -1;
19381 }
19382
19383 /* initialize opts for loop */
19384 huff = 0; /* starting code */
19385 sym = 0; /* starting code symbol */
19386 len = min; /* starting code length */
19387 next = table_index; /* current table to fill in */
19388 curr = root; /* current table index bits */
19389 drop = 0; /* current bits to drop from code for index */
19390 low = -1; /* trigger new sub-table when len > root */
19391 used = 1 << root; /* use root table entries */
19392 const mask = used - 1; /* mask for comparing low */
19393
19394 /* check available table space */
19395 if (type === LENS && used > ENOUGH_LENS ||
19396 type === DISTS && used > ENOUGH_DISTS) {
19397 return 1;
19398 }
19399
19400 /* process all codes and make table entries */
19401 for (;;) {
19402 /* create table entry */
19403 here_bits = len - drop;
19404 if (work[sym] < end) {
19405 here_op = 0;
19406 here_val = work[sym];
19407 } else if (work[sym] > end) {
19408 here_op = extra[extra_index + work[sym]];
19409 here_val = base[base_index + work[sym]];
19410 } else {
19411 here_op = 32 + 64; /* end of block */
19412 here_val = 0;
19413 }
19414
19415 /* replicate for those indices with low len bits equal to huff */
19416 incr = 1 << len - drop;
19417 fill = 1 << curr;
19418 min = fill; /* save offset to next table */
19419 do {
19420 fill -= incr;
19421 table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val |0;
19422 } while (fill !== 0);
19423
19424 /* backwards increment the len-bit code huff */
19425 incr = 1 << len - 1;
19426 while (huff & incr) {
19427 incr >>= 1;
19428 }
19429 if (incr !== 0) {
19430 huff &= incr - 1;
19431 huff += incr;
19432 } else {
19433 huff = 0;
19434 }
19435
19436 /* go to next symbol, update count, len */
19437 sym++;
19438 if (--count[len] === 0) {
19439 if (len === max) {
19440 break;
19441 }
19442 len = lens[lens_index + work[sym]];
19443 }
19444
19445 /* create new sub-table if needed */
19446 if (len > root && (huff & mask) !== low) {
19447 /* if first time, transition to sub-tables */
19448 if (drop === 0) {
19449 drop = root;
19450 }
19451
19452 /* increment past last table */
19453 next += min; /* here min is 1 << curr */
19454
19455 /* determine length of next table */
19456 curr = len - drop;
19457 left = 1 << curr;
19458 while (curr + drop < max) {
19459 left -= count[curr + drop];
19460 if (left <= 0) {
19461 break;
19462 }
19463 curr++;
19464 left <<= 1;
19465 }
19466
19467 /* check for enough space */
19468 used += 1 << curr;
19469 if (type === LENS && used > ENOUGH_LENS ||
19470 type === DISTS && used > ENOUGH_DISTS) {
19471 return 1;
19472 }
19473
19474 /* point entry in root table to sub-table */
19475 low = huff & mask;
19476 /*table.op[low] = curr;
19477 table.bits[low] = root;
19478 table.val[low] = next - opts.table_index;*/
19479 table[low] = root << 24 | curr << 16 | next - table_index |0;
19480 }
19481 }
19482
19483 /* fill in remaining table entry if code is incomplete (guaranteed to have
19484 at most one remaining entry, since if the code is incomplete, the
19485 maximum code length that was allowed to get this far is one bit) */
19486 if (huff !== 0) {
19487 //table.op[next + huff] = 64; /* invalid code marker */
19488 //table.bits[next + huff] = len - drop;
19489 //table.val[next + huff] = 0;
19490 table[next + huff] = len - drop << 24 | 64 << 16 |0;
19491 }
19492
19493 /* set return parameters */
19494 //opts.table_index += used;
19495 opts.bits = root;
19496 return 0;
19497 }
19498
19499 const CODES$1 = 0;
19500 const LENS$1 = 1;
19501 const DISTS$1 = 2;
19502
19503 /* STATES ====================================================================*/
19504 /* ===========================================================================*/
19505
19506
19507 const HEAD = 1; /* i: waiting for magic header */
19508 const FLAGS = 2; /* i: waiting for method and flags (gzip) */
19509 const TIME = 3; /* i: waiting for modification time (gzip) */
19510 const OS = 4; /* i: waiting for extra flags and operating system (gzip) */
19511 const EXLEN = 5; /* i: waiting for extra length (gzip) */
19512 const EXTRA = 6; /* i: waiting for extra bytes (gzip) */
19513 const NAME = 7; /* i: waiting for end of file name (gzip) */
19514 const COMMENT = 8; /* i: waiting for end of comment (gzip) */
19515 const HCRC = 9; /* i: waiting for header crc (gzip) */
19516 const DICTID = 10; /* i: waiting for dictionary check value */
19517 const DICT = 11; /* waiting for inflateSetDictionary() call */
19518 const TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */
19519 const TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
19520 const STORED = 14; /* i: waiting for stored size (length and complement) */
19521 const COPY_ = 15; /* i/o: same as COPY below, but only first time in */
19522 const COPY = 16; /* i/o: waiting for input or output to copy stored block */
19523 const TABLE = 17; /* i: waiting for dynamic block table lengths */
19524 const LENLENS = 18; /* i: waiting for code length code lengths */
19525 const CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
19526 const LEN_ = 20; /* i: same as LEN below, but only first time in */
19527 const LEN = 21; /* i: waiting for length/lit/eob code */
19528 const LENEXT = 22; /* i: waiting for length extra bits */
19529 const DIST = 23; /* i: waiting for distance code */
19530 const DISTEXT = 24; /* i: waiting for distance extra bits */
19531 const MATCH = 25; /* o: waiting for output space to copy string */
19532 const LIT = 26; /* o: waiting for output space to write literal */
19533 const CHECK = 27; /* i: waiting for 32-bit check value */
19534 const LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
19535 const DONE = 29; /* finished check, done -- remain here until reset */
19536 const BAD$1 = 30; /* got a data error -- remain here until reset */
19537 //const MEM = 31; /* got an inflate() memory error -- remain here until reset */
19538 const SYNC = 32; /* looking for synchronization bytes to restart inflate() */
19539
19540 /* ===========================================================================*/
19541
19542
19543
19544 const ENOUGH_LENS$1 = 852;
19545 const ENOUGH_DISTS$1 = 592;
19546
19547
19548 function zswap32(q) {
19549 return (((q >>> 24) & 0xff) +
19550 ((q >>> 8) & 0xff00) +
19551 ((q & 0xff00) << 8) +
19552 ((q & 0xff) << 24));
19553 }
19554
19555
19556 class InflateState {
19557 constructor() {
19558 this.mode = 0; /* current inflate mode */
19559 this.last = false; /* true if processing last block */
19560 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
19561 this.havedict = false; /* true if dictionary provided */
19562 this.flags = 0; /* gzip header method and flags (0 if zlib) */
19563 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
19564 this.check = 0; /* protected copy of check value */
19565 this.total = 0; /* protected copy of output count */
19566 // TODO: may be {}
19567 this.head = null; /* where to save gzip header information */
19568
19569 /* sliding window */
19570 this.wbits = 0; /* log base 2 of requested window size */
19571 this.wsize = 0; /* window size or zero if not using window */
19572 this.whave = 0; /* valid bytes in the window */
19573 this.wnext = 0; /* window write index */
19574 this.window = null; /* allocated sliding window, if needed */
19575
19576 /* bit accumulator */
19577 this.hold = 0; /* input bit accumulator */
19578 this.bits = 0; /* number of bits in "in" */
19579
19580 /* for string and stored block copying */
19581 this.length = 0; /* literal or length of data to copy */
19582 this.offset = 0; /* distance back to copy string from */
19583
19584 /* for table and code decoding */
19585 this.extra = 0; /* extra bits needed */
19586
19587 /* fixed and dynamic code tables */
19588 this.lencode = null; /* starting table for length/literal codes */
19589 this.distcode = null; /* starting table for distance codes */
19590 this.lenbits = 0; /* index bits for lencode */
19591 this.distbits = 0; /* index bits for distcode */
19592
19593 /* dynamic table building */
19594 this.ncode = 0; /* number of code length code lengths */
19595 this.nlen = 0; /* number of length code lengths */
19596 this.ndist = 0; /* number of distance code lengths */
19597 this.have = 0; /* number of code lengths in lens[] */
19598 this.next = null; /* next available space in codes[] */
19599
19600 this.lens = new Buf16(320); /* temporary storage for code lengths */
19601 this.work = new Buf16(288); /* work area for code table building */
19602
19603 /*
19604 because we don't have pointers in js, we use lencode and distcode directly
19605 as buffers so we don't need codes
19606 */
19607 //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
19608 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
19609 this.distdyn = null; /* dynamic table for distance codes (JS specific) */
19610 this.sane = 0; /* if false, allow invalid distance too far */
19611 this.back = 0; /* bits back of last unprocessed length/lit */
19612 this.was = 0; /* initial length of match */
19613 }
19614 }
19615
19616 function inflateResetKeep(strm) {
19617 let state;
19618
19619 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
19620 state = strm.state;
19621 strm.total_in = strm.total_out = state.total = 0;
19622 strm.msg = ''; /*Z_NULL*/
19623 if (state.wrap) { /* to support ill-conceived Java test suite */
19624 strm.adler = state.wrap & 1;
19625 }
19626 state.mode = HEAD;
19627 state.last = 0;
19628 state.havedict = 0;
19629 state.dmax = 32768;
19630 state.head = null/*Z_NULL*/;
19631 state.hold = 0;
19632 state.bits = 0;
19633 //state.lencode = state.distcode = state.next = state.codes;
19634 state.lencode = state.lendyn = new Buf32(ENOUGH_LENS$1);
19635 state.distcode = state.distdyn = new Buf32(ENOUGH_DISTS$1);
19636
19637 state.sane = 1;
19638 state.back = -1;
19639 //Tracev((stderr, "inflate: reset\n"));
19640 return Z_OK;
19641 }
19642
19643 function inflateReset(strm) {
19644 let state;
19645
19646 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
19647 state = strm.state;
19648 state.wsize = 0;
19649 state.whave = 0;
19650 state.wnext = 0;
19651 return inflateResetKeep(strm);
19652
19653 }
19654
19655 function inflateReset2(strm, windowBits) {
19656 let wrap;
19657 let state;
19658
19659 /* get the state */
19660 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
19661 state = strm.state;
19662
19663 /* extract wrap request from windowBits parameter */
19664 if (windowBits < 0) {
19665 wrap = 0;
19666 windowBits = -windowBits;
19667 }
19668 else {
19669 wrap = (windowBits >> 4) + 1;
19670 if (windowBits < 48) {
19671 windowBits &= 15;
19672 }
19673 }
19674
19675 /* set number of window bits, free window if different */
19676 if (windowBits && (windowBits < 8 || windowBits > 15)) {
19677 return Z_STREAM_ERROR;
19678 }
19679 if (state.window !== null && state.wbits !== windowBits) {
19680 state.window = null;
19681 }
19682
19683 /* update state and reset the rest of it */
19684 state.wrap = wrap;
19685 state.wbits = windowBits;
19686 return inflateReset(strm);
19687 }
19688
19689 function inflateInit2(strm, windowBits) {
19690 let ret;
19691 let state;
19692
19693 if (!strm) { return Z_STREAM_ERROR; }
19694 //strm.msg = Z_NULL; /* in case we return an error */
19695
19696 state = new InflateState();
19697
19698 //if (state === Z_NULL) return Z_MEM_ERROR;
19699 //Tracev((stderr, "inflate: allocated\n"));
19700 strm.state = state;
19701 state.window = null/*Z_NULL*/;
19702 ret = inflateReset2(strm, windowBits);
19703 if (ret !== Z_OK) {
19704 strm.state = null/*Z_NULL*/;
19705 }
19706 return ret;
19707 }
19708
19709
19710 /*
19711 Return state with length and distance decoding tables and index sizes set to
19712 fixed code decoding. Normally this returns fixed tables from inffixed.h.
19713 If BUILDFIXED is defined, then instead this routine builds the tables the
19714 first time it's called, and returns those tables the first time and
19715 thereafter. This reduces the size of the code by about 2K bytes, in
19716 exchange for a little execution time. However, BUILDFIXED should not be
19717 used for threaded applications, since the rewriting of the tables and virgin
19718 may not be thread-safe.
19719 */
19720 let virgin = true;
19721
19722 let lenfix, distfix; // We have no pointers in JS, so keep tables separate
19723
19724 function fixedtables(state) {
19725 /* build fixed huffman tables if first call (may not be thread safe) */
19726 if (virgin) {
19727 let sym;
19728
19729 lenfix = new Buf32(512);
19730 distfix = new Buf32(32);
19731
19732 /* literal/length table */
19733 sym = 0;
19734 while (sym < 144) { state.lens[sym++] = 8; }
19735 while (sym < 256) { state.lens[sym++] = 9; }
19736 while (sym < 280) { state.lens[sym++] = 7; }
19737 while (sym < 288) { state.lens[sym++] = 8; }
19738
19739 inflate_table(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
19740
19741 /* distance table */
19742 sym = 0;
19743 while (sym < 32) { state.lens[sym++] = 5; }
19744
19745 inflate_table(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
19746
19747 /* do this just once */
19748 virgin = false;
19749 }
19750
19751 state.lencode = lenfix;
19752 state.lenbits = 9;
19753 state.distcode = distfix;
19754 state.distbits = 5;
19755 }
19756
19757
19758 /*
19759 Update the window with the last wsize (normally 32K) bytes written before
19760 returning. If window does not exist yet, create it. This is only called
19761 when a window is already in use, or when output has been written during this
19762 inflate call, but the end of the deflate stream has not been reached yet.
19763 It is also called to create a window for dictionary data when a dictionary
19764 is loaded.
19765
19766 Providing output buffers larger than 32K to inflate() should provide a speed
19767 advantage, since only the last 32K of output is copied to the sliding window
19768 upon return from inflate(), and since all distances after the first 32K of
19769 output will fall in the output data, making match copies simpler and faster.
19770 The advantage may be dependent on the size of the processor's data caches.
19771 */
19772 function updatewindow(strm, src, end, copy) {
19773 let dist;
19774 const state = strm.state;
19775
19776 /* if it hasn't been done already, allocate space for the window */
19777 if (state.window === null) {
19778 state.wsize = 1 << state.wbits;
19779 state.wnext = 0;
19780 state.whave = 0;
19781
19782 state.window = new Buf8(state.wsize);
19783 }
19784
19785 /* copy state->wsize or less output bytes into the circular window */
19786 if (copy >= state.wsize) {
19787 arraySet(state.window, src, end - state.wsize, state.wsize, 0);
19788 state.wnext = 0;
19789 state.whave = state.wsize;
19790 }
19791 else {
19792 dist = state.wsize - state.wnext;
19793 if (dist > copy) {
19794 dist = copy;
19795 }
19796 //zmemcpy(state->window + state->wnext, end - copy, dist);
19797 arraySet(state.window, src, end - copy, dist, state.wnext);
19798 copy -= dist;
19799 if (copy) {
19800 //zmemcpy(state->window, end - copy, copy);
19801 arraySet(state.window, src, end - copy, copy, 0);
19802 state.wnext = copy;
19803 state.whave = state.wsize;
19804 }
19805 else {
19806 state.wnext += dist;
19807 if (state.wnext === state.wsize) { state.wnext = 0; }
19808 if (state.whave < state.wsize) { state.whave += dist; }
19809 }
19810 }
19811 return 0;
19812 }
19813
19814 function inflate(strm, flush) {
19815 let state;
19816 let input, output; // input/output buffers
19817 let next; /* next input INDEX */
19818 let put; /* next output INDEX */
19819 let have, left; /* available input and output */
19820 let hold; /* bit buffer */
19821 let bits; /* bits in bit buffer */
19822 let _in, _out; /* save starting available input and output */
19823 let copy; /* number of stored or match bytes to copy */
19824 let from; /* where to copy match bytes from */
19825 let from_source;
19826 let here = 0; /* current decoding table entry */
19827 let here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
19828 //var last; /* parent table entry */
19829 let last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
19830 let len; /* length to copy for repeats, bits to drop */
19831 let ret; /* return code */
19832 let hbuf = new Buf8(4); /* buffer for gzip header crc calculation */
19833 let opts;
19834
19835 let n; // temporary var for NEED_BITS
19836
19837 const order = /* permutation of code lengths */
19838 [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
19839
19840
19841 if (!strm || !strm.state || !strm.output ||
19842 (!strm.input && strm.avail_in !== 0)) {
19843 return Z_STREAM_ERROR;
19844 }
19845
19846 state = strm.state;
19847 if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */
19848
19849
19850 //--- LOAD() ---
19851 put = strm.next_out;
19852 output = strm.output;
19853 left = strm.avail_out;
19854 next = strm.next_in;
19855 input = strm.input;
19856 have = strm.avail_in;
19857 hold = state.hold;
19858 bits = state.bits;
19859 //---
19860
19861 _in = have;
19862 _out = left;
19863 ret = Z_OK;
19864
19865 inf_leave: // goto emulation
19866 for (;;) {
19867 switch (state.mode) {
19868 case HEAD:
19869 if (state.wrap === 0) {
19870 state.mode = TYPEDO;
19871 break;
19872 }
19873 //=== NEEDBITS(16);
19874 while (bits < 16) {
19875 if (have === 0) { break inf_leave; }
19876 have--;
19877 hold += input[next++] << bits;
19878 bits += 8;
19879 }
19880 //===//
19881 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
19882 state.check = 0/*crc32(0L, Z_NULL, 0)*/;
19883 //=== CRC2(state.check, hold);
19884 hbuf[0] = hold & 0xff;
19885 hbuf[1] = (hold >>> 8) & 0xff;
19886 state.check = crc32(state.check, hbuf, 2, 0);
19887 //===//
19888
19889 //=== INITBITS();
19890 hold = 0;
19891 bits = 0;
19892 //===//
19893 state.mode = FLAGS;
19894 break;
19895 }
19896 state.flags = 0; /* expect zlib header */
19897 if (state.head) {
19898 state.head.done = false;
19899 }
19900 if (!(state.wrap & 1) || /* check if zlib header allowed */
19901 (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
19902 strm.msg = 'incorrect header check';
19903 state.mode = BAD$1;
19904 break;
19905 }
19906 if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
19907 strm.msg = 'unknown compression method';
19908 state.mode = BAD$1;
19909 break;
19910 }
19911 //--- DROPBITS(4) ---//
19912 hold >>>= 4;
19913 bits -= 4;
19914 //---//
19915 len = (hold & 0x0f)/*BITS(4)*/ + 8;
19916 if (state.wbits === 0) {
19917 state.wbits = len;
19918 }
19919 else if (len > state.wbits) {
19920 strm.msg = 'invalid window size';
19921 state.mode = BAD$1;
19922 break;
19923 }
19924 state.dmax = 1 << len;
19925 //Tracev((stderr, "inflate: zlib header ok\n"));
19926 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
19927 state.mode = hold & 0x200 ? DICTID : TYPE$1;
19928 //=== INITBITS();
19929 hold = 0;
19930 bits = 0;
19931 //===//
19932 break;
19933 case FLAGS:
19934 //=== NEEDBITS(16); */
19935 while (bits < 16) {
19936 if (have === 0) { break inf_leave; }
19937 have--;
19938 hold += input[next++] << bits;
19939 bits += 8;
19940 }
19941 //===//
19942 state.flags = hold;
19943 if ((state.flags & 0xff) !== Z_DEFLATED) {
19944 strm.msg = 'unknown compression method';
19945 state.mode = BAD$1;
19946 break;
19947 }
19948 if (state.flags & 0xe000) {
19949 strm.msg = 'unknown header flags set';
19950 state.mode = BAD$1;
19951 break;
19952 }
19953 if (state.head) {
19954 state.head.text = ((hold >> 8) & 1);
19955 }
19956 if (state.flags & 0x0200) {
19957 //=== CRC2(state.check, hold);
19958 hbuf[0] = hold & 0xff;
19959 hbuf[1] = (hold >>> 8) & 0xff;
19960 state.check = crc32(state.check, hbuf, 2, 0);
19961 //===//
19962 }
19963 //=== INITBITS();
19964 hold = 0;
19965 bits = 0;
19966 //===//
19967 state.mode = TIME;
19968 /* falls through */
19969 case TIME:
19970 //=== NEEDBITS(32); */
19971 while (bits < 32) {
19972 if (have === 0) { break inf_leave; }
19973 have--;
19974 hold += input[next++] << bits;
19975 bits += 8;
19976 }
19977 //===//
19978 if (state.head) {
19979 state.head.time = hold;
19980 }
19981 if (state.flags & 0x0200) {
19982 //=== CRC4(state.check, hold)
19983 hbuf[0] = hold & 0xff;
19984 hbuf[1] = (hold >>> 8) & 0xff;
19985 hbuf[2] = (hold >>> 16) & 0xff;
19986 hbuf[3] = (hold >>> 24) & 0xff;
19987 state.check = crc32(state.check, hbuf, 4, 0);
19988 //===
19989 }
19990 //=== INITBITS();
19991 hold = 0;
19992 bits = 0;
19993 //===//
19994 state.mode = OS;
19995 /* falls through */
19996 case OS:
19997 //=== NEEDBITS(16); */
19998 while (bits < 16) {
19999 if (have === 0) { break inf_leave; }
20000 have--;
20001 hold += input[next++] << bits;
20002 bits += 8;
20003 }
20004 //===//
20005 if (state.head) {
20006 state.head.xflags = (hold & 0xff);
20007 state.head.os = (hold >> 8);
20008 }
20009 if (state.flags & 0x0200) {
20010 //=== CRC2(state.check, hold);
20011 hbuf[0] = hold & 0xff;
20012 hbuf[1] = (hold >>> 8) & 0xff;
20013 state.check = crc32(state.check, hbuf, 2, 0);
20014 //===//
20015 }
20016 //=== INITBITS();
20017 hold = 0;
20018 bits = 0;
20019 //===//
20020 state.mode = EXLEN;
20021 /* falls through */
20022 case EXLEN:
20023 if (state.flags & 0x0400) {
20024 //=== NEEDBITS(16); */
20025 while (bits < 16) {
20026 if (have === 0) { break inf_leave; }
20027 have--;
20028 hold += input[next++] << bits;
20029 bits += 8;
20030 }
20031 //===//
20032 state.length = hold;
20033 if (state.head) {
20034 state.head.extra_len = hold;
20035 }
20036 if (state.flags & 0x0200) {
20037 //=== CRC2(state.check, hold);
20038 hbuf[0] = hold & 0xff;
20039 hbuf[1] = (hold >>> 8) & 0xff;
20040 state.check = crc32(state.check, hbuf, 2, 0);
20041 //===//
20042 }
20043 //=== INITBITS();
20044 hold = 0;
20045 bits = 0;
20046 //===//
20047 }
20048 else if (state.head) {
20049 state.head.extra = null/*Z_NULL*/;
20050 }
20051 state.mode = EXTRA;
20052 /* falls through */
20053 case EXTRA:
20054 if (state.flags & 0x0400) {
20055 copy = state.length;
20056 if (copy > have) { copy = have; }
20057 if (copy) {
20058 if (state.head) {
20059 len = state.head.extra_len - state.length;
20060 if (!state.head.extra) {
20061 // Use untyped array for more convenient processing later
20062 state.head.extra = new Array(state.head.extra_len);
20063 }
20064 arraySet(
20065 state.head.extra,
20066 input,
20067 next,
20068 // extra field is limited to 65536 bytes
20069 // - no need for additional size check
20070 copy,
20071 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
20072 len
20073 );
20074 //zmemcpy(state.head.extra + len, next,
20075 // len + copy > state.head.extra_max ?
20076 // state.head.extra_max - len : copy);
20077 }
20078 if (state.flags & 0x0200) {
20079 state.check = crc32(state.check, input, copy, next);
20080 }
20081 have -= copy;
20082 next += copy;
20083 state.length -= copy;
20084 }
20085 if (state.length) { break inf_leave; }
20086 }
20087 state.length = 0;
20088 state.mode = NAME;
20089 /* falls through */
20090 case NAME:
20091 if (state.flags & 0x0800) {
20092 if (have === 0) { break inf_leave; }
20093 copy = 0;
20094 do {
20095 // TODO: 2 or 1 bytes?
20096 len = input[next + copy++];
20097 /* use constant limit because in js we should not preallocate memory */
20098 if (state.head && len &&
20099 (state.length < 65536 /*state.head.name_max*/)) {
20100 state.head.name += String.fromCharCode(len);
20101 }
20102 } while (len && copy < have);
20103
20104 if (state.flags & 0x0200) {
20105 state.check = crc32(state.check, input, copy, next);
20106 }
20107 have -= copy;
20108 next += copy;
20109 if (len) { break inf_leave; }
20110 }
20111 else if (state.head) {
20112 state.head.name = null;
20113 }
20114 state.length = 0;
20115 state.mode = COMMENT;
20116 /* falls through */
20117 case COMMENT:
20118 if (state.flags & 0x1000) {
20119 if (have === 0) { break inf_leave; }
20120 copy = 0;
20121 do {
20122 len = input[next + copy++];
20123 /* use constant limit because in js we should not preallocate memory */
20124 if (state.head && len &&
20125 (state.length < 65536 /*state.head.comm_max*/)) {
20126 state.head.comment += String.fromCharCode(len);
20127 }
20128 } while (len && copy < have);
20129 if (state.flags & 0x0200) {
20130 state.check = crc32(state.check, input, copy, next);
20131 }
20132 have -= copy;
20133 next += copy;
20134 if (len) { break inf_leave; }
20135 }
20136 else if (state.head) {
20137 state.head.comment = null;
20138 }
20139 state.mode = HCRC;
20140 /* falls through */
20141 case HCRC:
20142 if (state.flags & 0x0200) {
20143 //=== NEEDBITS(16); */
20144 while (bits < 16) {
20145 if (have === 0) { break inf_leave; }
20146 have--;
20147 hold += input[next++] << bits;
20148 bits += 8;
20149 }
20150 //===//
20151 if (hold !== (state.check & 0xffff)) {
20152 strm.msg = 'header crc mismatch';
20153 state.mode = BAD$1;
20154 break;
20155 }
20156 //=== INITBITS();
20157 hold = 0;
20158 bits = 0;
20159 //===//
20160 }
20161 if (state.head) {
20162 state.head.hcrc = ((state.flags >> 9) & 1);
20163 state.head.done = true;
20164 }
20165 strm.adler = state.check = 0;
20166 state.mode = TYPE$1;
20167 break;
20168 case DICTID:
20169 //=== NEEDBITS(32); */
20170 while (bits < 32) {
20171 if (have === 0) { break inf_leave; }
20172 have--;
20173 hold += input[next++] << bits;
20174 bits += 8;
20175 }
20176 //===//
20177 strm.adler = state.check = zswap32(hold);
20178 //=== INITBITS();
20179 hold = 0;
20180 bits = 0;
20181 //===//
20182 state.mode = DICT;
20183 /* falls through */
20184 case DICT:
20185 if (state.havedict === 0) {
20186 //--- RESTORE() ---
20187 strm.next_out = put;
20188 strm.avail_out = left;
20189 strm.next_in = next;
20190 strm.avail_in = have;
20191 state.hold = hold;
20192 state.bits = bits;
20193 //---
20194 return Z_NEED_DICT;
20195 }
20196 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
20197 state.mode = TYPE$1;
20198 /* falls through */
20199 case TYPE$1:
20200 if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
20201 /* falls through */
20202 case TYPEDO:
20203 if (state.last) {
20204 //--- BYTEBITS() ---//
20205 hold >>>= bits & 7;
20206 bits -= bits & 7;
20207 //---//
20208 state.mode = CHECK;
20209 break;
20210 }
20211 //=== NEEDBITS(3); */
20212 while (bits < 3) {
20213 if (have === 0) { break inf_leave; }
20214 have--;
20215 hold += input[next++] << bits;
20216 bits += 8;
20217 }
20218 //===//
20219 state.last = (hold & 0x01)/*BITS(1)*/;
20220 //--- DROPBITS(1) ---//
20221 hold >>>= 1;
20222 bits -= 1;
20223 //---//
20224
20225 switch ((hold & 0x03)/*BITS(2)*/) {
20226 case 0: /* stored block */
20227 //Tracev((stderr, "inflate: stored block%s\n",
20228 // state.last ? " (last)" : ""));
20229 state.mode = STORED;
20230 break;
20231 case 1: /* fixed block */
20232 fixedtables(state);
20233 //Tracev((stderr, "inflate: fixed codes block%s\n",
20234 // state.last ? " (last)" : ""));
20235 state.mode = LEN_; /* decode codes */
20236 if (flush === Z_TREES) {
20237 //--- DROPBITS(2) ---//
20238 hold >>>= 2;
20239 bits -= 2;
20240 //---//
20241 break inf_leave;
20242 }
20243 break;
20244 case 2: /* dynamic block */
20245 //Tracev((stderr, "inflate: dynamic codes block%s\n",
20246 // state.last ? " (last)" : ""));
20247 state.mode = TABLE;
20248 break;
20249 case 3:
20250 strm.msg = 'invalid block type';
20251 state.mode = BAD$1;
20252 }
20253 //--- DROPBITS(2) ---//
20254 hold >>>= 2;
20255 bits -= 2;
20256 //---//
20257 break;
20258 case STORED:
20259 //--- BYTEBITS() ---// /* go to byte boundary */
20260 hold >>>= bits & 7;
20261 bits -= bits & 7;
20262 //---//
20263 //=== NEEDBITS(32); */
20264 while (bits < 32) {
20265 if (have === 0) { break inf_leave; }
20266 have--;
20267 hold += input[next++] << bits;
20268 bits += 8;
20269 }
20270 //===//
20271 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
20272 strm.msg = 'invalid stored block lengths';
20273 state.mode = BAD$1;
20274 break;
20275 }
20276 state.length = hold & 0xffff;
20277 //Tracev((stderr, "inflate: stored length %u\n",
20278 // state.length));
20279 //=== INITBITS();
20280 hold = 0;
20281 bits = 0;
20282 //===//
20283 state.mode = COPY_;
20284 if (flush === Z_TREES) { break inf_leave; }
20285 /* falls through */
20286 case COPY_:
20287 state.mode = COPY;
20288 /* falls through */
20289 case COPY:
20290 copy = state.length;
20291 if (copy) {
20292 if (copy > have) { copy = have; }
20293 if (copy > left) { copy = left; }
20294 if (copy === 0) { break inf_leave; }
20295 //--- zmemcpy(put, next, copy); ---
20296 arraySet(output, input, next, copy, put);
20297 //---//
20298 have -= copy;
20299 next += copy;
20300 left -= copy;
20301 put += copy;
20302 state.length -= copy;
20303 break;
20304 }
20305 //Tracev((stderr, "inflate: stored end\n"));
20306 state.mode = TYPE$1;
20307 break;
20308 case TABLE:
20309 //=== NEEDBITS(14); */
20310 while (bits < 14) {
20311 if (have === 0) { break inf_leave; }
20312 have--;
20313 hold += input[next++] << bits;
20314 bits += 8;
20315 }
20316 //===//
20317 state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
20318 //--- DROPBITS(5) ---//
20319 hold >>>= 5;
20320 bits -= 5;
20321 //---//
20322 state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
20323 //--- DROPBITS(5) ---//
20324 hold >>>= 5;
20325 bits -= 5;
20326 //---//
20327 state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
20328 //--- DROPBITS(4) ---//
20329 hold >>>= 4;
20330 bits -= 4;
20331 //---//
20332 //#ifndef PKZIP_BUG_WORKAROUND
20333 if (state.nlen > 286 || state.ndist > 30) {
20334 strm.msg = 'too many length or distance symbols';
20335 state.mode = BAD$1;
20336 break;
20337 }
20338 //#endif
20339 //Tracev((stderr, "inflate: table sizes ok\n"));
20340 state.have = 0;
20341 state.mode = LENLENS;
20342 /* falls through */
20343 case LENLENS:
20344 while (state.have < state.ncode) {
20345 //=== NEEDBITS(3);
20346 while (bits < 3) {
20347 if (have === 0) { break inf_leave; }
20348 have--;
20349 hold += input[next++] << bits;
20350 bits += 8;
20351 }
20352 //===//
20353 state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
20354 //--- DROPBITS(3) ---//
20355 hold >>>= 3;
20356 bits -= 3;
20357 //---//
20358 }
20359 while (state.have < 19) {
20360 state.lens[order[state.have++]] = 0;
20361 }
20362 // We have separate tables & no pointers. 2 commented lines below not needed.
20363 //state.next = state.codes;
20364 //state.lencode = state.next;
20365 // Switch to use dynamic table
20366 state.lencode = state.lendyn;
20367 state.lenbits = 7;
20368
20369 opts = { bits: state.lenbits };
20370 ret = inflate_table(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts);
20371 state.lenbits = opts.bits;
20372
20373 if (ret) {
20374 strm.msg = 'invalid code lengths set';
20375 state.mode = BAD$1;
20376 break;
20377 }
20378 //Tracev((stderr, "inflate: code lengths ok\n"));
20379 state.have = 0;
20380 state.mode = CODELENS;
20381 /* falls through */
20382 case CODELENS:
20383 while (state.have < state.nlen + state.ndist) {
20384 for (;;) {
20385 here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
20386 here_bits = here >>> 24;
20387 here_op = (here >>> 16) & 0xff;
20388 here_val = here & 0xffff;
20389
20390 if ((here_bits) <= bits) { break; }
20391 //--- PULLBYTE() ---//
20392 if (have === 0) { break inf_leave; }
20393 have--;
20394 hold += input[next++] << bits;
20395 bits += 8;
20396 //---//
20397 }
20398 if (here_val < 16) {
20399 //--- DROPBITS(here.bits) ---//
20400 hold >>>= here_bits;
20401 bits -= here_bits;
20402 //---//
20403 state.lens[state.have++] = here_val;
20404 }
20405 else {
20406 if (here_val === 16) {
20407 //=== NEEDBITS(here.bits + 2);
20408 n = here_bits + 2;
20409 while (bits < n) {
20410 if (have === 0) { break inf_leave; }
20411 have--;
20412 hold += input[next++] << bits;
20413 bits += 8;
20414 }
20415 //===//
20416 //--- DROPBITS(here.bits) ---//
20417 hold >>>= here_bits;
20418 bits -= here_bits;
20419 //---//
20420 if (state.have === 0) {
20421 strm.msg = 'invalid bit length repeat';
20422 state.mode = BAD$1;
20423 break;
20424 }
20425 len = state.lens[state.have - 1];
20426 copy = 3 + (hold & 0x03);//BITS(2);
20427 //--- DROPBITS(2) ---//
20428 hold >>>= 2;
20429 bits -= 2;
20430 //---//
20431 }
20432 else if (here_val === 17) {
20433 //=== NEEDBITS(here.bits + 3);
20434 n = here_bits + 3;
20435 while (bits < n) {
20436 if (have === 0) { break inf_leave; }
20437 have--;
20438 hold += input[next++] << bits;
20439 bits += 8;
20440 }
20441 //===//
20442 //--- DROPBITS(here.bits) ---//
20443 hold >>>= here_bits;
20444 bits -= here_bits;
20445 //---//
20446 len = 0;
20447 copy = 3 + (hold & 0x07);//BITS(3);
20448 //--- DROPBITS(3) ---//
20449 hold >>>= 3;
20450 bits -= 3;
20451 //---//
20452 }
20453 else {
20454 //=== NEEDBITS(here.bits + 7);
20455 n = here_bits + 7;
20456 while (bits < n) {
20457 if (have === 0) { break inf_leave; }
20458 have--;
20459 hold += input[next++] << bits;
20460 bits += 8;
20461 }
20462 //===//
20463 //--- DROPBITS(here.bits) ---//
20464 hold >>>= here_bits;
20465 bits -= here_bits;
20466 //---//
20467 len = 0;
20468 copy = 11 + (hold & 0x7f);//BITS(7);
20469 //--- DROPBITS(7) ---//
20470 hold >>>= 7;
20471 bits -= 7;
20472 //---//
20473 }
20474 if (state.have + copy > state.nlen + state.ndist) {
20475 strm.msg = 'invalid bit length repeat';
20476 state.mode = BAD$1;
20477 break;
20478 }
20479 while (copy--) {
20480 state.lens[state.have++] = len;
20481 }
20482 }
20483 }
20484
20485 /* handle error breaks in while */
20486 if (state.mode === BAD$1) { break; }
20487
20488 /* check for end-of-block code (better have one) */
20489 if (state.lens[256] === 0) {
20490 strm.msg = 'invalid code -- missing end-of-block';
20491 state.mode = BAD$1;
20492 break;
20493 }
20494
20495 /* build code tables -- note: do not change the lenbits or distbits
20496 values here (9 and 6) without reading the comments in inftrees.h
20497 concerning the ENOUGH constants, which depend on those values */
20498 state.lenbits = 9;
20499
20500 opts = { bits: state.lenbits };
20501 ret = inflate_table(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
20502 // We have separate tables & no pointers. 2 commented lines below not needed.
20503 // state.next_index = opts.table_index;
20504 state.lenbits = opts.bits;
20505 // state.lencode = state.next;
20506
20507 if (ret) {
20508 strm.msg = 'invalid literal/lengths set';
20509 state.mode = BAD$1;
20510 break;
20511 }
20512
20513 state.distbits = 6;
20514 //state.distcode.copy(state.codes);
20515 // Switch to use dynamic table
20516 state.distcode = state.distdyn;
20517 opts = { bits: state.distbits };
20518 ret = inflate_table(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
20519 // We have separate tables & no pointers. 2 commented lines below not needed.
20520 // state.next_index = opts.table_index;
20521 state.distbits = opts.bits;
20522 // state.distcode = state.next;
20523
20524 if (ret) {
20525 strm.msg = 'invalid distances set';
20526 state.mode = BAD$1;
20527 break;
20528 }
20529 //Tracev((stderr, 'inflate: codes ok\n'));
20530 state.mode = LEN_;
20531 if (flush === Z_TREES) { break inf_leave; }
20532 /* falls through */
20533 case LEN_:
20534 state.mode = LEN;
20535 /* falls through */
20536 case LEN:
20537 if (have >= 6 && left >= 258) {
20538 //--- RESTORE() ---
20539 strm.next_out = put;
20540 strm.avail_out = left;
20541 strm.next_in = next;
20542 strm.avail_in = have;
20543 state.hold = hold;
20544 state.bits = bits;
20545 //---
20546 inflate_fast(strm, _out);
20547 //--- LOAD() ---
20548 put = strm.next_out;
20549 output = strm.output;
20550 left = strm.avail_out;
20551 next = strm.next_in;
20552 input = strm.input;
20553 have = strm.avail_in;
20554 hold = state.hold;
20555 bits = state.bits;
20556 //---
20557
20558 if (state.mode === TYPE$1) {
20559 state.back = -1;
20560 }
20561 break;
20562 }
20563 state.back = 0;
20564 for (;;) {
20565 here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
20566 here_bits = here >>> 24;
20567 here_op = (here >>> 16) & 0xff;
20568 here_val = here & 0xffff;
20569
20570 if (here_bits <= bits) { break; }
20571 //--- PULLBYTE() ---//
20572 if (have === 0) { break inf_leave; }
20573 have--;
20574 hold += input[next++] << bits;
20575 bits += 8;
20576 //---//
20577 }
20578 if (here_op && (here_op & 0xf0) === 0) {
20579 last_bits = here_bits;
20580 last_op = here_op;
20581 last_val = here_val;
20582 for (;;) {
20583 here = state.lencode[last_val +
20584 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
20585 here_bits = here >>> 24;
20586 here_op = (here >>> 16) & 0xff;
20587 here_val = here & 0xffff;
20588
20589 if ((last_bits + here_bits) <= bits) { break; }
20590 //--- PULLBYTE() ---//
20591 if (have === 0) { break inf_leave; }
20592 have--;
20593 hold += input[next++] << bits;
20594 bits += 8;
20595 //---//
20596 }
20597 //--- DROPBITS(last.bits) ---//
20598 hold >>>= last_bits;
20599 bits -= last_bits;
20600 //---//
20601 state.back += last_bits;
20602 }
20603 //--- DROPBITS(here.bits) ---//
20604 hold >>>= here_bits;
20605 bits -= here_bits;
20606 //---//
20607 state.back += here_bits;
20608 state.length = here_val;
20609 if (here_op === 0) {
20610 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
20611 // "inflate: literal '%c'\n" :
20612 // "inflate: literal 0x%02x\n", here.val));
20613 state.mode = LIT;
20614 break;
20615 }
20616 if (here_op & 32) {
20617 //Tracevv((stderr, "inflate: end of block\n"));
20618 state.back = -1;
20619 state.mode = TYPE$1;
20620 break;
20621 }
20622 if (here_op & 64) {
20623 strm.msg = 'invalid literal/length code';
20624 state.mode = BAD$1;
20625 break;
20626 }
20627 state.extra = here_op & 15;
20628 state.mode = LENEXT;
20629 /* falls through */
20630 case LENEXT:
20631 if (state.extra) {
20632 //=== NEEDBITS(state.extra);
20633 n = state.extra;
20634 while (bits < n) {
20635 if (have === 0) { break inf_leave; }
20636 have--;
20637 hold += input[next++] << bits;
20638 bits += 8;
20639 }
20640 //===//
20641 state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
20642 //--- DROPBITS(state.extra) ---//
20643 hold >>>= state.extra;
20644 bits -= state.extra;
20645 //---//
20646 state.back += state.extra;
20647 }
20648 //Tracevv((stderr, "inflate: length %u\n", state.length));
20649 state.was = state.length;
20650 state.mode = DIST;
20651 /* falls through */
20652 case DIST:
20653 for (;;) {
20654 here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
20655 here_bits = here >>> 24;
20656 here_op = (here >>> 16) & 0xff;
20657 here_val = here & 0xffff;
20658
20659 if ((here_bits) <= bits) { break; }
20660 //--- PULLBYTE() ---//
20661 if (have === 0) { break inf_leave; }
20662 have--;
20663 hold += input[next++] << bits;
20664 bits += 8;
20665 //---//
20666 }
20667 if ((here_op & 0xf0) === 0) {
20668 last_bits = here_bits;
20669 last_op = here_op;
20670 last_val = here_val;
20671 for (;;) {
20672 here = state.distcode[last_val +
20673 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
20674 here_bits = here >>> 24;
20675 here_op = (here >>> 16) & 0xff;
20676 here_val = here & 0xffff;
20677
20678 if ((last_bits + here_bits) <= bits) { break; }
20679 //--- PULLBYTE() ---//
20680 if (have === 0) { break inf_leave; }
20681 have--;
20682 hold += input[next++] << bits;
20683 bits += 8;
20684 //---//
20685 }
20686 //--- DROPBITS(last.bits) ---//
20687 hold >>>= last_bits;
20688 bits -= last_bits;
20689 //---//
20690 state.back += last_bits;
20691 }
20692 //--- DROPBITS(here.bits) ---//
20693 hold >>>= here_bits;
20694 bits -= here_bits;
20695 //---//
20696 state.back += here_bits;
20697 if (here_op & 64) {
20698 strm.msg = 'invalid distance code';
20699 state.mode = BAD$1;
20700 break;
20701 }
20702 state.offset = here_val;
20703 state.extra = (here_op) & 15;
20704 state.mode = DISTEXT;
20705 /* falls through */
20706 case DISTEXT:
20707 if (state.extra) {
20708 //=== NEEDBITS(state.extra);
20709 n = state.extra;
20710 while (bits < n) {
20711 if (have === 0) { break inf_leave; }
20712 have--;
20713 hold += input[next++] << bits;
20714 bits += 8;
20715 }
20716 //===//
20717 state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
20718 //--- DROPBITS(state.extra) ---//
20719 hold >>>= state.extra;
20720 bits -= state.extra;
20721 //---//
20722 state.back += state.extra;
20723 }
20724 //#ifdef INFLATE_STRICT
20725 if (state.offset > state.dmax) {
20726 strm.msg = 'invalid distance too far back';
20727 state.mode = BAD$1;
20728 break;
20729 }
20730 //#endif
20731 //Tracevv((stderr, "inflate: distance %u\n", state.offset));
20732 state.mode = MATCH;
20733 /* falls through */
20734 case MATCH:
20735 if (left === 0) { break inf_leave; }
20736 copy = _out - left;
20737 if (state.offset > copy) { /* copy from window */
20738 copy = state.offset - copy;
20739 if (copy > state.whave) {
20740 if (state.sane) {
20741 strm.msg = 'invalid distance too far back';
20742 state.mode = BAD$1;
20743 break;
20744 }
20745 // (!) This block is disabled in zlib defaults,
20746 // don't enable it for binary compatibility
20747 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
20748 // Trace((stderr, "inflate.c too far\n"));
20749 // copy -= state.whave;
20750 // if (copy > state.length) { copy = state.length; }
20751 // if (copy > left) { copy = left; }
20752 // left -= copy;
20753 // state.length -= copy;
20754 // do {
20755 // output[put++] = 0;
20756 // } while (--copy);
20757 // if (state.length === 0) { state.mode = LEN; }
20758 // break;
20759 //#endif
20760 }
20761 if (copy > state.wnext) {
20762 copy -= state.wnext;
20763 from = state.wsize - copy;
20764 }
20765 else {
20766 from = state.wnext - copy;
20767 }
20768 if (copy > state.length) { copy = state.length; }
20769 from_source = state.window;
20770 }
20771 else { /* copy from output */
20772 from_source = output;
20773 from = put - state.offset;
20774 copy = state.length;
20775 }
20776 if (copy > left) { copy = left; }
20777 left -= copy;
20778 state.length -= copy;
20779 do {
20780 output[put++] = from_source[from++];
20781 } while (--copy);
20782 if (state.length === 0) { state.mode = LEN; }
20783 break;
20784 case LIT:
20785 if (left === 0) { break inf_leave; }
20786 output[put++] = state.length;
20787 left--;
20788 state.mode = LEN;
20789 break;
20790 case CHECK:
20791 if (state.wrap) {
20792 //=== NEEDBITS(32);
20793 while (bits < 32) {
20794 if (have === 0) { break inf_leave; }
20795 have--;
20796 // Use '|' instead of '+' to make sure that result is signed
20797 hold |= input[next++] << bits;
20798 bits += 8;
20799 }
20800 //===//
20801 _out -= left;
20802 strm.total_out += _out;
20803 state.total += _out;
20804 if (_out) {
20805 strm.adler = state.check =
20806 /*UPDATE(state.check, put - _out, _out);*/
20807 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
20808
20809 }
20810 _out = left;
20811 // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
20812 if ((state.flags ? hold : zswap32(hold)) !== state.check) {
20813 strm.msg = 'incorrect data check';
20814 state.mode = BAD$1;
20815 break;
20816 }
20817 //=== INITBITS();
20818 hold = 0;
20819 bits = 0;
20820 //===//
20821 //Tracev((stderr, "inflate: check matches trailer\n"));
20822 }
20823 state.mode = LENGTH;
20824 /* falls through */
20825 case LENGTH:
20826 if (state.wrap && state.flags) {
20827 //=== NEEDBITS(32);
20828 while (bits < 32) {
20829 if (have === 0) { break inf_leave; }
20830 have--;
20831 hold += input[next++] << bits;
20832 bits += 8;
20833 }
20834 //===//
20835 if (hold !== (state.total & 0xffffffff)) {
20836 strm.msg = 'incorrect length check';
20837 state.mode = BAD$1;
20838 break;
20839 }
20840 //=== INITBITS();
20841 hold = 0;
20842 bits = 0;
20843 //===//
20844 //Tracev((stderr, "inflate: length matches trailer\n"));
20845 }
20846 state.mode = DONE;
20847 /* falls through */
20848 case DONE:
20849 ret = Z_STREAM_END;
20850 break inf_leave;
20851 case BAD$1:
20852 ret = Z_DATA_ERROR;
20853 break inf_leave;
20854 // case MEM:
20855 // return Z_MEM_ERROR;
20856 case SYNC:
20857 /* falls through */
20858 default:
20859 return Z_STREAM_ERROR;
20860 }
20861 }
20862
20863 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
20864
20865 /*
20866 Return from inflate(), updating the total counts and the check value.
20867 If there was no progress during the inflate() call, return a buffer
20868 error. Call updatewindow() to create and/or update the window state.
20869 Note: a memory error from inflate() is non-recoverable.
20870 */
20871
20872 //--- RESTORE() ---
20873 strm.next_out = put;
20874 strm.avail_out = left;
20875 strm.next_in = next;
20876 strm.avail_in = have;
20877 state.hold = hold;
20878 state.bits = bits;
20879 //---
20880
20881 if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 &&
20882 (state.mode < CHECK || flush !== Z_FINISH))) {
20883 if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;
20884 }
20885 _in -= strm.avail_in;
20886 _out -= strm.avail_out;
20887 strm.total_in += _in;
20888 strm.total_out += _out;
20889 state.total += _out;
20890 if (state.wrap && _out) {
20891 strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
20892 (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
20893 }
20894 strm.data_type = state.bits + (state.last ? 64 : 0) +
20895 (state.mode === TYPE$1 ? 128 : 0) +
20896 (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
20897 if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
20898 ret = Z_BUF_ERROR;
20899 }
20900 return ret;
20901 }
20902
20903 function inflateEnd(strm) {
20904
20905 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
20906 return Z_STREAM_ERROR;
20907 }
20908
20909 const state = strm.state;
20910 if (state.window) {
20911 state.window = null;
20912 }
20913 strm.state = null;
20914 return Z_OK;
20915 }
20916
20917 function inflateGetHeader(strm, head) {
20918 let state;
20919
20920 /* check state */
20921 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
20922 state = strm.state;
20923 if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
20924
20925 /* save header structure */
20926 state.head = head;
20927 head.done = false;
20928 return Z_OK;
20929 }
20930
20931 function inflateSetDictionary(strm, dictionary) {
20932 const dictLength = dictionary.length;
20933
20934 let state;
20935 let dictid;
20936
20937 /* check state */
20938 if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
20939 state = strm.state;
20940
20941 if (state.wrap !== 0 && state.mode !== DICT) {
20942 return Z_STREAM_ERROR;
20943 }
20944
20945 /* check for correct dictionary identifier */
20946 if (state.mode === DICT) {
20947 dictid = 1; /* adler32(0, null, 0)*/
20948 /* dictid = adler32(dictid, dictionary, dictLength); */
20949 dictid = adler32(dictid, dictionary, dictLength, 0);
20950 if (dictid !== state.check) {
20951 return Z_DATA_ERROR;
20952 }
20953 }
20954 /* copy dictionary to window using updatewindow(), which will amend the
20955 existing dictionary if appropriate */
20956 updatewindow(strm, dictionary, dictLength, dictLength);
20957 // if (ret) {
20958 // state.mode = MEM;
20959 // return Z_MEM_ERROR;
20960 // }
20961 state.havedict = 1;
20962 // Tracev((stderr, "inflate: dictionary set\n"));
20963 return Z_OK;
20964 }
20965
20966 /* Not implemented
20967 exports.inflateCopy = inflateCopy;
20968 exports.inflateGetDictionary = inflateGetDictionary;
20969 exports.inflateMark = inflateMark;
20970 exports.inflatePrime = inflatePrime;
20971 exports.inflateSync = inflateSync;
20972 exports.inflateSyncPoint = inflateSyncPoint;
20973 exports.inflateUndermine = inflateUndermine;
20974 */
20975
20976 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
20977 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
20978 //
20979 // This software is provided 'as-is', without any express or implied
20980 // warranty. In no event will the authors be held liable for any damages
20981 // arising from the use of this software.
20982 //
20983 // Permission is granted to anyone to use this software for any purpose,
20984 // including commercial applications, and to alter it and redistribute it
20985 // freely, subject to the following restrictions:
20986 //
20987 // 1. The origin of this software must not be misrepresented; you must not
20988 // claim that you wrote the original software. If you use this software
20989 // in a product, an acknowledgment in the product documentation would be
20990 // appreciated but is not required.
20991 // 2. Altered source versions must be plainly marked as such, and must not be
20992 // misrepresented as being the original software.
20993 // 3. This notice may not be removed or altered from any source distribution.
20994
20995 class GZheader {
20996 constructor() {
20997 /* true if compressed data believed to be text */
20998 this.text = 0;
20999 /* modification time */
21000 this.time = 0;
21001 /* extra flags (not used when writing a gzip file) */
21002 this.xflags = 0;
21003 /* operating system */
21004 this.os = 0;
21005 /* pointer to extra field or Z_NULL if none */
21006 this.extra = null;
21007 /* extra field length (valid if extra != Z_NULL) */
21008 this.extra_len = 0; // Actually, we don't need it in JS,
21009 // but leave for few code modifications
21010
21011 //
21012 // Setup limits is not necessary because in js we should not preallocate memory
21013 // for inflate use constant limit in 65536 bytes
21014 //
21015
21016 /* space at extra (only when reading header) */
21017 // this.extra_max = 0;
21018 /* pointer to zero-terminated file name or Z_NULL */
21019 this.name = '';
21020 /* space at name (only when reading header) */
21021 // this.name_max = 0;
21022 /* pointer to zero-terminated comment or Z_NULL */
21023 this.comment = '';
21024 /* space at comment (only when reading header) */
21025 // this.comm_max = 0;
21026 /* true if there was or will be a header crc */
21027 this.hcrc = 0;
21028 /* true when done reading gzip header (not used when writing a gzip file) */
21029 this.done = false;
21030 }
21031 }
21032
21033 /**
21034 * class Inflate
21035 *
21036 * Generic JS-style wrapper for zlib calls. If you don't need
21037 * streaming behaviour - use more simple functions: [[inflate]]
21038 * and [[inflateRaw]].
21039 **/
21040
21041 /* internal
21042 * inflate.chunks -> Array
21043 *
21044 * Chunks of output data, if [[Inflate#onData]] not overridden.
21045 **/
21046
21047 /**
21048 * Inflate.result -> Uint8Array|Array|String
21049 *
21050 * Uncompressed result, generated by default [[Inflate#onData]]
21051 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
21052 * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
21053 * push a chunk with explicit flush (call [[Inflate#push]] with
21054 * `Z_SYNC_FLUSH` param).
21055 **/
21056
21057 /**
21058 * Inflate.err -> Number
21059 *
21060 * Error code after inflate finished. 0 (Z_OK) on success.
21061 * Should be checked if broken data possible.
21062 **/
21063
21064 /**
21065 * Inflate.msg -> String
21066 *
21067 * Error message, if [[Inflate.err]] != 0
21068 **/
21069
21070
21071 /**
21072 * new Inflate(options)
21073 * - options (Object): zlib inflate options.
21074 *
21075 * Creates new inflator instance with specified params. Throws exception
21076 * on bad params. Supported options:
21077 *
21078 * - `windowBits`
21079 * - `dictionary`
21080 *
21081 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
21082 * for more information on these.
21083 *
21084 * Additional options, for internal needs:
21085 *
21086 * - `chunkSize` - size of generated data chunks (16K by default)
21087 * - `raw` (Boolean) - do raw inflate
21088 * - `to` (String) - if equal to 'string', then result will be converted
21089 * from utf8 to utf16 (javascript) string. When string output requested,
21090 * chunk length can differ from `chunkSize`, depending on content.
21091 *
21092 * By default, when no options set, autodetect deflate/gzip data format via
21093 * wrapper header.
21094 *
21095 * ##### Example:
21096 *
21097 * ```javascript
21098 * var pako = void('pako')
21099 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
21100 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
21101 *
21102 * var inflate = new pako.Inflate({ level: 3});
21103 *
21104 * inflate.push(chunk1, false);
21105 * inflate.push(chunk2, true); // true -> last chunk
21106 *
21107 * if (inflate.err) { throw new Error(inflate.err); }
21108 *
21109 * console.log(inflate.result);
21110 * ```
21111 **/
21112 class Inflate {
21113 constructor(options) {
21114 this.options = {
21115 chunkSize: 16384,
21116 windowBits: 0,
21117 ...(options || {})
21118 };
21119
21120 const opt = this.options;
21121
21122 // Force window size for `raw` data, if not set directly,
21123 // because we have no header for autodetect.
21124 if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
21125 opt.windowBits = -opt.windowBits;
21126 if (opt.windowBits === 0) { opt.windowBits = -15; }
21127 }
21128
21129 // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
21130 if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
21131 !(options && options.windowBits)) {
21132 opt.windowBits += 32;
21133 }
21134
21135 // Gzip header has no info about windows size, we can do autodetect only
21136 // for deflate. So, if window size not set, force it to max when gzip possible
21137 if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
21138 // bit 3 (16) -> gzipped data
21139 // bit 4 (32) -> autodetect gzip/deflate
21140 if ((opt.windowBits & 15) === 0) {
21141 opt.windowBits |= 15;
21142 }
21143 }
21144
21145 this.err = 0; // error code, if happens (0 = Z_OK)
21146 this.msg = ''; // error message
21147 this.ended = false; // used to avoid multiple onEnd() calls
21148 this.chunks = []; // chunks of compressed data
21149
21150 this.strm = new ZStream();
21151 this.strm.avail_out = 0;
21152
21153 let status = inflateInit2(
21154 this.strm,
21155 opt.windowBits
21156 );
21157
21158 if (status !== Z_OK) {
21159 throw new Error(msg[status]);
21160 }
21161
21162 this.header = new GZheader();
21163
21164 inflateGetHeader(this.strm, this.header);
21165
21166 // Setup dictionary
21167 if (opt.dictionary) {
21168 // Convert data if needed
21169 if (typeof opt.dictionary === 'string') {
21170 opt.dictionary = string2buf(opt.dictionary);
21171 } else if (opt.dictionary instanceof ArrayBuffer) {
21172 opt.dictionary = new Uint8Array(opt.dictionary);
21173 }
21174 if (opt.raw) { //In raw mode we need to set the dictionary early
21175 status = inflateSetDictionary(this.strm, opt.dictionary);
21176 if (status !== Z_OK) {
21177 throw new Error(msg[status]);
21178 }
21179 }
21180 }
21181 }
21182 /**
21183 * Inflate#push(data[, mode]) -> Boolean
21184 * - data (Uint8Array|Array|ArrayBuffer|String): input data
21185 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
21186 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
21187 *
21188 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
21189 * new output chunks. Returns `true` on success. The last data block must have
21190 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
21191 * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
21192 * can use mode Z_SYNC_FLUSH, keeping the decompression context.
21193 *
21194 * On fail call [[Inflate#onEnd]] with error code and return false.
21195 *
21196 * We strongly recommend to use `Uint8Array` on input for best speed (output
21197 * format is detected automatically). Also, don't skip last param and always
21198 * use the same type in your code (boolean or number). That will improve JS speed.
21199 *
21200 * For regular `Array`-s make sure all elements are [0..255].
21201 *
21202 * ##### Example
21203 *
21204 * ```javascript
21205 * push(chunk, false); // push one of data chunks
21206 * ...
21207 * push(chunk, true); // push last chunk
21208 * ```
21209 **/
21210 push(data, mode) {
21211 const { strm, options: { chunkSize, dictionary } } = this;
21212 let status, _mode;
21213
21214 // Flag to properly process Z_BUF_ERROR on testing inflate call
21215 // when we check that all output data was flushed.
21216 let allowBufError = false;
21217
21218 if (this.ended) { return false; }
21219 _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
21220
21221 // Convert data if needed
21222 if (typeof data === 'string') {
21223 // Only binary strings can be decompressed on practice
21224 strm.input = binstring2buf(data);
21225 } else if (data instanceof ArrayBuffer) {
21226 strm.input = new Uint8Array(data);
21227 } else {
21228 strm.input = data;
21229 }
21230
21231 strm.next_in = 0;
21232 strm.avail_in = strm.input.length;
21233
21234 do {
21235 if (strm.avail_out === 0) {
21236 strm.output = new Buf8(chunkSize);
21237 strm.next_out = 0;
21238 strm.avail_out = chunkSize;
21239 }
21240
21241 status = inflate(strm, Z_NO_FLUSH); /* no bad return value */
21242
21243 if (status === Z_NEED_DICT && dictionary) {
21244 status = inflateSetDictionary(this.strm, dictionary);
21245 }
21246
21247 if (status === Z_BUF_ERROR && allowBufError === true) {
21248 status = Z_OK;
21249 allowBufError = false;
21250 }
21251
21252 if (status !== Z_STREAM_END && status !== Z_OK) {
21253 this.onEnd(status);
21254 this.ended = true;
21255 return false;
21256 }
21257
21258 if (strm.next_out) {
21259 if (strm.avail_out === 0 || status === Z_STREAM_END || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
21260 this.onData(shrinkBuf(strm.output, strm.next_out));
21261 }
21262 }
21263
21264 // When no more input data, we should check that internal inflate buffers
21265 // are flushed. The only way to do it when avail_out = 0 - run one more
21266 // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
21267 // Here we set flag to process this error properly.
21268 //
21269 // NOTE. Deflate does not return error in this case and does not needs such
21270 // logic.
21271 if (strm.avail_in === 0 && strm.avail_out === 0) {
21272 allowBufError = true;
21273 }
21274
21275 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
21276
21277 if (status === Z_STREAM_END) {
21278 _mode = Z_FINISH;
21279 }
21280
21281 // Finalize on the last chunk.
21282 if (_mode === Z_FINISH) {
21283 status = inflateEnd(this.strm);
21284 this.onEnd(status);
21285 this.ended = true;
21286 return status === Z_OK;
21287 }
21288
21289 // callback interim results if Z_SYNC_FLUSH.
21290 if (_mode === Z_SYNC_FLUSH) {
21291 this.onEnd(Z_OK);
21292 strm.avail_out = 0;
21293 return true;
21294 }
21295
21296 return true;
21297 };
21298
21299 /**
21300 * Inflate#onData(chunk) -> Void
21301 * - chunk (Uint8Array|Array|String): output data. Type of array depends
21302 * on js engine support. When string output requested, each chunk
21303 * will be string.
21304 *
21305 * By default, stores data blocks in `chunks[]` property and glue
21306 * those in `onEnd`. Override this handler, if you need another behaviour.
21307 **/
21308 onData(chunk) {
21309 this.chunks.push(chunk);
21310 };
21311
21312
21313
21314 /**
21315 * Inflate#onEnd(status) -> Void
21316 * - status (Number): inflate status. 0 (Z_OK) on success,
21317 * other if not.
21318 *
21319 * Called either after you tell inflate that the input stream is
21320 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
21321 * or if an error happened. By default - join collected chunks,
21322 * free memory and fill `results` / `err` properties.
21323 **/
21324 onEnd(status) {
21325 // On success - join
21326 if (status === Z_OK) {
21327 this.result = flattenChunks(this.chunks);
21328 }
21329 this.chunks = [];
21330 this.err = status;
21331 this.msg = this.strm.msg;
21332 };
21333 }
21334
21335 /*
21336 node-bzip - a pure-javascript Node.JS module for decoding bzip2 data
21337
21338 Copyright (C) 2012 Eli Skeggs
21339
21340 This library is free software; you can redistribute it and/or
21341 modify it under the terms of the GNU Lesser General Public
21342 License as published by the Free Software Foundation; either
21343 version 2.1 of the License, or (at your option) any later version.
21344
21345 This library is distributed in the hope that it will be useful,
21346 but WITHOUT ANY WARRANTY; without even the implied warranty of
21347 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21348 Lesser General Public License for more details.
21349
21350 You should have received a copy of the GNU Lesser General Public
21351 License along with this library; if not, see
21352 http://www.gnu.org/licenses/lgpl-2.1.html
21353
21354 Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).
21355
21356 Based on micro-bunzip by Rob Landley (rob@landley.net).
21357
21358 Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
21359 which also acknowledges contributions by Mike Burrows, David Wheeler,
21360 Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
21361 Robert Sedgewick, and Jon L. Bentley.
21362 */
21363
21364 var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];
21365
21366 // offset in bytes
21367 var BitReader = function(stream) {
21368 this.stream = stream;
21369 this.bitOffset = 0;
21370 this.curByte = 0;
21371 this.hasByte = false;
21372 };
21373
21374 BitReader.prototype._ensureByte = function() {
21375 if (!this.hasByte) {
21376 this.curByte = this.stream.readByte();
21377 this.hasByte = true;
21378 }
21379 };
21380
21381 // reads bits from the buffer
21382 BitReader.prototype.read = function(bits) {
21383 var result = 0;
21384 while (bits > 0) {
21385 this._ensureByte();
21386 var remaining = 8 - this.bitOffset;
21387 // if we're in a byte
21388 if (bits >= remaining) {
21389 result <<= remaining;
21390 result |= BITMASK[remaining] & this.curByte;
21391 this.hasByte = false;
21392 this.bitOffset = 0;
21393 bits -= remaining;
21394 } else {
21395 result <<= bits;
21396 var shift = remaining - bits;
21397 result |= (this.curByte & (BITMASK[bits] << shift)) >> shift;
21398 this.bitOffset += bits;
21399 bits = 0;
21400 }
21401 }
21402 return result;
21403 };
21404
21405 // seek to an arbitrary point in the buffer (expressed in bits)
21406 BitReader.prototype.seek = function(pos) {
21407 var n_bit = pos % 8;
21408 var n_byte = (pos - n_bit) / 8;
21409 this.bitOffset = n_bit;
21410 this.stream.seek(n_byte);
21411 this.hasByte = false;
21412 };
21413
21414 // reads 6 bytes worth of data using the read method
21415 BitReader.prototype.pi = function() {
21416 var buf = new Uint8Array(6), i;
21417 for (i = 0; i < buf.length; i++) {
21418 buf[i] = this.read(8);
21419 }
21420 return bufToHex(buf);
21421 };
21422
21423 function bufToHex(buf) {
21424 return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');
21425 }
21426
21427 var bitreader = BitReader;
21428
21429 /* very simple input/output stream interface */
21430 var Stream = function() {
21431 };
21432
21433 // input streams //////////////
21434 /** Returns the next byte, or -1 for EOF. */
21435 Stream.prototype.readByte = function() {
21436 throw new Error("abstract method readByte() not implemented");
21437 };
21438 /** Attempts to fill the buffer; returns number of bytes read, or
21439 * -1 for EOF. */
21440 Stream.prototype.read = function(buffer, bufOffset, length) {
21441 var bytesRead = 0;
21442 while (bytesRead < length) {
21443 var c = this.readByte();
21444 if (c < 0) { // EOF
21445 return (bytesRead===0) ? -1 : bytesRead;
21446 }
21447 buffer[bufOffset++] = c;
21448 bytesRead++;
21449 }
21450 return bytesRead;
21451 };
21452 Stream.prototype.seek = function(new_pos) {
21453 throw new Error("abstract method seek() not implemented");
21454 };
21455
21456 // output streams ///////////
21457 Stream.prototype.writeByte = function(_byte) {
21458 throw new Error("abstract method readByte() not implemented");
21459 };
21460 Stream.prototype.write = function(buffer, bufOffset, length) {
21461 var i;
21462 for (i=0; i<length; i++) {
21463 this.writeByte(buffer[bufOffset++]);
21464 }
21465 return length;
21466 };
21467 Stream.prototype.flush = function() {
21468 };
21469
21470 var stream = Stream;
21471
21472 /* CRC32, used in Bzip2 implementation.
21473 * This is a port of CRC32.java from the jbzip2 implementation at
21474 * https://code.google.com/p/jbzip2
21475 * which is:
21476 * Copyright (c) 2011 Matthew Francis
21477 *
21478 * Permission is hereby granted, free of charge, to any person
21479 * obtaining a copy of this software and associated documentation
21480 * files (the "Software"), to deal in the Software without
21481 * restriction, including without limitation the rights to use,
21482 * copy, modify, merge, publish, distribute, sublicense, and/or sell
21483 * copies of the Software, and to permit persons to whom the
21484 * Software is furnished to do so, subject to the following
21485 * conditions:
21486 *
21487 * The above copyright notice and this permission notice shall be
21488 * included in all copies or substantial portions of the Software.
21489 *
21490 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21491 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
21492 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21493 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21494 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21495 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21496 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21497 * OTHER DEALINGS IN THE SOFTWARE.
21498 * This JavaScript implementation is:
21499 * Copyright (c) 2013 C. Scott Ananian
21500 * with the same licensing terms as Matthew Francis' original implementation.
21501 */
21502 var crc32$1 = (function() {
21503
21504 /**
21505 * A static CRC lookup table
21506 */
21507 var crc32Lookup = new Uint32Array([
21508 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
21509 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
21510 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
21511 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
21512 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
21513 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
21514 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
21515 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
21516 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
21517 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
21518 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
21519 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
21520 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
21521 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
21522 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
21523 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
21524 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
21525 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
21526 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
21527 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
21528 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
21529 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
21530 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
21531 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
21532 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
21533 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
21534 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
21535 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
21536 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
21537 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
21538 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
21539 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
21540 ]);
21541
21542 var CRC32 = function() {
21543 /**
21544 * The current CRC
21545 */
21546 var crc = 0xffffffff;
21547
21548 /**
21549 * @return The current CRC
21550 */
21551 this.getCRC = function() {
21552 return (~crc) >>> 0; // return an unsigned value
21553 };
21554
21555 /**
21556 * Update the CRC with a single byte
21557 * @param value The value to update the CRC with
21558 */
21559 this.updateCRC = function(value) {
21560 crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];
21561 };
21562
21563 /**
21564 * Update the CRC with a sequence of identical bytes
21565 * @param value The value to update the CRC with
21566 * @param count The number of bytes
21567 */
21568 this.updateCRCRun = function(value, count) {
21569 while (count-- > 0) {
21570 crc = (crc << 8) ^ crc32Lookup[((crc >>> 24) ^ value) & 0xff];
21571 }
21572 };
21573 };
21574 return CRC32;
21575 })();
21576
21577 /*
21578 seek-bzip - a pure-javascript module for seeking within bzip2 data
21579
21580 Copyright (C) 2013 C. Scott Ananian
21581 Copyright (C) 2012 Eli Skeggs
21582 Copyright (C) 2011 Kevin Kwok
21583
21584 This library is free software; you can redistribute it and/or
21585 modify it under the terms of the GNU Lesser General Public
21586 License as published by the Free Software Foundation; either
21587 version 2.1 of the License, or (at your option) any later version.
21588
21589 This library is distributed in the hope that it will be useful,
21590 but WITHOUT ANY WARRANTY; without even the implied warranty of
21591 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21592 Lesser General Public License for more details.
21593
21594 You should have received a copy of the GNU Lesser General Public
21595 License along with this library; if not, see
21596 http://www.gnu.org/licenses/lgpl-2.1.html
21597
21598 Adapted from node-bzip, copyright 2012 Eli Skeggs.
21599 Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).
21600
21601 Based on micro-bunzip by Rob Landley (rob@landley.net).
21602
21603 Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
21604 which also acknowledges contributions by Mike Burrows, David Wheeler,
21605 Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
21606 Robert Sedgewick, and Jon L. Bentley.
21607 */
21608
21609
21610
21611
21612
21613 var MAX_HUFCODE_BITS = 20;
21614 var MAX_SYMBOLS = 258;
21615 var SYMBOL_RUNA = 0;
21616 var SYMBOL_RUNB = 1;
21617 var MIN_GROUPS = 2;
21618 var MAX_GROUPS = 6;
21619 var GROUP_SIZE = 50;
21620
21621 var WHOLEPI = "314159265359";
21622 var SQRTPI = "177245385090";
21623
21624 var mtf = function(array, index) {
21625 var src = array[index], i;
21626 for (i = index; i > 0; i--) {
21627 array[i] = array[i-1];
21628 }
21629 array[0] = src;
21630 return src;
21631 };
21632
21633 var Err = {
21634 OK: 0,
21635 LAST_BLOCK: -1,
21636 NOT_BZIP_DATA: -2,
21637 UNEXPECTED_INPUT_EOF: -3,
21638 UNEXPECTED_OUTPUT_EOF: -4,
21639 DATA_ERROR: -5,
21640 OUT_OF_MEMORY: -6,
21641 OBSOLETE_INPUT: -7,
21642 END_OF_BLOCK: -8
21643 };
21644 var ErrorMessages = {};
21645 ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum";
21646 ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data";
21647 ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF";
21648 ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF";
21649 ErrorMessages[Err.DATA_ERROR] = "Data error";
21650 ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory";
21651 ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported.";
21652
21653 var _throw = function(status, optDetail) {
21654 var msg = ErrorMessages[status] || 'unknown error';
21655 if (optDetail) { msg += ': '+optDetail; }
21656 var e = new TypeError(msg);
21657 e.errorCode = status;
21658 throw e;
21659 };
21660
21661 var Bunzip = function(inputStream, outputStream) {
21662 this.writePos = this.writeCurrent = this.writeCount = 0;
21663
21664 this._start_bunzip(inputStream, outputStream);
21665 };
21666 Bunzip.prototype._init_block = function() {
21667 var moreBlocks = this._get_next_block();
21668 if ( !moreBlocks ) {
21669 this.writeCount = -1;
21670 return false; /* no more blocks */
21671 }
21672 this.blockCRC = new crc32$1();
21673 return true;
21674 };
21675 /* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */
21676 Bunzip.prototype._start_bunzip = function(inputStream, outputStream) {
21677 /* Ensure that file starts with "BZh['1'-'9']." */
21678 var buf = new Uint8Array(4);
21679 if (inputStream.read(buf, 0, 4) !== 4 ||
21680 String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh')
21681 _throw(Err.NOT_BZIP_DATA, 'bad magic');
21682
21683 var level = buf[3] - 0x30;
21684 if (level < 1 || level > 9)
21685 _throw(Err.NOT_BZIP_DATA, 'level out of range');
21686
21687 this.reader = new bitreader(inputStream);
21688
21689 /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of
21690 uncompressed data. Allocate intermediate buffer for block. */
21691 this.dbufSize = 100000 * level;
21692 this.nextoutput = 0;
21693 this.outputStream = outputStream;
21694 this.streamCRC = 0;
21695 };
21696 Bunzip.prototype._get_next_block = function() {
21697 var i, j, k;
21698 var reader = this.reader;
21699 // this is get_next_block() function from micro-bunzip:
21700 /* Read in header signature and CRC, then validate signature.
21701 (last block signature means CRC is for whole file, return now) */
21702 var h = reader.pi();
21703 if (h === SQRTPI) { // last block
21704 return false; /* no more blocks */
21705 }
21706 if (h !== WHOLEPI)
21707 _throw(Err.NOT_BZIP_DATA);
21708 this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)
21709 this.streamCRC = (this.targetBlockCRC ^
21710 ((this.streamCRC << 1) | (this.streamCRC>>>31))) >>> 0;
21711 /* We can add support for blockRandomised if anybody complains. There was
21712 some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
21713 it didn't actually work. */
21714 if (reader.read(1))
21715 _throw(Err.OBSOLETE_INPUT);
21716 var origPointer = reader.read(24);
21717 if (origPointer > this.dbufSize)
21718 _throw(Err.DATA_ERROR, 'initial position out of bounds');
21719 /* mapping table: if some byte values are never used (encoding things
21720 like ascii text), the compression code removes the gaps to have fewer
21721 symbols to deal with, and writes a sparse bitfield indicating which
21722 values were present. We make a translation table to convert the symbols
21723 back to the corresponding bytes. */
21724 var t = reader.read(16);
21725 var symToByte = new Uint8Array(256), symTotal = 0;
21726 for (i = 0; i < 16; i++) {
21727 if (t & (1 << (0xF - i))) {
21728 var o = i * 16;
21729 k = reader.read(16);
21730 for (j = 0; j < 16; j++)
21731 if (k & (1 << (0xF - j)))
21732 symToByte[symTotal++] = o + j;
21733 }
21734 }
21735
21736 /* How many different huffman coding groups does this block use? */
21737 var groupCount = reader.read(3);
21738 if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS)
21739 _throw(Err.DATA_ERROR);
21740 /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding
21741 group. Read in the group selector list, which is stored as MTF encoded
21742 bit runs. (MTF=Move To Front, as each value is used it's moved to the
21743 start of the list.) */
21744 var nSelectors = reader.read(15);
21745 if (nSelectors === 0)
21746 _throw(Err.DATA_ERROR);
21747
21748 var mtfSymbol = new Uint8Array(256);
21749 for (i = 0; i < groupCount; i++)
21750 mtfSymbol[i] = i;
21751
21752 var selectors = new Uint8Array(nSelectors); // was 32768...
21753
21754 for (i = 0; i < nSelectors; i++) {
21755 /* Get next value */
21756 for (j = 0; reader.read(1); j++)
21757 if (j >= groupCount) _throw(Err.DATA_ERROR);
21758 /* Decode MTF to get the next selector */
21759 selectors[i] = mtf(mtfSymbol, j);
21760 }
21761
21762 /* Read the huffman coding tables for each group, which code for symTotal
21763 literal symbols, plus two run symbols (RUNA, RUNB) */
21764 var symCount = symTotal + 2;
21765 var groups = [], hufGroup;
21766 for (j = 0; j < groupCount; j++) {
21767 var length = new Uint8Array(symCount), temp = new Uint16Array(MAX_HUFCODE_BITS + 1);
21768 /* Read huffman code lengths for each symbol. They're stored in
21769 a way similar to mtf; record a starting value for the first symbol,
21770 and an offset from the previous value for everys symbol after that. */
21771 t = reader.read(5); // lengths
21772 for (i = 0; i < symCount; i++) {
21773 for (;;) {
21774 if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);
21775 /* If first bit is 0, stop. Else second bit indicates whether
21776 to increment or decrement the value. */
21777 if(!reader.read(1))
21778 break;
21779 if(!reader.read(1))
21780 t++;
21781 else
21782 t--;
21783 }
21784 length[i] = t;
21785 }
21786
21787 /* Find largest and smallest lengths in this group */
21788 var minLen, maxLen;
21789 minLen = maxLen = length[0];
21790 for (i = 1; i < symCount; i++) {
21791 if (length[i] > maxLen)
21792 maxLen = length[i];
21793 else if (length[i] < minLen)
21794 minLen = length[i];
21795 }
21796
21797 /* Calculate permute[], base[], and limit[] tables from length[].
21798 *
21799 * permute[] is the lookup table for converting huffman coded symbols
21800 * into decoded symbols. base[] is the amount to subtract from the
21801 * value of a huffman symbol of a given length when using permute[].
21802 *
21803 * limit[] indicates the largest numerical value a symbol with a given
21804 * number of bits can have. This is how the huffman codes can vary in
21805 * length: each code with a value>limit[length] needs another bit.
21806 */
21807 hufGroup = {};
21808 groups.push(hufGroup);
21809 hufGroup.permute = new Uint16Array(MAX_SYMBOLS);
21810 hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);
21811 hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);
21812 hufGroup.minLen = minLen;
21813 hufGroup.maxLen = maxLen;
21814 /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */
21815 var pp = 0;
21816 for (i = minLen; i <= maxLen; i++) {
21817 temp[i] = hufGroup.limit[i] = 0;
21818 for (t = 0; t < symCount; t++)
21819 if (length[t] === i)
21820 hufGroup.permute[pp++] = t;
21821 }
21822 /* Count symbols coded for at each bit length */
21823 for (i = 0; i < symCount; i++)
21824 temp[length[i]]++;
21825 /* Calculate limit[] (the largest symbol-coding value at each bit
21826 * length, which is (previous limit<<1)+symbols at this level), and
21827 * base[] (number of symbols to ignore at each bit length, which is
21828 * limit minus the cumulative count of symbols coded for already). */
21829 pp = t = 0;
21830 for (i = minLen; i < maxLen; i++) {
21831 pp += temp[i];
21832 /* We read the largest possible symbol size and then unget bits
21833 after determining how many we need, and those extra bits could
21834 be set to anything. (They're noise from future symbols.) At
21835 each level we're really only interested in the first few bits,
21836 so here we set all the trailing to-be-ignored bits to 1 so they
21837 don't affect the value>limit[length] comparison. */
21838 hufGroup.limit[i] = pp - 1;
21839 pp <<= 1;
21840 t += temp[i];
21841 hufGroup.base[i + 1] = pp - t;
21842 }
21843 hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */
21844 hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;
21845 hufGroup.base[minLen] = 0;
21846 }
21847 /* We've finished reading and digesting the block header. Now read this
21848 block's huffman coded symbols from the file and undo the huffman coding
21849 and run length encoding, saving the result into dbuf[dbufCount++]=uc */
21850
21851 /* Initialize symbol occurrence counters and symbol Move To Front table */
21852 var byteCount = new Uint32Array(256);
21853 for (i = 0; i < 256; i++)
21854 mtfSymbol[i] = i;
21855 /* Loop through compressed symbols. */
21856 var runPos = 0, dbufCount = 0, selector = 0, uc;
21857 var dbuf = this.dbuf = new Uint32Array(this.dbufSize);
21858 symCount = 0;
21859 for (;;) {
21860 /* Determine which huffman coding group to use. */
21861 if (!(symCount--)) {
21862 symCount = GROUP_SIZE - 1;
21863 if (selector >= nSelectors) { _throw(Err.DATA_ERROR); }
21864 hufGroup = groups[selectors[selector++]];
21865 }
21866 /* Read next huffman-coded symbol. */
21867 i = hufGroup.minLen;
21868 j = reader.read(i);
21869 for (;;i++) {
21870 if (i > hufGroup.maxLen) { _throw(Err.DATA_ERROR); }
21871 if (j <= hufGroup.limit[i])
21872 break;
21873 j = (j << 1) | reader.read(1);
21874 }
21875 /* Huffman decode value to get nextSym (with bounds checking) */
21876 j -= hufGroup.base[i];
21877 if (j < 0 || j >= MAX_SYMBOLS) { _throw(Err.DATA_ERROR); }
21878 var nextSym = hufGroup.permute[j];
21879 /* We have now decoded the symbol, which indicates either a new literal
21880 byte, or a repeated run of the most recent literal byte. First,
21881 check if nextSym indicates a repeated run, and if so loop collecting
21882 how many times to repeat the last literal. */
21883 if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {
21884 /* If this is the start of a new run, zero out counter */
21885 if (!runPos){
21886 runPos = 1;
21887 t = 0;
21888 }
21889 /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
21890 each bit position, add 1 or 2 instead. For example,
21891 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
21892 You can make any bit pattern that way using 1 less symbol than
21893 the basic or 0/1 method (except all bits 0, which would use no
21894 symbols, but a run of length 0 doesn't mean anything in this
21895 context). Thus space is saved. */
21896 if (nextSym === SYMBOL_RUNA)
21897 t += runPos;
21898 else
21899 t += 2 * runPos;
21900 runPos <<= 1;
21901 continue;
21902 }
21903 /* When we hit the first non-run symbol after a run, we now know
21904 how many times to repeat the last literal, so append that many
21905 copies to our buffer of decoded symbols (dbuf) now. (The last
21906 literal used is the one at the head of the mtfSymbol array.) */
21907 if (runPos){
21908 runPos = 0;
21909 if (dbufCount + t > this.dbufSize) { _throw(Err.DATA_ERROR); }
21910 uc = symToByte[mtfSymbol[0]];
21911 byteCount[uc] += t;
21912 while (t--)
21913 dbuf[dbufCount++] = uc;
21914 }
21915 /* Is this the terminating symbol? */
21916 if (nextSym > symTotal)
21917 break;
21918 /* At this point, nextSym indicates a new literal character. Subtract
21919 one to get the position in the MTF array at which this literal is
21920 currently to be found. (Note that the result can't be -1 or 0,
21921 because 0 and 1 are RUNA and RUNB. But another instance of the
21922 first symbol in the mtf array, position 0, would have been handled
21923 as part of a run above. Therefore 1 unused mtf position minus
21924 2 non-literal nextSym values equals -1.) */
21925 if (dbufCount >= this.dbufSize) { _throw(Err.DATA_ERROR); }
21926 i = nextSym - 1;
21927 uc = mtf(mtfSymbol, i);
21928 uc = symToByte[uc];
21929 /* We have our literal byte. Save it into dbuf. */
21930 byteCount[uc]++;
21931 dbuf[dbufCount++] = uc;
21932 }
21933 /* At this point, we've read all the huffman-coded symbols (and repeated
21934 runs) for this block from the input stream, and decoded them into the
21935 intermediate buffer. There are dbufCount many decoded bytes in dbuf[].
21936 Now undo the Burrows-Wheeler transform on dbuf.
21937 See http://dogma.net/markn/articles/bwt/bwt.htm
21938 */
21939 if (origPointer < 0 || origPointer >= dbufCount) { _throw(Err.DATA_ERROR); }
21940 /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
21941 j = 0;
21942 for (i = 0; i < 256; i++) {
21943 k = j + byteCount[i];
21944 byteCount[i] = j;
21945 j = k;
21946 }
21947 /* Figure out what order dbuf would be in if we sorted it. */
21948 for (i = 0; i < dbufCount; i++) {
21949 uc = dbuf[i] & 0xff;
21950 dbuf[byteCount[uc]] |= (i << 8);
21951 byteCount[uc]++;
21952 }
21953 /* Decode first byte by hand to initialize "previous" byte. Note that it
21954 doesn't get output, and if the first three characters are identical
21955 it doesn't qualify as a run (hence writeRunCountdown=5). */
21956 var pos = 0, current = 0, run = 0;
21957 if (dbufCount) {
21958 pos = dbuf[origPointer];
21959 current = (pos & 0xff);
21960 pos >>= 8;
21961 run = -1;
21962 }
21963 this.writePos = pos;
21964 this.writeCurrent = current;
21965 this.writeCount = dbufCount;
21966 this.writeRun = run;
21967
21968 return true; /* more blocks to come */
21969 };
21970 /* Undo burrows-wheeler transform on intermediate buffer to produce output.
21971 If start_bunzip was initialized with out_fd=-1, then up to len bytes of
21972 data are written to outbuf. Return value is number of bytes written or
21973 error (all errors are negative numbers). If out_fd!=-1, outbuf and len
21974 are ignored, data is written to out_fd and return is RETVAL_OK or error.
21975 */
21976 Bunzip.prototype._read_bunzip = function(outputBuffer, len) {
21977 var copies, previous, outbyte;
21978 /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully
21979 decoded, which results in this returning RETVAL_LAST_BLOCK, also
21980 equal to -1... Confusing, I'm returning 0 here to indicate no
21981 bytes written into the buffer */
21982 if (this.writeCount < 0) { return 0; }
21983 var dbuf = this.dbuf, pos = this.writePos, current = this.writeCurrent;
21984 var dbufCount = this.writeCount; this.outputsize;
21985 var run = this.writeRun;
21986
21987 while (dbufCount) {
21988 dbufCount--;
21989 previous = current;
21990 pos = dbuf[pos];
21991 current = pos & 0xff;
21992 pos >>= 8;
21993 if (run++ === 3){
21994 copies = current;
21995 outbyte = previous;
21996 current = -1;
21997 } else {
21998 copies = 1;
21999 outbyte = current;
22000 }
22001 this.blockCRC.updateCRCRun(outbyte, copies);
22002 while (copies--) {
22003 this.outputStream.writeByte(outbyte);
22004 this.nextoutput++;
22005 }
22006 if (current != previous)
22007 run = 0;
22008 }
22009 this.writeCount = dbufCount;
22010 // check CRC
22011 if (this.blockCRC.getCRC() !== this.targetBlockCRC) {
22012 _throw(Err.DATA_ERROR, "Bad block CRC "+
22013 "(got "+this.blockCRC.getCRC().toString(16)+
22014 " expected "+this.targetBlockCRC.toString(16)+")");
22015 }
22016 return this.nextoutput;
22017 };
22018
22019 var coerceInputStream = function(input) {
22020 if ('readByte' in input) { return input; }
22021 var inputStream = new stream();
22022 inputStream.pos = 0;
22023 inputStream.readByte = function() { return input[this.pos++]; };
22024 inputStream.seek = function(pos) { this.pos = pos; };
22025 inputStream.eof = function() { return this.pos >= input.length; };
22026 return inputStream;
22027 };
22028 var coerceOutputStream = function(output) {
22029 var outputStream = new stream();
22030 var resizeOk = true;
22031 if (output) {
22032 if (typeof(output)==='number') {
22033 outputStream.buffer = new Uint8Array(output);
22034 resizeOk = false;
22035 } else if ('writeByte' in output) {
22036 return output;
22037 } else {
22038 outputStream.buffer = output;
22039 resizeOk = false;
22040 }
22041 } else {
22042 outputStream.buffer = new Uint8Array(16384);
22043 }
22044 outputStream.pos = 0;
22045 outputStream.writeByte = function(_byte) {
22046 if (resizeOk && this.pos >= this.buffer.length) {
22047 var newBuffer = new Uint8Array(this.buffer.length*2);
22048 newBuffer.set(this.buffer);
22049 this.buffer = newBuffer;
22050 }
22051 this.buffer[this.pos++] = _byte;
22052 };
22053 outputStream.getBuffer = function() {
22054 // trim buffer
22055 if (this.pos !== this.buffer.length) {
22056 if (!resizeOk)
22057 throw new TypeError('outputsize does not match decoded input');
22058 var newBuffer = new Uint8Array(this.pos);
22059 newBuffer.set(this.buffer.subarray(0, this.pos));
22060 this.buffer = newBuffer;
22061 }
22062 return this.buffer;
22063 };
22064 outputStream._coerced = true;
22065 return outputStream;
22066 };
22067
22068 /* Static helper functions */
22069 // 'input' can be a stream or a buffer
22070 // 'output' can be a stream or a buffer or a number (buffer size)
22071 const decode$2 = function(input, output, multistream) {
22072 // make a stream from a buffer, if necessary
22073 var inputStream = coerceInputStream(input);
22074 var outputStream = coerceOutputStream(output);
22075
22076 var bz = new Bunzip(inputStream, outputStream);
22077 while (true) {
22078 if ('eof' in inputStream && inputStream.eof()) break;
22079 if (bz._init_block()) {
22080 bz._read_bunzip();
22081 } else {
22082 var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)
22083 if (targetStreamCRC !== bz.streamCRC) {
22084 _throw(Err.DATA_ERROR, "Bad stream CRC "+
22085 "(got "+bz.streamCRC.toString(16)+
22086 " expected "+targetStreamCRC.toString(16)+")");
22087 }
22088 if (multistream &&
22089 'eof' in inputStream &&
22090 !inputStream.eof()) {
22091 // note that start_bunzip will also resync the bit reader to next byte
22092 bz._start_bunzip(inputStream, outputStream);
22093 } else break;
22094 }
22095 }
22096 if ('getBuffer' in outputStream)
22097 return outputStream.getBuffer();
22098 };
22099 const decodeBlock = function(input, pos, output) {
22100 // make a stream from a buffer, if necessary
22101 var inputStream = coerceInputStream(input);
22102 var outputStream = coerceOutputStream(output);
22103 var bz = new Bunzip(inputStream, outputStream);
22104 bz.reader.seek(pos);
22105 /* Fill the decode buffer for the block */
22106 var moreBlocks = bz._get_next_block();
22107 if (moreBlocks) {
22108 /* Init the CRC for writing */
22109 bz.blockCRC = new crc32$1();
22110
22111 /* Zero this so the current byte from before the seek is not written */
22112 bz.writeCopies = 0;
22113
22114 /* Decompress the block and write to stdout */
22115 bz._read_bunzip();
22116 // XXX keep writing?
22117 }
22118 if ('getBuffer' in outputStream)
22119 return outputStream.getBuffer();
22120 };
22121 /* Reads bzip2 file from stream or buffer `input`, and invoke
22122 * `callback(position, size)` once for each bzip2 block,
22123 * where position gives the starting position (in *bits*)
22124 * and size gives uncompressed size of the block (in *bytes*). */
22125 const table = function(input, callback, multistream) {
22126 // make a stream from a buffer, if necessary
22127 var inputStream = new stream();
22128 inputStream.delegate = coerceInputStream(input);
22129 inputStream.pos = 0;
22130 inputStream.readByte = function() {
22131 this.pos++;
22132 return this.delegate.readByte();
22133 };
22134 if (inputStream.delegate.eof) {
22135 inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);
22136 }
22137 var outputStream = new stream();
22138 outputStream.pos = 0;
22139 outputStream.writeByte = function() { this.pos++; };
22140
22141 var bz = new Bunzip(inputStream, outputStream);
22142 var blockSize = bz.dbufSize;
22143 while (true) {
22144 if ('eof' in inputStream && inputStream.eof()) break;
22145
22146 var position = inputStream.pos*8 + bz.reader.bitOffset;
22147 if (bz.reader.hasByte) { position -= 8; }
22148
22149 if (bz._init_block()) {
22150 var start = outputStream.pos;
22151 bz._read_bunzip();
22152 callback(position, outputStream.pos - start);
22153 } else {
22154 bz.reader.read(32); // (but we ignore the crc)
22155 if (multistream &&
22156 'eof' in inputStream &&
22157 !inputStream.eof()) {
22158 // note that start_bunzip will also resync the bit reader to next byte
22159 bz._start_bunzip(inputStream, outputStream);
22160 console.assert(bz.dbufSize === blockSize,
22161 "shouldn't change block size within multistream file");
22162 } else break;
22163 }
22164 }
22165 };
22166
22167 var lib = {
22168 Bunzip,
22169 Stream: stream,
22170 Err,
22171 decode: decode$2,
22172 decodeBlock,
22173 table
22174 };
22175 var lib_4 = lib.decode;
22176
22177 // GPG4Browsers - An OpenPGP implementation in javascript
22178
22179 /**
22180 * Implementation of the Literal Data Packet (Tag 11)
22181 *
22182 * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:
22183 * A Literal Data packet contains the body of a message; data that is not to be
22184 * further interpreted.
22185 */
22186 class LiteralDataPacket {
22187 static get tag() {
22188 return enums.packet.literalData;
22189 }
22190
22191 /**
22192 * @param {Date} date - The creation date of the literal package
22193 */
22194 constructor(date = new Date()) {
22195 this.format = 'utf8'; // default format for literal data packets
22196 this.date = util.normalizeDate(date);
22197 this.text = null; // textual data representation
22198 this.data = null; // literal data representation
22199 this.filename = '';
22200 }
22201
22202 /**
22203 * Set the packet data to a javascript native string, end of line
22204 * will be normalized to \r\n and by default text is converted to UTF8
22205 * @param {String | ReadableStream<String>} text - Any native javascript string
22206 * @param {utf8|binary|text|mime} [format] - The format of the string of bytes
22207 */
22208 setText(text, format = 'utf8') {
22209 this.format = format;
22210 this.text = text;
22211 this.data = null;
22212 }
22213
22214 /**
22215 * Returns literal data packets as native JavaScript string
22216 * with normalized end of line to \n
22217 * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again
22218 * @returns {String | ReadableStream<String>} Literal data as text.
22219 */
22220 getText(clone = false) {
22221 if (this.text === null || util.isStream(this.text)) { // Assume that this.text has been read
22222 this.text = util.decodeUTF8(util.nativeEOL(this.getBytes(clone)));
22223 }
22224 return this.text;
22225 }
22226
22227 /**
22228 * Set the packet data to value represented by the provided string of bytes.
22229 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - The string of bytes
22230 * @param {utf8|binary|text|mime} format - The format of the string of bytes
22231 */
22232 setBytes(bytes, format) {
22233 this.format = format;
22234 this.data = bytes;
22235 this.text = null;
22236 }
22237
22238
22239 /**
22240 * Get the byte sequence representing the literal packet data
22241 * @param {Boolean} [clone] - Whether to return a clone so that getBytes/getText can be called again
22242 * @returns {Uint8Array | ReadableStream<Uint8Array>} A sequence of bytes.
22243 */
22244 getBytes(clone = false) {
22245 if (this.data === null) {
22246 // encode UTF8 and normalize EOL to \r\n
22247 this.data = util.canonicalizeEOL(util.encodeUTF8(this.text));
22248 }
22249 if (clone) {
22250 return passiveClone(this.data);
22251 }
22252 return this.data;
22253 }
22254
22255
22256 /**
22257 * Sets the filename of the literal packet data
22258 * @param {String} filename - Any native javascript string
22259 */
22260 setFilename(filename) {
22261 this.filename = filename;
22262 }
22263
22264
22265 /**
22266 * Get the filename of the literal packet data
22267 * @returns {String} Filename.
22268 */
22269 getFilename() {
22270 return this.filename;
22271 }
22272
22273 /**
22274 * Parsing function for a literal data packet (tag 11).
22275 *
22276 * @param {Uint8Array | ReadableStream<Uint8Array>} input - Payload of a tag 11 packet
22277 * @returns {Promise<LiteralDataPacket>} Object representation.
22278 * @async
22279 */
22280 async read(bytes) {
22281 await parse(bytes, async reader => {
22282 // - A one-octet field that describes how the data is formatted.
22283 const format = enums.read(enums.literal, await reader.readByte());
22284
22285 const filename_len = await reader.readByte();
22286 this.filename = util.decodeUTF8(await reader.readBytes(filename_len));
22287
22288 this.date = util.readDate(await reader.readBytes(4));
22289
22290 const data = reader.remainder();
22291
22292 this.setBytes(data, format);
22293 });
22294 }
22295
22296 /**
22297 * Creates a Uint8Array representation of the packet, excluding the data
22298 *
22299 * @returns {Uint8Array} Uint8Array representation of the packet.
22300 */
22301 writeHeader() {
22302 const filename = util.encodeUTF8(this.filename);
22303 const filename_length = new Uint8Array([filename.length]);
22304
22305 const format = new Uint8Array([enums.write(enums.literal, this.format)]);
22306 const date = util.writeDate(this.date);
22307
22308 return util.concatUint8Array([format, filename_length, filename, date]);
22309 }
22310
22311 /**
22312 * Creates a Uint8Array representation of the packet
22313 *
22314 * @returns {Uint8Array | ReadableStream<Uint8Array>} Uint8Array representation of the packet.
22315 */
22316 write() {
22317 const header = this.writeHeader();
22318 const data = this.getBytes();
22319
22320 return util.concat([header, data]);
22321 }
22322 }
22323
22324 // GPG4Browsers - An OpenPGP implementation in javascript
22325
22326 function readSimpleLength(bytes) {
22327 let len = 0;
22328 let offset;
22329 const type = bytes[0];
22330
22331
22332 if (type < 192) {
22333 [len] = bytes;
22334 offset = 1;
22335 } else if (type < 255) {
22336 len = ((bytes[0] - 192) << 8) + (bytes[1]) + 192;
22337 offset = 2;
22338 } else if (type === 255) {
22339 len = util.readNumber(bytes.subarray(1, 1 + 4));
22340 offset = 5;
22341 }
22342
22343 return {
22344 len: len,
22345 offset: offset
22346 };
22347 }
22348
22349 /**
22350 * Encodes a given integer of length to the openpgp length specifier to a
22351 * string
22352 *
22353 * @param {Integer} length - The length to encode
22354 * @returns {Uint8Array} String with openpgp length representation.
22355 */
22356 function writeSimpleLength(length) {
22357 if (length < 192) {
22358 return new Uint8Array([length]);
22359 } else if (length > 191 && length < 8384) {
22360 /*
22361 * let a = (total data packet length) - 192 let bc = two octet
22362 * representation of a let d = b + 192
22363 */
22364 return new Uint8Array([((length - 192) >> 8) + 192, (length - 192) & 0xFF]);
22365 }
22366 return util.concatUint8Array([new Uint8Array([255]), util.writeNumber(length, 4)]);
22367 }
22368
22369 function writePartialLength(power) {
22370 if (power < 0 || power > 30) {
22371 throw new Error('Partial Length power must be between 1 and 30');
22372 }
22373 return new Uint8Array([224 + power]);
22374 }
22375
22376 function writeTag(tag_type) {
22377 /* we're only generating v4 packet headers here */
22378 return new Uint8Array([0xC0 | tag_type]);
22379 }
22380
22381 /**
22382 * Writes a packet header version 4 with the given tag_type and length to a
22383 * string
22384 *
22385 * @param {Integer} tag_type - Tag type
22386 * @param {Integer} length - Length of the payload
22387 * @returns {String} String of the header.
22388 */
22389 function writeHeader(tag_type, length) {
22390 /* we're only generating v4 packet headers here */
22391 return util.concatUint8Array([writeTag(tag_type), writeSimpleLength(length)]);
22392 }
22393
22394 /**
22395 * Whether the packet type supports partial lengths per RFC4880
22396 * @param {Integer} tag - Tag type
22397 * @returns {Boolean} String of the header.
22398 */
22399 function supportsStreaming(tag) {
22400 return [
22401 enums.packet.literalData,
22402 enums.packet.compressedData,
22403 enums.packet.symmetricallyEncryptedData,
22404 enums.packet.symEncryptedIntegrityProtectedData,
22405 enums.packet.aeadEncryptedData
22406 ].includes(tag);
22407 }
22408
22409 /**
22410 * Generic static Packet Parser function
22411 *
22412 * @param {Uint8Array | ReadableStream<Uint8Array>} input - Input stream as string
22413 * @param {Function} callback - Function to call with the parsed packet
22414 * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.
22415 */
22416 async function readPackets(input, callback) {
22417 const reader = getReader(input);
22418 let writer;
22419 let callbackReturned;
22420 try {
22421 const peekedBytes = await reader.peekBytes(2);
22422 // some sanity checks
22423 if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {
22424 throw new Error('Error during parsing. This message / key probably does not conform to a valid OpenPGP format.');
22425 }
22426 const headerByte = await reader.readByte();
22427 let tag = -1;
22428 let format = -1;
22429 let packetLength;
22430
22431 format = 0; // 0 = old format; 1 = new format
22432 if ((headerByte & 0x40) !== 0) {
22433 format = 1;
22434 }
22435
22436 let packetLengthType;
22437 if (format) {
22438 // new format header
22439 tag = headerByte & 0x3F; // bit 5-0
22440 } else {
22441 // old format header
22442 tag = (headerByte & 0x3F) >> 2; // bit 5-2
22443 packetLengthType = headerByte & 0x03; // bit 1-0
22444 }
22445
22446 const packetSupportsStreaming = supportsStreaming(tag);
22447 let packet = null;
22448 if (packetSupportsStreaming) {
22449 if (util.isStream(input) === 'array') {
22450 const arrayStream = new ArrayStream();
22451 writer = getWriter(arrayStream);
22452 packet = arrayStream;
22453 } else {
22454 const transform = new TransformStream();
22455 writer = getWriter(transform.writable);
22456 packet = transform.readable;
22457 }
22458 callbackReturned = callback({ tag, packet });
22459 } else {
22460 packet = [];
22461 }
22462
22463 let wasPartialLength;
22464 do {
22465 if (!format) {
22466 // 4.2.1. Old Format Packet Lengths
22467 switch (packetLengthType) {
22468 case 0:
22469 // The packet has a one-octet length. The header is 2 octets
22470 // long.
22471 packetLength = await reader.readByte();
22472 break;
22473 case 1:
22474 // The packet has a two-octet length. The header is 3 octets
22475 // long.
22476 packetLength = (await reader.readByte() << 8) | await reader.readByte();
22477 break;
22478 case 2:
22479 // The packet has a four-octet length. The header is 5
22480 // octets long.
22481 packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<
22482 8) | await reader.readByte();
22483 break;
22484 default:
22485 // 3 - The packet is of indeterminate length. The header is 1
22486 // octet long, and the implementation must determine how long
22487 // the packet is. If the packet is in a file, this means that
22488 // the packet extends until the end of the file. In general,
22489 // an implementation SHOULD NOT use indeterminate-length
22490 // packets except where the end of the data will be clear
22491 // from the context, and even then it is better to use a
22492 // definite length, or a new format header. The new format
22493 // headers described below have a mechanism for precisely
22494 // encoding data of indeterminate length.
22495 packetLength = Infinity;
22496 break;
22497 }
22498 } else { // 4.2.2. New Format Packet Lengths
22499 // 4.2.2.1. One-Octet Lengths
22500 const lengthByte = await reader.readByte();
22501 wasPartialLength = false;
22502 if (lengthByte < 192) {
22503 packetLength = lengthByte;
22504 // 4.2.2.2. Two-Octet Lengths
22505 } else if (lengthByte >= 192 && lengthByte < 224) {
22506 packetLength = ((lengthByte - 192) << 8) + (await reader.readByte()) + 192;
22507 // 4.2.2.4. Partial Body Lengths
22508 } else if (lengthByte > 223 && lengthByte < 255) {
22509 packetLength = 1 << (lengthByte & 0x1F);
22510 wasPartialLength = true;
22511 if (!packetSupportsStreaming) {
22512 throw new TypeError('This packet type does not support partial lengths.');
22513 }
22514 // 4.2.2.3. Five-Octet Lengths
22515 } else {
22516 packetLength = (await reader.readByte() << 24) | (await reader.readByte() << 16) | (await reader.readByte() <<
22517 8) | await reader.readByte();
22518 }
22519 }
22520 if (packetLength > 0) {
22521 let bytesRead = 0;
22522 while (true) {
22523 if (writer) await writer.ready;
22524 const { done, value } = await reader.read();
22525 if (done) {
22526 if (packetLength === Infinity) break;
22527 throw new Error('Unexpected end of packet');
22528 }
22529 const chunk = packetLength === Infinity ? value : value.subarray(0, packetLength - bytesRead);
22530 if (writer) await writer.write(chunk);
22531 else packet.push(chunk);
22532 bytesRead += value.length;
22533 if (bytesRead >= packetLength) {
22534 reader.unshift(value.subarray(packetLength - bytesRead + value.length));
22535 break;
22536 }
22537 }
22538 }
22539 } while (wasPartialLength);
22540
22541 // If this was not a packet that "supports streaming", we peek to check
22542 // whether it is the last packet in the message. We peek 2 bytes instead
22543 // of 1 because the beginning of this function also peeks 2 bytes, and we
22544 // want to cut a `subarray` of the correct length into `web-stream-tools`'
22545 // `externalBuffer` as a tiny optimization here.
22546 //
22547 // If it *was* a streaming packet (i.e. the data packets), we peek at the
22548 // entire remainder of the stream, in order to forward errors in the
22549 // remainder of the stream to the packet data. (Note that this means we
22550 // read/peek at all signature packets before closing the literal data
22551 // packet, for example.) This forwards MDC errors to the literal data
22552 // stream, for example, so that they don't get lost / forgotten on
22553 // decryptedMessage.packets.stream, which we never look at.
22554 //
22555 // An example of what we do when stream-parsing a message containing
22556 // [ one-pass signature packet, literal data packet, signature packet ]:
22557 // 1. Read the one-pass signature packet
22558 // 2. Peek 2 bytes of the literal data packet
22559 // 3. Parse the one-pass signature packet
22560 //
22561 // 4. Read the literal data packet, simultaneously stream-parsing it
22562 // 5. Peek until the end of the message
22563 // 6. Finish parsing the literal data packet
22564 //
22565 // 7. Read the signature packet again (we already peeked at it in step 5)
22566 // 8. Peek at the end of the stream again (`peekBytes` returns undefined)
22567 // 9. Parse the signature packet
22568 //
22569 // Note that this means that if there's an error in the very end of the
22570 // stream, such as an MDC error, we throw in step 5 instead of in step 8
22571 // (or never), which is the point of this exercise.
22572 const nextPacket = await reader.peekBytes(packetSupportsStreaming ? Infinity : 2);
22573 if (writer) {
22574 await writer.ready;
22575 await writer.close();
22576 } else {
22577 packet = util.concatUint8Array(packet);
22578 await callback({ tag, packet });
22579 }
22580 return !nextPacket || !nextPacket.length;
22581 } catch (e) {
22582 if (writer) {
22583 await writer.abort(e);
22584 return true;
22585 } else {
22586 throw e;
22587 }
22588 } finally {
22589 if (writer) {
22590 await callbackReturned;
22591 }
22592 reader.releaseLock();
22593 }
22594 }
22595
22596 class UnsupportedError extends Error {
22597 constructor(...params) {
22598 super(...params);
22599
22600 if (Error.captureStackTrace) {
22601 Error.captureStackTrace(this, UnsupportedError);
22602 }
22603
22604 this.name = 'UnsupportedError';
22605 }
22606 }
22607
22608 // GPG4Browsers - An OpenPGP implementation in javascript
22609
22610 // Symbol to store cryptographic validity of the signature, to avoid recomputing multiple times on verification.
22611 const verified = Symbol('verified');
22612
22613 // GPG puts the Issuer and Signature subpackets in the unhashed area.
22614 // Tampering with those invalidates the signature, so we still trust them and parse them.
22615 // All other unhashed subpackets are ignored.
22616 const allowedUnhashedSubpackets = new Set([
22617 enums.signatureSubpacket.issuer,
22618 enums.signatureSubpacket.issuerFingerprint,
22619 enums.signatureSubpacket.embeddedSignature
22620 ]);
22621
22622 /**
22623 * Implementation of the Signature Packet (Tag 2)
22624 *
22625 * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:
22626 * A Signature packet describes a binding between some public key and
22627 * some data. The most common signatures are a signature of a file or a
22628 * block of text, and a signature that is a certification of a User ID.
22629 */
22630 class SignaturePacket {
22631 static get tag() {
22632 return enums.packet.signature;
22633 }
22634
22635 constructor() {
22636 this.version = null;
22637 this.signatureType = null;
22638 this.hashAlgorithm = null;
22639 this.publicKeyAlgorithm = null;
22640
22641 this.signatureData = null;
22642 this.unhashedSubpackets = [];
22643 this.signedHashValue = null;
22644
22645 this.created = null;
22646 this.signatureExpirationTime = null;
22647 this.signatureNeverExpires = true;
22648 this.exportable = null;
22649 this.trustLevel = null;
22650 this.trustAmount = null;
22651 this.regularExpression = null;
22652 this.revocable = null;
22653 this.keyExpirationTime = null;
22654 this.keyNeverExpires = null;
22655 this.preferredSymmetricAlgorithms = null;
22656 this.revocationKeyClass = null;
22657 this.revocationKeyAlgorithm = null;
22658 this.revocationKeyFingerprint = null;
22659 this.issuerKeyID = new KeyID();
22660 this.rawNotations = [];
22661 this.notations = {};
22662 this.preferredHashAlgorithms = null;
22663 this.preferredCompressionAlgorithms = null;
22664 this.keyServerPreferences = null;
22665 this.preferredKeyServer = null;
22666 this.isPrimaryUserID = null;
22667 this.policyURI = null;
22668 this.keyFlags = null;
22669 this.signersUserID = null;
22670 this.reasonForRevocationFlag = null;
22671 this.reasonForRevocationString = null;
22672 this.features = null;
22673 this.signatureTargetPublicKeyAlgorithm = null;
22674 this.signatureTargetHashAlgorithm = null;
22675 this.signatureTargetHash = null;
22676 this.embeddedSignature = null;
22677 this.issuerKeyVersion = null;
22678 this.issuerFingerprint = null;
22679 this.preferredAEADAlgorithms = null;
22680
22681 this.revoked = null;
22682 this[verified] = null;
22683 }
22684
22685 /**
22686 * parsing function for a signature packet (tag 2).
22687 * @param {String} bytes - Payload of a tag 2 packet
22688 * @returns {SignaturePacket} Object representation.
22689 */
22690 read(bytes) {
22691 let i = 0;
22692 this.version = bytes[i++];
22693
22694 if (this.version !== 4 && this.version !== 5) {
22695 throw new UnsupportedError(`Version ${this.version} of the signature packet is unsupported.`);
22696 }
22697
22698 this.signatureType = bytes[i++];
22699 this.publicKeyAlgorithm = bytes[i++];
22700 this.hashAlgorithm = bytes[i++];
22701
22702 // hashed subpackets
22703 i += this.readSubPackets(bytes.subarray(i, bytes.length), true);
22704 if (!this.created) {
22705 throw new Error('Missing signature creation time subpacket.');
22706 }
22707
22708 // A V4 signature hashes the packet body
22709 // starting from its first field, the version number, through the end
22710 // of the hashed subpacket data. Thus, the fields hashed are the
22711 // signature version, the signature type, the public-key algorithm, the
22712 // hash algorithm, the hashed subpacket length, and the hashed
22713 // subpacket body.
22714 this.signatureData = bytes.subarray(0, i);
22715
22716 // unhashed subpackets
22717 i += this.readSubPackets(bytes.subarray(i, bytes.length), false);
22718
22719 // Two-octet field holding left 16 bits of signed hash value.
22720 this.signedHashValue = bytes.subarray(i, i + 2);
22721 i += 2;
22722
22723 this.params = mod.signature.parseSignatureParams(this.publicKeyAlgorithm, bytes.subarray(i, bytes.length));
22724 }
22725
22726 /**
22727 * @returns {Uint8Array | ReadableStream<Uint8Array>}
22728 */
22729 writeParams() {
22730 if (this.params instanceof Promise) {
22731 return fromAsync(
22732 async () => mod.serializeParams(this.publicKeyAlgorithm, await this.params)
22733 );
22734 }
22735 return mod.serializeParams(this.publicKeyAlgorithm, this.params);
22736 }
22737
22738 write() {
22739 const arr = [];
22740 arr.push(this.signatureData);
22741 arr.push(this.writeUnhashedSubPackets());
22742 arr.push(this.signedHashValue);
22743 arr.push(this.writeParams());
22744 return util.concat(arr);
22745 }
22746
22747 /**
22748 * Signs provided data. This needs to be done prior to serialization.
22749 * @param {SecretKeyPacket} key - Private key used to sign the message.
22750 * @param {Object} data - Contains packets to be signed.
22751 * @param {Date} [date] - The signature creation time.
22752 * @param {Boolean} [detached] - Whether to create a detached signature
22753 * @throws {Error} if signing failed
22754 * @async
22755 */
22756 async sign(key, data, date = new Date(), detached = false) {
22757 const signatureType = enums.write(enums.signature, this.signatureType);
22758 const publicKeyAlgorithm = enums.write(enums.publicKey, this.publicKeyAlgorithm);
22759 const hashAlgorithm = enums.write(enums.hash, this.hashAlgorithm);
22760
22761 if (key.version === 5) {
22762 this.version = 5;
22763 } else {
22764 this.version = 4;
22765 }
22766 const arr = [new Uint8Array([this.version, signatureType, publicKeyAlgorithm, hashAlgorithm])];
22767
22768 this.created = util.normalizeDate(date);
22769 this.issuerKeyVersion = key.version;
22770 this.issuerFingerprint = key.getFingerprintBytes();
22771 this.issuerKeyID = key.getKeyID();
22772
22773 // Add hashed subpackets
22774 arr.push(this.writeHashedSubPackets());
22775
22776 this.signatureData = util.concat(arr);
22777
22778 const toHash = this.toHash(signatureType, data, detached);
22779 const hash = await this.hash(signatureType, data, toHash, detached);
22780
22781 this.signedHashValue = slice(clone(hash), 0, 2);
22782 const signed = async () => mod.signature.sign(
22783 publicKeyAlgorithm, hashAlgorithm, key.publicParams, key.privateParams, toHash, await readToEnd(hash)
22784 );
22785 if (util.isStream(hash)) {
22786 this.params = signed();
22787 } else {
22788 this.params = await signed();
22789
22790 // Store the fact that this signature is valid, e.g. for when we call `await
22791 // getLatestValidSignature(this.revocationSignatures, key, data)` later.
22792 // Note that this only holds up if the key and data passed to verify are the
22793 // same as the ones passed to sign.
22794 this[verified] = true;
22795 }
22796 }
22797
22798 /**
22799 * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets
22800 * @returns {Uint8Array} Subpacket data.
22801 */
22802 writeHashedSubPackets() {
22803 const sub = enums.signatureSubpacket;
22804 const arr = [];
22805 let bytes;
22806 if (this.created === null) {
22807 throw new Error('Missing signature creation time');
22808 }
22809 arr.push(writeSubPacket(sub.signatureCreationTime, util.writeDate(this.created)));
22810 if (this.signatureExpirationTime !== null) {
22811 arr.push(writeSubPacket(sub.signatureExpirationTime, util.writeNumber(this.signatureExpirationTime, 4)));
22812 }
22813 if (this.exportable !== null) {
22814 arr.push(writeSubPacket(sub.exportableCertification, new Uint8Array([this.exportable ? 1 : 0])));
22815 }
22816 if (this.trustLevel !== null) {
22817 bytes = new Uint8Array([this.trustLevel, this.trustAmount]);
22818 arr.push(writeSubPacket(sub.trustSignature, bytes));
22819 }
22820 if (this.regularExpression !== null) {
22821 arr.push(writeSubPacket(sub.regularExpression, this.regularExpression));
22822 }
22823 if (this.revocable !== null) {
22824 arr.push(writeSubPacket(sub.revocable, new Uint8Array([this.revocable ? 1 : 0])));
22825 }
22826 if (this.keyExpirationTime !== null) {
22827 arr.push(writeSubPacket(sub.keyExpirationTime, util.writeNumber(this.keyExpirationTime, 4)));
22828 }
22829 if (this.preferredSymmetricAlgorithms !== null) {
22830 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredSymmetricAlgorithms));
22831 arr.push(writeSubPacket(sub.preferredSymmetricAlgorithms, bytes));
22832 }
22833 if (this.revocationKeyClass !== null) {
22834 bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);
22835 bytes = util.concat([bytes, this.revocationKeyFingerprint]);
22836 arr.push(writeSubPacket(sub.revocationKey, bytes));
22837 }
22838 this.rawNotations.forEach(([{ name, value, humanReadable }]) => {
22839 bytes = [new Uint8Array([humanReadable ? 0x80 : 0, 0, 0, 0])];
22840 // 2 octets of name length
22841 bytes.push(util.writeNumber(name.length, 2));
22842 // 2 octets of value length
22843 bytes.push(util.writeNumber(value.length, 2));
22844 bytes.push(util.stringToUint8Array(name));
22845 bytes.push(value);
22846 bytes = util.concat(bytes);
22847 arr.push(writeSubPacket(sub.notationData, bytes));
22848 });
22849 if (this.preferredHashAlgorithms !== null) {
22850 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredHashAlgorithms));
22851 arr.push(writeSubPacket(sub.preferredHashAlgorithms, bytes));
22852 }
22853 if (this.preferredCompressionAlgorithms !== null) {
22854 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredCompressionAlgorithms));
22855 arr.push(writeSubPacket(sub.preferredCompressionAlgorithms, bytes));
22856 }
22857 if (this.keyServerPreferences !== null) {
22858 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyServerPreferences));
22859 arr.push(writeSubPacket(sub.keyServerPreferences, bytes));
22860 }
22861 if (this.preferredKeyServer !== null) {
22862 arr.push(writeSubPacket(sub.preferredKeyServer, util.stringToUint8Array(this.preferredKeyServer)));
22863 }
22864 if (this.isPrimaryUserID !== null) {
22865 arr.push(writeSubPacket(sub.primaryUserID, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));
22866 }
22867 if (this.policyURI !== null) {
22868 arr.push(writeSubPacket(sub.policyURI, util.stringToUint8Array(this.policyURI)));
22869 }
22870 if (this.keyFlags !== null) {
22871 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.keyFlags));
22872 arr.push(writeSubPacket(sub.keyFlags, bytes));
22873 }
22874 if (this.signersUserID !== null) {
22875 arr.push(writeSubPacket(sub.signersUserID, util.stringToUint8Array(this.signersUserID)));
22876 }
22877 if (this.reasonForRevocationFlag !== null) {
22878 bytes = util.stringToUint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);
22879 arr.push(writeSubPacket(sub.reasonForRevocation, bytes));
22880 }
22881 if (this.features !== null) {
22882 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.features));
22883 arr.push(writeSubPacket(sub.features, bytes));
22884 }
22885 if (this.signatureTargetPublicKeyAlgorithm !== null) {
22886 bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];
22887 bytes.push(util.stringToUint8Array(this.signatureTargetHash));
22888 bytes = util.concat(bytes);
22889 arr.push(writeSubPacket(sub.signatureTarget, bytes));
22890 }
22891 if (this.preferredAEADAlgorithms !== null) {
22892 bytes = util.stringToUint8Array(util.uint8ArrayToString(this.preferredAEADAlgorithms));
22893 arr.push(writeSubPacket(sub.preferredAEADAlgorithms, bytes));
22894 }
22895
22896 const result = util.concat(arr);
22897 const length = util.writeNumber(result.length, 2);
22898
22899 return util.concat([length, result]);
22900 }
22901
22902 /**
22903 * Creates Uint8Array of bytes of Issuer and Embedded Signature subpackets
22904 * @returns {Uint8Array} Subpacket data.
22905 */
22906 writeUnhashedSubPackets() {
22907 const sub = enums.signatureSubpacket;
22908 const arr = [];
22909 let bytes;
22910 if (!this.issuerKeyID.isNull() && this.issuerKeyVersion !== 5) {
22911 // If the version of [the] key is greater than 4, this subpacket
22912 // MUST NOT be included in the signature.
22913 arr.push(writeSubPacket(sub.issuer, this.issuerKeyID.write()));
22914 }
22915 if (this.embeddedSignature !== null) {
22916 arr.push(writeSubPacket(sub.embeddedSignature, this.embeddedSignature.write()));
22917 }
22918 if (this.issuerFingerprint !== null) {
22919 bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];
22920 bytes = util.concat(bytes);
22921 arr.push(writeSubPacket(sub.issuerFingerprint, bytes));
22922 }
22923 this.unhashedSubpackets.forEach(data => {
22924 arr.push(writeSimpleLength(data.length));
22925 arr.push(data);
22926 });
22927
22928 const result = util.concat(arr);
22929 const length = util.writeNumber(result.length, 2);
22930
22931 return util.concat([length, result]);
22932 }
22933
22934 // V4 signature sub packets
22935 readSubPacket(bytes, hashed = true) {
22936 let mypos = 0;
22937
22938 // The leftmost bit denotes a "critical" packet
22939 const critical = bytes[mypos] & 0x80;
22940 const type = bytes[mypos] & 0x7F;
22941
22942 if (!hashed && !allowedUnhashedSubpackets.has(type)) {
22943 this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length));
22944 return;
22945 }
22946
22947 mypos++;
22948
22949 // subpacket type
22950 switch (type) {
22951 case enums.signatureSubpacket.signatureCreationTime:
22952 // Signature Creation Time
22953 this.created = util.readDate(bytes.subarray(mypos, bytes.length));
22954 break;
22955 case enums.signatureSubpacket.signatureExpirationTime: {
22956 // Signature Expiration Time in seconds
22957 const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));
22958
22959 this.signatureNeverExpires = seconds === 0;
22960 this.signatureExpirationTime = seconds;
22961
22962 break;
22963 }
22964 case enums.signatureSubpacket.exportableCertification:
22965 // Exportable Certification
22966 this.exportable = bytes[mypos++] === 1;
22967 break;
22968 case enums.signatureSubpacket.trustSignature:
22969 // Trust Signature
22970 this.trustLevel = bytes[mypos++];
22971 this.trustAmount = bytes[mypos++];
22972 break;
22973 case enums.signatureSubpacket.regularExpression:
22974 // Regular Expression
22975 this.regularExpression = bytes[mypos];
22976 break;
22977 case enums.signatureSubpacket.revocable:
22978 // Revocable
22979 this.revocable = bytes[mypos++] === 1;
22980 break;
22981 case enums.signatureSubpacket.keyExpirationTime: {
22982 // Key Expiration Time in seconds
22983 const seconds = util.readNumber(bytes.subarray(mypos, bytes.length));
22984
22985 this.keyExpirationTime = seconds;
22986 this.keyNeverExpires = seconds === 0;
22987
22988 break;
22989 }
22990 case enums.signatureSubpacket.preferredSymmetricAlgorithms:
22991 // Preferred Symmetric Algorithms
22992 this.preferredSymmetricAlgorithms = [...bytes.subarray(mypos, bytes.length)];
22993 break;
22994 case enums.signatureSubpacket.revocationKey:
22995 // Revocation Key
22996 // (1 octet of class, 1 octet of public-key algorithm ID, 20
22997 // octets of
22998 // fingerprint)
22999 this.revocationKeyClass = bytes[mypos++];
23000 this.revocationKeyAlgorithm = bytes[mypos++];
23001 this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);
23002 break;
23003
23004 case enums.signatureSubpacket.issuer:
23005 // Issuer
23006 this.issuerKeyID.read(bytes.subarray(mypos, bytes.length));
23007 break;
23008
23009 case enums.signatureSubpacket.notationData: {
23010 // Notation Data
23011 const humanReadable = !!(bytes[mypos] & 0x80);
23012
23013 // We extract key/value tuple from the byte stream.
23014 mypos += 4;
23015 const m = util.readNumber(bytes.subarray(mypos, mypos + 2));
23016 mypos += 2;
23017 const n = util.readNumber(bytes.subarray(mypos, mypos + 2));
23018 mypos += 2;
23019
23020 const name = util.uint8ArrayToString(bytes.subarray(mypos, mypos + m));
23021 const value = bytes.subarray(mypos + m, mypos + m + n);
23022
23023 this.rawNotations.push({ name, humanReadable, value, critical });
23024
23025 if (humanReadable) {
23026 this.notations[name] = util.uint8ArrayToString(value);
23027 }
23028 break;
23029 }
23030 case enums.signatureSubpacket.preferredHashAlgorithms:
23031 // Preferred Hash Algorithms
23032 this.preferredHashAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23033 break;
23034 case enums.signatureSubpacket.preferredCompressionAlgorithms:
23035 // Preferred Compression Algorithms
23036 this.preferredCompressionAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23037 break;
23038 case enums.signatureSubpacket.keyServerPreferences:
23039 // Key Server Preferences
23040 this.keyServerPreferences = [...bytes.subarray(mypos, bytes.length)];
23041 break;
23042 case enums.signatureSubpacket.preferredKeyServer:
23043 // Preferred Key Server
23044 this.preferredKeyServer = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length));
23045 break;
23046 case enums.signatureSubpacket.primaryUserID:
23047 // Primary User ID
23048 this.isPrimaryUserID = bytes[mypos++] !== 0;
23049 break;
23050 case enums.signatureSubpacket.policyURI:
23051 // Policy URI
23052 this.policyURI = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length));
23053 break;
23054 case enums.signatureSubpacket.keyFlags:
23055 // Key Flags
23056 this.keyFlags = [...bytes.subarray(mypos, bytes.length)];
23057 break;
23058 case enums.signatureSubpacket.signersUserID:
23059 // Signer's User ID
23060 this.signersUserID = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length));
23061 break;
23062 case enums.signatureSubpacket.reasonForRevocation:
23063 // Reason for Revocation
23064 this.reasonForRevocationFlag = bytes[mypos++];
23065 this.reasonForRevocationString = util.uint8ArrayToString(bytes.subarray(mypos, bytes.length));
23066 break;
23067 case enums.signatureSubpacket.features:
23068 // Features
23069 this.features = [...bytes.subarray(mypos, bytes.length)];
23070 break;
23071 case enums.signatureSubpacket.signatureTarget: {
23072 // Signature Target
23073 // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)
23074 this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];
23075 this.signatureTargetHashAlgorithm = bytes[mypos++];
23076
23077 const len = mod.getHashByteLength(this.signatureTargetHashAlgorithm);
23078
23079 this.signatureTargetHash = util.uint8ArrayToString(bytes.subarray(mypos, mypos + len));
23080 break;
23081 }
23082 case enums.signatureSubpacket.embeddedSignature:
23083 // Embedded Signature
23084 this.embeddedSignature = new SignaturePacket();
23085 this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));
23086 break;
23087 case enums.signatureSubpacket.issuerFingerprint:
23088 // Issuer Fingerprint
23089 this.issuerKeyVersion = bytes[mypos++];
23090 this.issuerFingerprint = bytes.subarray(mypos, bytes.length);
23091 if (this.issuerKeyVersion === 5) {
23092 this.issuerKeyID.read(this.issuerFingerprint);
23093 } else {
23094 this.issuerKeyID.read(this.issuerFingerprint.subarray(-8));
23095 }
23096 break;
23097 case enums.signatureSubpacket.preferredAEADAlgorithms:
23098 // Preferred AEAD Algorithms
23099 this.preferredAEADAlgorithms = [...bytes.subarray(mypos, bytes.length)];
23100 break;
23101 default: {
23102 const err = new Error(`Unknown signature subpacket type ${type}`);
23103 if (critical) {
23104 throw err;
23105 } else {
23106 util.printDebug(err);
23107 }
23108 }
23109 }
23110 }
23111
23112 readSubPackets(bytes, trusted = true, config) {
23113 // Two-octet scalar octet count for following subpacket data.
23114 const subpacketLength = util.readNumber(bytes.subarray(0, 2));
23115
23116 let i = 2;
23117
23118 // subpacket data set (zero or more subpackets)
23119 while (i < 2 + subpacketLength) {
23120 const len = readSimpleLength(bytes.subarray(i, bytes.length));
23121 i += len.offset;
23122
23123 this.readSubPacket(bytes.subarray(i, i + len.len), trusted, config);
23124
23125 i += len.len;
23126 }
23127
23128 return i;
23129 }
23130
23131 // Produces data to produce signature on
23132 toSign(type, data) {
23133 const t = enums.signature;
23134
23135 switch (type) {
23136 case t.binary:
23137 if (data.text !== null) {
23138 return util.encodeUTF8(data.getText(true));
23139 }
23140 return data.getBytes(true);
23141
23142 case t.text: {
23143 const bytes = data.getBytes(true);
23144 // normalize EOL to \r\n
23145 return util.canonicalizeEOL(bytes);
23146 }
23147 case t.standalone:
23148 return new Uint8Array(0);
23149
23150 case t.certGeneric:
23151 case t.certPersona:
23152 case t.certCasual:
23153 case t.certPositive:
23154 case t.certRevocation: {
23155 let packet;
23156 let tag;
23157
23158 if (data.userID) {
23159 tag = 0xB4;
23160 packet = data.userID;
23161 } else if (data.userAttribute) {
23162 tag = 0xD1;
23163 packet = data.userAttribute;
23164 } else {
23165 throw new Error('Either a userID or userAttribute packet needs to be ' +
23166 'supplied for certification.');
23167 }
23168
23169 const bytes = packet.write();
23170
23171 return util.concat([this.toSign(t.key, data),
23172 new Uint8Array([tag]),
23173 util.writeNumber(bytes.length, 4),
23174 bytes]);
23175 }
23176 case t.subkeyBinding:
23177 case t.subkeyRevocation:
23178 case t.keyBinding:
23179 return util.concat([this.toSign(t.key, data), this.toSign(t.key, {
23180 key: data.bind
23181 })]);
23182
23183 case t.key:
23184 if (data.key === undefined) {
23185 throw new Error('Key packet is required for this signature.');
23186 }
23187 return data.key.writeForHash(this.version);
23188
23189 case t.keyRevocation:
23190 return this.toSign(t.key, data);
23191 case t.timestamp:
23192 return new Uint8Array(0);
23193 case t.thirdParty:
23194 throw new Error('Not implemented');
23195 default:
23196 throw new Error('Unknown signature type.');
23197 }
23198 }
23199
23200 calculateTrailer(data, detached) {
23201 let length = 0;
23202 return transform(clone(this.signatureData), value => {
23203 length += value.length;
23204 }, () => {
23205 const arr = [];
23206 if (this.version === 5 && (this.signatureType === enums.signature.binary || this.signatureType === enums.signature.text)) {
23207 if (detached) {
23208 arr.push(new Uint8Array(6));
23209 } else {
23210 arr.push(data.writeHeader());
23211 }
23212 }
23213 arr.push(new Uint8Array([this.version, 0xFF]));
23214 if (this.version === 5) {
23215 arr.push(new Uint8Array(4));
23216 }
23217 arr.push(util.writeNumber(length, 4));
23218 // For v5, this should really be writeNumber(length, 8) rather than the
23219 // hardcoded 4 zero bytes above
23220 return util.concat(arr);
23221 });
23222 }
23223
23224 toHash(signatureType, data, detached = false) {
23225 const bytes = this.toSign(signatureType, data);
23226
23227 return util.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]);
23228 }
23229
23230 async hash(signatureType, data, toHash, detached = false) {
23231 const hashAlgorithm = enums.write(enums.hash, this.hashAlgorithm);
23232 if (!toHash) toHash = this.toHash(signatureType, data, detached);
23233 return mod.hash.digest(hashAlgorithm, toHash);
23234 }
23235
23236 /**
23237 * verifies the signature packet. Note: not all signature types are implemented
23238 * @param {PublicSubkeyPacket|PublicKeyPacket|
23239 * SecretSubkeyPacket|SecretKeyPacket} key - the public key to verify the signature
23240 * @param {module:enums.signature} signatureType - Expected signature type
23241 * @param {String|Object} data - Data which on the signature applies
23242 * @param {Date} [date] - Use the given date instead of the current time to check for signature validity and expiration
23243 * @param {Boolean} [detached] - Whether to verify a detached signature
23244 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23245 * @throws {Error} if signature validation failed
23246 * @async
23247 */
23248 async verify(key, signatureType, data, date = new Date(), detached = false, config = defaultConfig) {
23249 const publicKeyAlgorithm = enums.write(enums.publicKey, this.publicKeyAlgorithm);
23250 const hashAlgorithm = enums.write(enums.hash, this.hashAlgorithm);
23251 if (!this.issuerKeyID.equals(key.getKeyID())) {
23252 throw new Error('Signature was not issued by the given public key');
23253 }
23254 if (publicKeyAlgorithm !== enums.write(enums.publicKey, key.algorithm)) {
23255 throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');
23256 }
23257
23258 const isMessageSignature = signatureType === enums.signature.binary || signatureType === enums.signature.text;
23259 // Cryptographic validity is cached after one successful verification.
23260 // However, for message signatures, we always re-verify, since the passed `data` can change
23261 const skipVerify = this[verified] && !isMessageSignature;
23262 if (!skipVerify) {
23263 let toHash;
23264 let hash;
23265 if (this.hashed) {
23266 hash = await this.hashed;
23267 } else {
23268 toHash = this.toHash(signatureType, data, detached);
23269 hash = await this.hash(signatureType, data, toHash);
23270 }
23271 hash = await readToEnd(hash);
23272 if (this.signedHashValue[0] !== hash[0] ||
23273 this.signedHashValue[1] !== hash[1]) {
23274 throw new Error('Signed digest did not match');
23275 }
23276
23277 this.params = await this.params;
23278
23279 this[verified] = await mod.signature.verify(
23280 publicKeyAlgorithm, hashAlgorithm, this.params, key.publicParams,
23281 toHash, hash
23282 );
23283
23284 if (!this[verified]) {
23285 throw new Error('Signature verification failed');
23286 }
23287 }
23288
23289 const normDate = util.normalizeDate(date);
23290 if (normDate && this.created > normDate) {
23291 throw new Error('Signature creation time is in the future');
23292 }
23293 if (normDate && normDate >= this.getExpirationTime()) {
23294 throw new Error('Signature is expired');
23295 }
23296 if (config.rejectHashAlgorithms.has(hashAlgorithm)) {
23297 throw new Error('Insecure hash algorithm: ' + enums.read(enums.hash, hashAlgorithm).toUpperCase());
23298 }
23299 if (config.rejectMessageHashAlgorithms.has(hashAlgorithm) &&
23300 [enums.signature.binary, enums.signature.text].includes(this.signatureType)) {
23301 throw new Error('Insecure message hash algorithm: ' + enums.read(enums.hash, hashAlgorithm).toUpperCase());
23302 }
23303 this.rawNotations.forEach(({ name, critical }) => {
23304 if (critical && (config.knownNotations.indexOf(name) < 0)) {
23305 throw new Error(`Unknown critical notation: ${name}`);
23306 }
23307 });
23308 if (this.revocationKeyClass !== null) {
23309 throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');
23310 }
23311 }
23312
23313 /**
23314 * Verifies signature expiration date
23315 * @param {Date} [date] - Use the given date for verification instead of the current time
23316 * @returns {Boolean} True if expired.
23317 */
23318 isExpired(date = new Date()) {
23319 const normDate = util.normalizeDate(date);
23320 if (normDate !== null) {
23321 return !(this.created <= normDate && normDate < this.getExpirationTime());
23322 }
23323 return false;
23324 }
23325
23326 /**
23327 * Returns the expiration time of the signature or Infinity if signature does not expire
23328 * @returns {Date | Infinity} Expiration time.
23329 */
23330 getExpirationTime() {
23331 return this.signatureNeverExpires ? Infinity : new Date(this.created.getTime() + this.signatureExpirationTime * 1000);
23332 }
23333 }
23334
23335 /**
23336 * Creates a string representation of a sub signature packet
23337 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}
23338 * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}
23339 * @param {Integer} type - Subpacket signature type.
23340 * @param {String} data - Data to be included
23341 * @returns {String} A string-representation of a sub signature packet.
23342 * @private
23343 */
23344 function writeSubPacket(type, data) {
23345 const arr = [];
23346 arr.push(writeSimpleLength(data.length + 1));
23347 arr.push(new Uint8Array([type]));
23348 arr.push(data);
23349 return util.concat(arr);
23350 }
23351
23352 // GPG4Browsers - An OpenPGP implementation in javascript
23353
23354 const VERSION = 3;
23355
23356 /**
23357 * Implementation of the One-Pass Signature Packets (Tag 4)
23358 *
23359 * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:
23360 * The One-Pass Signature packet precedes the signed data and contains
23361 * enough information to allow the receiver to begin calculating any
23362 * hashes needed to verify the signature. It allows the Signature
23363 * packet to be placed at the end of the message, so that the signer
23364 * can compute the entire signed message in one pass.
23365 */
23366 class OnePassSignaturePacket {
23367 static get tag() {
23368 return enums.packet.onePassSignature;
23369 }
23370
23371 constructor() {
23372 /** A one-octet version number. The current version is 3. */
23373 this.version = null;
23374 /**
23375 * A one-octet signature type.
23376 * Signature types are described in
23377 * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.
23378 */
23379 this.signatureType = null;
23380 /**
23381 * A one-octet number describing the hash algorithm used.
23382 * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}
23383 */
23384 this.hashAlgorithm = null;
23385 /**
23386 * A one-octet number describing the public-key algorithm used.
23387 * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}
23388 */
23389 this.publicKeyAlgorithm = null;
23390 /** An eight-octet number holding the Key ID of the signing key. */
23391 this.issuerKeyID = null;
23392 /**
23393 * A one-octet number holding a flag showing whether the signature is nested.
23394 * A zero value indicates that the next packet is another One-Pass Signature packet
23395 * that describes another signature to be applied to the same message data.
23396 */
23397 this.flags = null;
23398 }
23399
23400 /**
23401 * parsing function for a one-pass signature packet (tag 4).
23402 * @param {Uint8Array} bytes - Payload of a tag 4 packet
23403 * @returns {OnePassSignaturePacket} Object representation.
23404 */
23405 read(bytes) {
23406 let mypos = 0;
23407 // A one-octet version number. The current version is 3.
23408 this.version = bytes[mypos++];
23409 if (this.version !== VERSION) {
23410 throw new UnsupportedError(`Version ${this.version} of the one-pass signature packet is unsupported.`);
23411 }
23412
23413 // A one-octet signature type. Signature types are described in
23414 // Section 5.2.1.
23415 this.signatureType = bytes[mypos++];
23416
23417 // A one-octet number describing the hash algorithm used.
23418 this.hashAlgorithm = bytes[mypos++];
23419
23420 // A one-octet number describing the public-key algorithm used.
23421 this.publicKeyAlgorithm = bytes[mypos++];
23422
23423 // An eight-octet number holding the Key ID of the signing key.
23424 this.issuerKeyID = new KeyID();
23425 this.issuerKeyID.read(bytes.subarray(mypos, mypos + 8));
23426 mypos += 8;
23427
23428 // A one-octet number holding a flag showing whether the signature
23429 // is nested. A zero value indicates that the next packet is
23430 // another One-Pass Signature packet that describes another
23431 // signature to be applied to the same message data.
23432 this.flags = bytes[mypos++];
23433 return this;
23434 }
23435
23436 /**
23437 * creates a string representation of a one-pass signature packet
23438 * @returns {Uint8Array} A Uint8Array representation of a one-pass signature packet.
23439 */
23440 write() {
23441 const start = new Uint8Array([VERSION, enums.write(enums.signature, this.signatureType),
23442 enums.write(enums.hash, this.hashAlgorithm),
23443 enums.write(enums.publicKey, this.publicKeyAlgorithm)]);
23444
23445 const end = new Uint8Array([this.flags]);
23446
23447 return util.concatUint8Array([start, this.issuerKeyID.write(), end]);
23448 }
23449
23450 calculateTrailer(...args) {
23451 return fromAsync(async () => SignaturePacket.prototype.calculateTrailer.apply(await this.correspondingSig, args));
23452 }
23453
23454 async verify() {
23455 const correspondingSig = await this.correspondingSig;
23456 if (!correspondingSig || correspondingSig.constructor.tag !== enums.packet.signature) {
23457 throw new Error('Corresponding signature packet missing');
23458 }
23459 if (
23460 correspondingSig.signatureType !== this.signatureType ||
23461 correspondingSig.hashAlgorithm !== this.hashAlgorithm ||
23462 correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm ||
23463 !correspondingSig.issuerKeyID.equals(this.issuerKeyID)
23464 ) {
23465 throw new Error('Corresponding signature packet does not match one-pass signature packet');
23466 }
23467 correspondingSig.hashed = this.hashed;
23468 return correspondingSig.verify.apply(correspondingSig, arguments);
23469 }
23470 }
23471
23472 OnePassSignaturePacket.prototype.hash = SignaturePacket.prototype.hash;
23473 OnePassSignaturePacket.prototype.toHash = SignaturePacket.prototype.toHash;
23474 OnePassSignaturePacket.prototype.toSign = SignaturePacket.prototype.toSign;
23475
23476 /**
23477 * Instantiate a new packet given its tag
23478 * @function newPacketFromTag
23479 * @param {module:enums.packet} tag - Property value from {@link module:enums.packet}
23480 * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
23481 * @returns {Object} New packet object with type based on tag
23482 * @throws {Error|UnsupportedError} for disallowed or unknown packets
23483 */
23484 function newPacketFromTag(tag, allowedPackets) {
23485 if (!allowedPackets[tag]) {
23486 // distinguish between disallowed packets and unknown ones
23487 let packetType;
23488 try {
23489 packetType = enums.read(enums.packet, tag);
23490 } catch (e) {
23491 throw new UnsupportedError(`Unknown packet type with tag: ${tag}`);
23492 }
23493 throw new Error(`Packet not allowed in this context: ${packetType}`);
23494 }
23495 return new allowedPackets[tag]();
23496 }
23497
23498 /**
23499 * This class represents a list of openpgp packets.
23500 * Take care when iterating over it - the packets themselves
23501 * are stored as numerical indices.
23502 * @extends Array
23503 */
23504 class PacketList extends Array {
23505 /**
23506 * Parses the given binary data and returns a list of packets.
23507 * Equivalent to calling `read` on an empty PacketList instance.
23508 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - binary data to parse
23509 * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
23510 * @param {Object} [config] - full configuration, defaults to openpgp.config
23511 * @returns {PacketList} parsed list of packets
23512 * @throws on parsing errors
23513 * @async
23514 */
23515 static async fromBinary(bytes, allowedPackets, config = defaultConfig) {
23516 const packets = new PacketList();
23517 await packets.read(bytes, allowedPackets, config);
23518 return packets;
23519 }
23520
23521 /**
23522 * Reads a stream of binary data and interprets it as a list of packets.
23523 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - binary data to parse
23524 * @param {Object} allowedPackets - mapping where keys are allowed packet tags, pointing to their Packet class
23525 * @param {Object} [config] - full configuration, defaults to openpgp.config
23526 * @throws on parsing errors
23527 * @async
23528 */
23529 async read(bytes, allowedPackets, config = defaultConfig) {
23530 this.stream = transformPair(bytes, async (readable, writable) => {
23531 const writer = getWriter(writable);
23532 try {
23533 while (true) {
23534 await writer.ready;
23535 const done = await readPackets(readable, async parsed => {
23536 try {
23537 if (parsed.tag === enums.packet.marker || parsed.tag === enums.packet.trust) {
23538 // According to the spec, these packet types should be ignored and not cause parsing errors, even if not esplicitly allowed:
23539 // - Marker packets MUST be ignored when received: https://github.com/openpgpjs/openpgpjs/issues/1145
23540 // - Trust packets SHOULD be ignored outside of keyrings (unsupported): https://datatracker.ietf.org/doc/html/rfc4880#section-5.10
23541 return;
23542 }
23543 const packet = newPacketFromTag(parsed.tag, allowedPackets);
23544 packet.packets = new PacketList();
23545 packet.fromStream = util.isStream(parsed.packet);
23546 await packet.read(parsed.packet, config);
23547 await writer.write(packet);
23548 } catch (e) {
23549 const throwUnsupportedError = !config.ignoreUnsupportedPackets && e instanceof UnsupportedError;
23550 const throwMalformedError = !config.ignoreMalformedPackets && !(e instanceof UnsupportedError);
23551 if (throwUnsupportedError || throwMalformedError || supportsStreaming(parsed.tag)) {
23552 // The packets that support streaming are the ones that contain message data.
23553 // Those are also the ones we want to be more strict about and throw on parse errors
23554 // (since we likely cannot process the message without these packets anyway).
23555 await writer.abort(e);
23556 }
23557 util.printDebugError(e);
23558 }
23559 });
23560 if (done) {
23561 await writer.ready;
23562 await writer.close();
23563 return;
23564 }
23565 }
23566 } catch (e) {
23567 await writer.abort(e);
23568 }
23569 });
23570
23571 // Wait until first few packets have been read
23572 const reader = getReader(this.stream);
23573 while (true) {
23574 const { done, value } = await reader.read();
23575 if (!done) {
23576 this.push(value);
23577 } else {
23578 this.stream = null;
23579 }
23580 if (done || supportsStreaming(value.constructor.tag)) {
23581 break;
23582 }
23583 }
23584 reader.releaseLock();
23585 }
23586
23587 /**
23588 * Creates a binary representation of openpgp objects contained within the
23589 * class instance.
23590 * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.
23591 */
23592 write() {
23593 const arr = [];
23594
23595 for (let i = 0; i < this.length; i++) {
23596 const packetbytes = this[i].write();
23597 if (util.isStream(packetbytes) && supportsStreaming(this[i].constructor.tag)) {
23598 let buffer = [];
23599 let bufferLength = 0;
23600 const minLength = 512;
23601 arr.push(writeTag(this[i].constructor.tag));
23602 arr.push(transform(packetbytes, value => {
23603 buffer.push(value);
23604 bufferLength += value.length;
23605 if (bufferLength >= minLength) {
23606 const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);
23607 const chunkSize = 2 ** powerOf2;
23608 const bufferConcat = util.concat([writePartialLength(powerOf2)].concat(buffer));
23609 buffer = [bufferConcat.subarray(1 + chunkSize)];
23610 bufferLength = buffer[0].length;
23611 return bufferConcat.subarray(0, 1 + chunkSize);
23612 }
23613 }, () => util.concat([writeSimpleLength(bufferLength)].concat(buffer))));
23614 } else {
23615 if (util.isStream(packetbytes)) {
23616 let length = 0;
23617 arr.push(transform(clone(packetbytes), value => {
23618 length += value.length;
23619 }, () => writeHeader(this[i].constructor.tag, length)));
23620 } else {
23621 arr.push(writeHeader(this[i].constructor.tag, packetbytes.length));
23622 }
23623 arr.push(packetbytes);
23624 }
23625 }
23626
23627 return util.concat(arr);
23628 }
23629
23630 /**
23631 * Creates a new PacketList with all packets matching the given tag(s)
23632 * @param {...module:enums.packet} tags - packet tags to look for
23633 * @returns {PacketList}
23634 */
23635 filterByTag(...tags) {
23636 const filtered = new PacketList();
23637
23638 const handle = tag => packetType => tag === packetType;
23639
23640 for (let i = 0; i < this.length; i++) {
23641 if (tags.some(handle(this[i].constructor.tag))) {
23642 filtered.push(this[i]);
23643 }
23644 }
23645
23646 return filtered;
23647 }
23648
23649 /**
23650 * Traverses packet list and returns first packet with matching tag
23651 * @param {module:enums.packet} tag - The packet tag
23652 * @returns {Packet|undefined}
23653 */
23654 findPacket(tag) {
23655 return this.find(packet => packet.constructor.tag === tag);
23656 }
23657
23658 /**
23659 * Find indices of packets with the given tag(s)
23660 * @param {...module:enums.packet} tags - packet tags to look for
23661 * @returns {Integer[]} packet indices
23662 */
23663 indexOfTag(...tags) {
23664 const tagIndex = [];
23665 const that = this;
23666
23667 const handle = tag => packetType => tag === packetType;
23668
23669 for (let i = 0; i < this.length; i++) {
23670 if (tags.some(handle(that[i].constructor.tag))) {
23671 tagIndex.push(i);
23672 }
23673 }
23674 return tagIndex;
23675 }
23676 }
23677
23678 // GPG4Browsers - An OpenPGP implementation in javascript
23679
23680 // A Compressed Data packet can contain the following packet types
23681 const allowedPackets = /*#__PURE__*/ util.constructAllowedPackets([
23682 LiteralDataPacket,
23683 OnePassSignaturePacket,
23684 SignaturePacket
23685 ]);
23686
23687 /**
23688 * Implementation of the Compressed Data Packet (Tag 8)
23689 *
23690 * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:
23691 * The Compressed Data packet contains compressed data. Typically,
23692 * this packet is found as the contents of an encrypted packet, or following
23693 * a Signature or One-Pass Signature packet, and contains a literal data packet.
23694 */
23695 class CompressedDataPacket {
23696 static get tag() {
23697 return enums.packet.compressedData;
23698 }
23699
23700 /**
23701 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23702 */
23703 constructor(config = defaultConfig) {
23704 /**
23705 * List of packets
23706 * @type {PacketList}
23707 */
23708 this.packets = null;
23709 /**
23710 * Compression algorithm
23711 * @type {compression}
23712 */
23713 this.algorithm = enums.read(enums.compression, config.preferredCompressionAlgorithm);
23714
23715 /**
23716 * Compressed packet data
23717 * @type {Uint8Array | ReadableStream<Uint8Array>}
23718 */
23719 this.compressed = null;
23720
23721 /**
23722 * zip/zlib compression level, between 1 and 9
23723 */
23724 this.deflateLevel = config.deflateLevel;
23725 }
23726
23727 /**
23728 * Parsing function for the packet.
23729 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes - Payload of a tag 8 packet
23730 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23731 */
23732 async read(bytes, config = defaultConfig) {
23733 await parse(bytes, async reader => {
23734
23735 // One octet that gives the algorithm used to compress the packet.
23736 this.algorithm = enums.read(enums.compression, await reader.readByte());
23737
23738 // Compressed data, which makes up the remainder of the packet.
23739 this.compressed = reader.remainder();
23740
23741 await this.decompress(config);
23742 });
23743 }
23744
23745
23746 /**
23747 * Return the compressed packet.
23748 * @returns {Uint8Array | ReadableStream<Uint8Array>} Binary compressed packet.
23749 */
23750 write() {
23751 if (this.compressed === null) {
23752 this.compress();
23753 }
23754
23755 return util.concat([new Uint8Array([enums.write(enums.compression, this.algorithm)]), this.compressed]);
23756 }
23757
23758
23759 /**
23760 * Decompression method for decompressing the compressed data
23761 * read by read_packet
23762 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23763 */
23764 async decompress(config = defaultConfig) {
23765
23766 if (!decompress_fns[this.algorithm]) {
23767 throw new Error(this.algorithm + ' decompression not supported');
23768 }
23769
23770 this.packets = await PacketList.fromBinary(decompress_fns[this.algorithm](this.compressed), allowedPackets, config);
23771 }
23772
23773 /**
23774 * Compress the packet data (member decompressedData)
23775 */
23776 compress() {
23777 if (!compress_fns[this.algorithm]) {
23778 throw new Error(this.algorithm + ' compression not supported');
23779 }
23780
23781 this.compressed = compress_fns[this.algorithm](this.packets.write(), this.deflateLevel);
23782 }
23783 }
23784
23785 //////////////////////////
23786 // //
23787 // Helper functions //
23788 // //
23789 //////////////////////////
23790
23791
23792 const nodeZlib = util.getNodeZlib();
23793
23794 function uncompressed(data) {
23795 return data;
23796 }
23797
23798 function node_zlib(func, create, options = {}) {
23799 return function (data) {
23800 if (!util.isStream(data) || isArrayStream(data)) {
23801 return fromAsync(() => readToEnd(data).then(data => {
23802 return new Promise((resolve, reject) => {
23803 func(data, options, (err, result) => {
23804 if (err) return reject(err);
23805 resolve(result);
23806 });
23807 });
23808 }));
23809 }
23810 return nodeToWeb(webToNode(data).pipe(create(options)));
23811 };
23812 }
23813
23814 function pako_zlib(constructor, options = {}) {
23815 return function(data) {
23816 const obj = new constructor(options);
23817 return transform(data, value => {
23818 if (value.length) {
23819 obj.push(value, Z_SYNC_FLUSH);
23820 return obj.result;
23821 }
23822 }, () => {
23823 if (constructor === Deflate) {
23824 obj.push([], Z_FINISH);
23825 return obj.result;
23826 }
23827 });
23828 };
23829 }
23830
23831 function bzip2(func) {
23832 return function(data) {
23833 return fromAsync(async () => func(await readToEnd(data)));
23834 };
23835 }
23836
23837 const compress_fns = nodeZlib ? {
23838 zip: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflateRaw, nodeZlib.createDeflateRaw, { level })(compressed),
23839 zlib: /*#__PURE__*/ (compressed, level) => node_zlib(nodeZlib.deflate, nodeZlib.createDeflate, { level })(compressed)
23840 } : {
23841 zip: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { raw: true, level })(compressed),
23842 zlib: /*#__PURE__*/ (compressed, level) => pako_zlib(Deflate, { level })(compressed)
23843 };
23844
23845 const decompress_fns = nodeZlib ? {
23846 uncompressed: uncompressed,
23847 zip: /*#__PURE__*/ node_zlib(nodeZlib.inflateRaw, nodeZlib.createInflateRaw),
23848 zlib: /*#__PURE__*/ node_zlib(nodeZlib.inflate, nodeZlib.createInflate),
23849 bzip2: /*#__PURE__*/ bzip2(lib_4)
23850 } : {
23851 uncompressed: uncompressed,
23852 zip: /*#__PURE__*/ pako_zlib(Inflate, { raw: true }),
23853 zlib: /*#__PURE__*/ pako_zlib(Inflate),
23854 bzip2: /*#__PURE__*/ bzip2(lib_4)
23855 };
23856
23857 // GPG4Browsers - An OpenPGP implementation in javascript
23858
23859 // A SEIP packet can contain the following packet types
23860 const allowedPackets$1 = /*#__PURE__*/ util.constructAllowedPackets([
23861 LiteralDataPacket,
23862 CompressedDataPacket,
23863 OnePassSignaturePacket,
23864 SignaturePacket
23865 ]);
23866
23867 const VERSION$1 = 1; // A one-octet version number of the data packet.
23868
23869 /**
23870 * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)
23871 *
23872 * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:
23873 * The Symmetrically Encrypted Integrity Protected Data packet is
23874 * a variant of the Symmetrically Encrypted Data packet. It is a new feature
23875 * created for OpenPGP that addresses the problem of detecting a modification to
23876 * encrypted data. It is used in combination with a Modification Detection Code
23877 * packet.
23878 */
23879 class SymEncryptedIntegrityProtectedDataPacket {
23880 static get tag() {
23881 return enums.packet.symEncryptedIntegrityProtectedData;
23882 }
23883
23884 constructor() {
23885 this.version = VERSION$1;
23886 this.encrypted = null;
23887 this.packets = null;
23888 }
23889
23890 async read(bytes) {
23891 await parse(bytes, async reader => {
23892 const version = await reader.readByte();
23893 // - A one-octet version number. The only currently defined value is 1.
23894 if (version !== VERSION$1) {
23895 throw new UnsupportedError(`Version ${version} of the SEIP packet is unsupported.`);
23896 }
23897
23898 // - Encrypted data, the output of the selected symmetric-key cipher
23899 // operating in Cipher Feedback mode with shift amount equal to the
23900 // block size of the cipher (CFB-n where n is the block size).
23901 this.encrypted = reader.remainder();
23902 });
23903 }
23904
23905 write() {
23906 return util.concat([new Uint8Array([VERSION$1]), this.encrypted]);
23907 }
23908
23909 /**
23910 * Encrypt the payload in the packet.
23911 * @param {String} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used e.g. 'aes128'
23912 * @param {Uint8Array} key - The key of cipher blocksize length to be used
23913 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23914 * @returns {Promise<Boolean>}
23915 * @async
23916 */
23917 async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
23918 let bytes = this.packets.write();
23919 if (isArrayStream(bytes)) bytes = await readToEnd(bytes);
23920 const prefix = await mod.getPrefixRandom(sessionKeyAlgorithm);
23921 const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet
23922
23923 const tohash = util.concat([prefix, bytes, mdc]);
23924 const hash = await mod.hash.sha1(passiveClone(tohash));
23925 const plaintext = util.concat([tohash, hash]);
23926
23927 this.encrypted = await mod.mode.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(mod.cipher[sessionKeyAlgorithm].blockSize), config);
23928 return true;
23929 }
23930
23931 /**
23932 * Decrypts the encrypted data contained in the packet.
23933 * @param {String} sessionKeyAlgorithm - The selected symmetric encryption algorithm to be used e.g. 'aes128'
23934 * @param {Uint8Array} key - The key of cipher blocksize length to be used
23935 * @param {Object} [config] - Full configuration, defaults to openpgp.config
23936 * @returns {Promise<Boolean>}
23937 * @async
23938 */
23939 async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
23940 let encrypted = clone(this.encrypted);
23941 if (isArrayStream(encrypted)) encrypted = await readToEnd(encrypted);
23942 const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(mod.cipher[sessionKeyAlgorithm].blockSize));
23943
23944 // there must be a modification detection code packet as the
23945 // last packet and everything gets hashed except the hash itself
23946 const realHash = slice(passiveClone(decrypted), -20);
23947 const tohash = slice(decrypted, 0, -20);
23948 const verifyHash = Promise.all([
23949 readToEnd(await mod.hash.sha1(passiveClone(tohash))),
23950 readToEnd(realHash)
23951 ]).then(([hash, mdc]) => {
23952 if (!util.equalsUint8Array(hash, mdc)) {
23953 throw new Error('Modification detected.');
23954 }
23955 return new Uint8Array();
23956 });
23957 const bytes = slice(tohash, mod.cipher[sessionKeyAlgorithm].blockSize + 2); // Remove random prefix
23958 let packetbytes = slice(bytes, 0, -2); // Remove MDC packet
23959 packetbytes = concat([packetbytes, fromAsync(() => verifyHash)]);
23960 if (!util.isStream(encrypted) || !config.allowUnauthenticatedStream) {
23961 packetbytes = await readToEnd(packetbytes);
23962 }
23963 this.packets = await PacketList.fromBinary(packetbytes, allowedPackets$1, config);
23964 return true;
23965 }
23966 }
23967
23968 // OpenPGP.js - An OpenPGP implementation in javascript
23969
23970 // An AEAD-encrypted Data packet can contain the following packet types
23971 const allowedPackets$2 = /*#__PURE__*/ util.constructAllowedPackets([
23972 LiteralDataPacket,
23973 CompressedDataPacket,
23974 OnePassSignaturePacket,
23975 SignaturePacket
23976 ]);
23977
23978 const VERSION$2 = 1; // A one-octet version number of the data packet.
23979
23980 /**
23981 * Implementation of the Symmetrically Encrypted Authenticated Encryption with
23982 * Additional Data (AEAD) Protected Data Packet
23983 *
23984 * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:
23985 * AEAD Protected Data Packet
23986 */
23987 class AEADEncryptedDataPacket {
23988 static get tag() {
23989 return enums.packet.aeadEncryptedData;
23990 }
23991
23992 constructor() {
23993 this.version = VERSION$2;
23994 this.cipherAlgo = null;
23995 this.aeadAlgorithm = 'eax';
23996 this.aeadAlgo = null;
23997 this.chunkSizeByte = null;
23998 this.iv = null;
23999 this.encrypted = null;
24000 this.packets = null;
24001 }
24002
24003 /**
24004 * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
24005 * @param {Uint8Array | ReadableStream<Uint8Array>} bytes
24006 */
24007 async read(bytes) {
24008 await parse(bytes, async reader => {
24009 const version = await reader.readByte();
24010 if (version !== VERSION$2) { // The only currently defined value is 1.
24011 throw new UnsupportedError(`Version ${version} of the AEAD-encrypted data packet is not supported.`);
24012 }
24013 this.cipherAlgo = await reader.readByte();
24014 this.aeadAlgo = await reader.readByte();
24015 this.chunkSizeByte = await reader.readByte();
24016 const mode = mod.mode[enums.read(enums.aead, this.aeadAlgo)];
24017 this.iv = await reader.readBytes(mode.ivLength);
24018 this.encrypted = reader.remainder();
24019 });
24020 }
24021
24022 /**
24023 * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
24024 * @returns {Uint8Array | ReadableStream<Uint8Array>} The encrypted payload.
24025 */
24026 write() {
24027 return util.concat([new Uint8Array([this.version, this.cipherAlgo, this.aeadAlgo, this.chunkSizeByte]), this.iv, this.encrypted]);
24028 }
24029
24030 /**
24031 * Decrypt the encrypted payload.
24032 * @param {String} sessionKeyAlgorithm - The session key's cipher algorithm e.g. 'aes128'
24033 * @param {Uint8Array} key - The session key used to encrypt the payload
24034 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24035 * @throws {Error} if decryption was not successful
24036 * @async
24037 */
24038 async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
24039 this.packets = await PacketList.fromBinary(
24040 await this.crypt('decrypt', key, clone(this.encrypted)),
24041 allowedPackets$2,
24042 config
24043 );
24044 }
24045
24046 /**
24047 * Encrypt the packet list payload.
24048 * @param {String} sessionKeyAlgorithm - The session key's cipher algorithm e.g. 'aes128'
24049 * @param {Uint8Array} key - The session key used to encrypt the payload
24050 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24051 * @throws {Error} if encryption was not successful
24052 * @async
24053 */
24054 async encrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
24055 this.cipherAlgo = enums.write(enums.symmetric, sessionKeyAlgorithm);
24056 this.aeadAlgo = enums.write(enums.aead, this.aeadAlgorithm);
24057 const mode = mod.mode[enums.read(enums.aead, this.aeadAlgo)];
24058 this.iv = await mod.random.getRandomBytes(mode.ivLength); // generate new random IV
24059 this.chunkSizeByte = config.aeadChunkSizeByte;
24060 const data = this.packets.write();
24061 this.encrypted = await this.crypt('encrypt', key, data);
24062 }
24063
24064 /**
24065 * En/decrypt the payload.
24066 * @param {encrypt|decrypt} fn - Whether to encrypt or decrypt
24067 * @param {Uint8Array} key - The session key used to en/decrypt the payload
24068 * @param {Uint8Array | ReadableStream<Uint8Array>} data - The data to en/decrypt
24069 * @returns {Promise<Uint8Array | ReadableStream<Uint8Array>>}
24070 * @async
24071 */
24072 async crypt(fn, key, data) {
24073 const cipher = enums.read(enums.symmetric, this.cipherAlgo);
24074 const mode = mod.mode[enums.read(enums.aead, this.aeadAlgo)];
24075 const modeInstance = await mode(cipher, key);
24076 const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;
24077 const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;
24078 const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))
24079 const adataBuffer = new ArrayBuffer(21);
24080 const adataArray = new Uint8Array(adataBuffer, 0, 13);
24081 const adataTagArray = new Uint8Array(adataBuffer);
24082 const adataView = new DataView(adataBuffer);
24083 const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);
24084 adataArray.set([0xC0 | AEADEncryptedDataPacket.tag, this.version, this.cipherAlgo, this.aeadAlgo, this.chunkSizeByte], 0);
24085 let chunkIndex = 0;
24086 let latestPromise = Promise.resolve();
24087 let cryptedBytes = 0;
24088 let queuedBytes = 0;
24089 const iv = this.iv;
24090 return transformPair(data, async (readable, writable) => {
24091 if (util.isStream(readable) !== 'array') {
24092 const buffer = new TransformStream({}, {
24093 highWaterMark: util.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6),
24094 size: array => array.length
24095 });
24096 pipe(buffer.readable, writable);
24097 writable = buffer.writable;
24098 }
24099 const reader = getReader(readable);
24100 const writer = getWriter(writable);
24101 try {
24102 while (true) {
24103 let chunk = await reader.readBytes(chunkSize + tagLengthIfDecrypting) || new Uint8Array();
24104 const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);
24105 chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);
24106 let cryptedPromise;
24107 let done;
24108 if (!chunkIndex || chunk.length) {
24109 reader.unshift(finalChunk);
24110 cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray);
24111 queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;
24112 } else {
24113 // After the last chunk, we either encrypt a final, empty
24114 // data chunk to get the final authentication tag or
24115 // validate that final authentication tag.
24116 adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...)
24117 cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray);
24118 queuedBytes += tagLengthIfEncrypting;
24119 done = true;
24120 }
24121 cryptedBytes += chunk.length - tagLengthIfDecrypting;
24122 // eslint-disable-next-line no-loop-func
24123 latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {
24124 await writer.ready;
24125 await writer.write(crypted);
24126 queuedBytes -= crypted.length;
24127 }).catch(err => writer.abort(err));
24128 if (done || queuedBytes > writer.desiredSize) {
24129 await latestPromise; // Respect backpressure
24130 }
24131 if (!done) {
24132 adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)
24133 } else {
24134 await writer.close();
24135 break;
24136 }
24137 }
24138 } catch (e) {
24139 await writer.abort(e);
24140 }
24141 });
24142 }
24143 }
24144
24145 // GPG4Browsers - An OpenPGP implementation in javascript
24146
24147 const VERSION$3 = 3;
24148
24149 /**
24150 * Public-Key Encrypted Session Key Packets (Tag 1)
24151 *
24152 * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:
24153 * A Public-Key Encrypted Session Key packet holds the session key
24154 * used to encrypt a message. Zero or more Public-Key Encrypted Session Key
24155 * packets and/or Symmetric-Key Encrypted Session Key packets may precede a
24156 * Symmetrically Encrypted Data Packet, which holds an encrypted message. The
24157 * message is encrypted with the session key, and the session key is itself
24158 * encrypted and stored in the Encrypted Session Key packet(s). The
24159 * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted
24160 * Session Key packet for each OpenPGP key to which the message is encrypted.
24161 * The recipient of the message finds a session key that is encrypted to their
24162 * public key, decrypts the session key, and then uses the session key to
24163 * decrypt the message.
24164 */
24165 class PublicKeyEncryptedSessionKeyPacket {
24166 static get tag() {
24167 return enums.packet.publicKeyEncryptedSessionKey;
24168 }
24169
24170 constructor() {
24171 this.version = 3;
24172
24173 this.publicKeyID = new KeyID();
24174 this.publicKeyAlgorithm = null;
24175
24176 this.sessionKey = null;
24177 this.sessionKeyAlgorithm = null;
24178
24179 /** @type {Object} */
24180 this.encrypted = {};
24181 }
24182
24183 /**
24184 * Parsing function for a publickey encrypted session key packet (tag 1).
24185 *
24186 * @param {Uint8Array} bytes - Payload of a tag 1 packet
24187 */
24188 read(bytes) {
24189 this.version = bytes[0];
24190 if (this.version !== VERSION$3) {
24191 throw new UnsupportedError(`Version ${this.version} of the PKESK packet is unsupported.`);
24192 }
24193 this.publicKeyID.read(bytes.subarray(1, bytes.length));
24194 this.publicKeyAlgorithm = enums.read(enums.publicKey, bytes[9]);
24195
24196 const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);
24197 this.encrypted = mod.parseEncSessionKeyParams(algo, bytes.subarray(10));
24198 }
24199
24200 /**
24201 * Create a binary representation of a tag 1 packet
24202 *
24203 * @returns {Uint8Array} The Uint8Array representation.
24204 */
24205 write() {
24206 const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);
24207
24208 const arr = [
24209 new Uint8Array([this.version]),
24210 this.publicKeyID.write(),
24211 new Uint8Array([enums.write(enums.publicKey, this.publicKeyAlgorithm)]),
24212 mod.serializeParams(algo, this.encrypted)
24213 ];
24214
24215 return util.concatUint8Array(arr);
24216 }
24217
24218 /**
24219 * Encrypt session key packet
24220 * @param {PublicKeyPacket} key - Public key
24221 * @throws {Error} if encryption failed
24222 * @async
24223 */
24224 async encrypt(key) {
24225 const data = util.concatUint8Array([
24226 new Uint8Array([enums.write(enums.symmetric, this.sessionKeyAlgorithm)]),
24227 this.sessionKey,
24228 util.writeChecksum(this.sessionKey)
24229 ]);
24230 const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);
24231 this.encrypted = await mod.publicKeyEncrypt(
24232 algo, key.publicParams, data, key.getFingerprintBytes());
24233 }
24234
24235 /**
24236 * Decrypts the session key (only for public key encrypted session key
24237 * packets (tag 1)
24238 * @param {SecretKeyPacket} key - decrypted private key
24239 * @throws {Error} if decryption failed
24240 * @async
24241 */
24242 async decrypt(key) {
24243 const algo = enums.write(enums.publicKey, this.publicKeyAlgorithm);
24244 const keyAlgo = enums.write(enums.publicKey, key.algorithm);
24245 // check that session key algo matches the secret key algo
24246 if (algo !== keyAlgo) {
24247 throw new Error('Decryption error');
24248 }
24249 const decoded = await mod.publicKeyDecrypt(algo, key.publicParams, key.privateParams, this.encrypted, key.getFingerprintBytes());
24250 const checksum = decoded.subarray(decoded.length - 2);
24251 const sessionKey = decoded.subarray(1, decoded.length - 2);
24252 if (!util.equalsUint8Array(checksum, util.writeChecksum(sessionKey))) {
24253 throw new Error('Decryption error');
24254 } else {
24255 this.sessionKey = sessionKey;
24256 this.sessionKeyAlgorithm = enums.read(enums.symmetric, decoded[0]);
24257 }
24258 }
24259 }
24260
24261 // GPG4Browsers - An OpenPGP implementation in javascript
24262
24263 class S2K {
24264 /**
24265 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24266 */
24267 constructor(config = defaultConfig) {
24268 /** @type {module:enums.hash} */
24269 this.algorithm = 'sha256';
24270 /** @type {module:enums.s2k} */
24271 this.type = 'iterated';
24272 /** @type {Integer} */
24273 this.c = config.s2kIterationCountByte;
24274 /** Eight bytes of salt in a binary string.
24275 * @type {String}
24276 */
24277 this.salt = null;
24278 }
24279
24280 getCount() {
24281 // Exponent bias, defined in RFC4880
24282 const expbias = 6;
24283
24284 return (16 + (this.c & 15)) << ((this.c >> 4) + expbias);
24285 }
24286
24287 /**
24288 * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).
24289 * @param {String} bytes - Payload of string-to-key specifier
24290 * @returns {Integer} Actual length of the object.
24291 */
24292 read(bytes) {
24293 let i = 0;
24294 this.type = enums.read(enums.s2k, bytes[i++]);
24295 this.algorithm = bytes[i++];
24296 if (this.type !== 'gnu') {
24297 this.algorithm = enums.read(enums.hash, this.algorithm);
24298 }
24299
24300 switch (this.type) {
24301 case 'simple':
24302 break;
24303
24304 case 'salted':
24305 this.salt = bytes.subarray(i, i + 8);
24306 i += 8;
24307 break;
24308
24309 case 'iterated':
24310 this.salt = bytes.subarray(i, i + 8);
24311 i += 8;
24312
24313 // Octet 10: count, a one-octet, coded value
24314 this.c = bytes[i++];
24315 break;
24316
24317 case 'gnu':
24318 if (util.uint8ArrayToString(bytes.subarray(i, i + 3)) === 'GNU') {
24319 i += 3; // GNU
24320 const gnuExtType = 1000 + bytes[i++];
24321 if (gnuExtType === 1001) {
24322 this.type = 'gnu-dummy';
24323 // GnuPG extension mode 1001 -- don't write secret key at all
24324 } else {
24325 throw new Error('Unknown s2k gnu protection mode.');
24326 }
24327 } else {
24328 throw new Error('Unknown s2k type.');
24329 }
24330 break;
24331
24332 default:
24333 throw new Error('Unknown s2k type.');
24334 }
24335
24336 return i;
24337 }
24338
24339 /**
24340 * Serializes s2k information
24341 * @returns {Uint8Array} Binary representation of s2k.
24342 */
24343 write() {
24344 if (this.type === 'gnu-dummy') {
24345 return new Uint8Array([101, 0, ...util.stringToUint8Array('GNU'), 1]);
24346 }
24347
24348 const arr = [new Uint8Array([enums.write(enums.s2k, this.type), enums.write(enums.hash, this.algorithm)])];
24349
24350 switch (this.type) {
24351 case 'simple':
24352 break;
24353 case 'salted':
24354 arr.push(this.salt);
24355 break;
24356 case 'iterated':
24357 arr.push(this.salt);
24358 arr.push(new Uint8Array([this.c]));
24359 break;
24360 case 'gnu':
24361 throw new Error('GNU s2k type not supported.');
24362 default:
24363 throw new Error('Unknown s2k type.');
24364 }
24365
24366 return util.concatUint8Array(arr);
24367 }
24368
24369 /**
24370 * Produces a key using the specified passphrase and the defined
24371 * hashAlgorithm
24372 * @param {String} passphrase - Passphrase containing user input
24373 * @returns {Promise<Uint8Array>} Produced key with a length corresponding to.
24374 * hashAlgorithm hash length
24375 * @async
24376 */
24377 async produceKey(passphrase, numBytes) {
24378 passphrase = util.encodeUTF8(passphrase);
24379 const algorithm = enums.write(enums.hash, this.algorithm);
24380
24381 const arr = [];
24382 let rlength = 0;
24383
24384 let prefixlen = 0;
24385 while (rlength < numBytes) {
24386 let toHash;
24387 switch (this.type) {
24388 case 'simple':
24389 toHash = util.concatUint8Array([new Uint8Array(prefixlen), passphrase]);
24390 break;
24391 case 'salted':
24392 toHash = util.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);
24393 break;
24394 case 'iterated': {
24395 const data = util.concatUint8Array([this.salt, passphrase]);
24396 let datalen = data.length;
24397 const count = Math.max(this.getCount(), datalen);
24398 toHash = new Uint8Array(prefixlen + count);
24399 toHash.set(data, prefixlen);
24400 for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {
24401 toHash.copyWithin(pos, prefixlen, pos);
24402 }
24403 break;
24404 }
24405 case 'gnu':
24406 throw new Error('GNU s2k type not supported.');
24407 default:
24408 throw new Error('Unknown s2k type.');
24409 }
24410 const result = await mod.hash.digest(algorithm, toHash);
24411 arr.push(result);
24412 rlength += result.length;
24413 prefixlen++;
24414 }
24415
24416 return util.concatUint8Array(arr).subarray(0, numBytes);
24417 }
24418 }
24419
24420 // GPG4Browsers - An OpenPGP implementation in javascript
24421
24422 /**
24423 * Symmetric-Key Encrypted Session Key Packets (Tag 3)
24424 *
24425 * {@link https://tools.ietf.org/html/rfc4880#section-5.3|RFC4880 5.3}:
24426 * The Symmetric-Key Encrypted Session Key packet holds the
24427 * symmetric-key encryption of a session key used to encrypt a message.
24428 * Zero or more Public-Key Encrypted Session Key packets and/or
24429 * Symmetric-Key Encrypted Session Key packets may precede a
24430 * Symmetrically Encrypted Data packet that holds an encrypted message.
24431 * The message is encrypted with a session key, and the session key is
24432 * itself encrypted and stored in the Encrypted Session Key packet or
24433 * the Symmetric-Key Encrypted Session Key packet.
24434 */
24435 class SymEncryptedSessionKeyPacket {
24436 static get tag() {
24437 return enums.packet.symEncryptedSessionKey;
24438 }
24439
24440 /**
24441 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24442 */
24443 constructor(config = defaultConfig) {
24444 this.version = config.aeadProtect ? 5 : 4;
24445 this.sessionKey = null;
24446 this.sessionKeyEncryptionAlgorithm = null;
24447 this.sessionKeyAlgorithm = 'aes256';
24448 this.aeadAlgorithm = enums.read(enums.aead, config.preferredAEADAlgorithm);
24449 this.encrypted = null;
24450 this.s2k = null;
24451 this.iv = null;
24452 }
24453
24454 /**
24455 * Parsing function for a symmetric encrypted session key packet (tag 3).
24456 *
24457 * @param {Uint8Array} bytes - Payload of a tag 3 packet
24458 */
24459 read(bytes) {
24460 let offset = 0;
24461
24462 // A one-octet version number. The only currently defined version is 4.
24463 this.version = bytes[offset++];
24464 if (this.version !== 4 && this.version !== 5) {
24465 throw new UnsupportedError(`Version ${this.version} of the SKESK packet is unsupported.`);
24466 }
24467
24468 // A one-octet number describing the symmetric algorithm used.
24469 const algo = enums.read(enums.symmetric, bytes[offset++]);
24470
24471 if (this.version === 5) {
24472 // A one-octet AEAD algorithm.
24473 this.aeadAlgorithm = enums.read(enums.aead, bytes[offset++]);
24474 }
24475
24476 // A string-to-key (S2K) specifier, length as defined above.
24477 this.s2k = new S2K();
24478 offset += this.s2k.read(bytes.subarray(offset, bytes.length));
24479
24480 if (this.version === 5) {
24481 const mode = mod.mode[this.aeadAlgorithm];
24482
24483 // A starting initialization vector of size specified by the AEAD
24484 // algorithm.
24485 this.iv = bytes.subarray(offset, offset += mode.ivLength);
24486 }
24487
24488 // The encrypted session key itself, which is decrypted with the
24489 // string-to-key object. This is optional in version 4.
24490 if (this.version === 5 || offset < bytes.length) {
24491 this.encrypted = bytes.subarray(offset, bytes.length);
24492 this.sessionKeyEncryptionAlgorithm = algo;
24493 } else {
24494 this.sessionKeyAlgorithm = algo;
24495 }
24496 }
24497
24498 /**
24499 * Create a binary representation of a tag 3 packet
24500 *
24501 * @returns {Uint8Array} The Uint8Array representation.
24502 */
24503 write() {
24504 const algo = this.encrypted === null ?
24505 this.sessionKeyAlgorithm :
24506 this.sessionKeyEncryptionAlgorithm;
24507
24508 let bytes;
24509
24510 if (this.version === 5) {
24511 bytes = util.concatUint8Array([new Uint8Array([this.version, enums.write(enums.symmetric, algo), enums.write(enums.aead, this.aeadAlgorithm)]), this.s2k.write(), this.iv, this.encrypted]);
24512 } else {
24513 bytes = util.concatUint8Array([new Uint8Array([this.version, enums.write(enums.symmetric, algo)]), this.s2k.write()]);
24514
24515 if (this.encrypted !== null) {
24516 bytes = util.concatUint8Array([bytes, this.encrypted]);
24517 }
24518 }
24519
24520 return bytes;
24521 }
24522
24523 /**
24524 * Decrypts the session key
24525 * @param {String} passphrase - The passphrase in string form
24526 * @throws {Error} if decryption was not successful
24527 * @async
24528 */
24529 async decrypt(passphrase) {
24530 const algo = this.sessionKeyEncryptionAlgorithm !== null ?
24531 this.sessionKeyEncryptionAlgorithm :
24532 this.sessionKeyAlgorithm;
24533
24534 const length = mod.cipher[algo].keySize;
24535 const key = await this.s2k.produceKey(passphrase, length);
24536
24537 if (this.version === 5) {
24538 const mode = mod.mode[this.aeadAlgorithm];
24539 const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, enums.write(enums.symmetric, this.sessionKeyEncryptionAlgorithm), enums.write(enums.aead, this.aeadAlgorithm)]);
24540 const modeInstance = await mode(algo, key);
24541 this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);
24542 } else if (this.encrypted !== null) {
24543 const decrypted = await mod.mode.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(mod.cipher[algo].blockSize));
24544
24545 this.sessionKeyAlgorithm = enums.read(enums.symmetric, decrypted[0]);
24546 this.sessionKey = decrypted.subarray(1, decrypted.length);
24547 } else {
24548 this.sessionKey = key;
24549 }
24550 }
24551
24552 /**
24553 * Encrypts the session key
24554 * @param {String} passphrase - The passphrase in string form
24555 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24556 * @throws {Error} if encryption was not successful
24557 * @async
24558 */
24559 async encrypt(passphrase, config = defaultConfig) {
24560 const algo = this.sessionKeyEncryptionAlgorithm !== null ?
24561 this.sessionKeyEncryptionAlgorithm :
24562 this.sessionKeyAlgorithm;
24563
24564 this.sessionKeyEncryptionAlgorithm = algo;
24565
24566 this.s2k = new S2K(config);
24567 this.s2k.salt = await mod.random.getRandomBytes(8);
24568
24569 const length = mod.cipher[algo].keySize;
24570 const key = await this.s2k.produceKey(passphrase, length);
24571
24572 if (this.sessionKey === null) {
24573 this.sessionKey = await mod.generateSessionKey(this.sessionKeyAlgorithm);
24574 }
24575
24576 if (this.version === 5) {
24577 const mode = mod.mode[this.aeadAlgorithm];
24578 this.iv = await mod.random.getRandomBytes(mode.ivLength); // generate new random IV
24579 const adata = new Uint8Array([0xC0 | SymEncryptedSessionKeyPacket.tag, this.version, enums.write(enums.symmetric, this.sessionKeyEncryptionAlgorithm), enums.write(enums.aead, this.aeadAlgorithm)]);
24580 const modeInstance = await mode(algo, key);
24581 this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata);
24582 } else {
24583 const algo_enum = new Uint8Array([enums.write(enums.symmetric, this.sessionKeyAlgorithm)]);
24584 const private_key = util.concatUint8Array([algo_enum, this.sessionKey]);
24585 this.encrypted = await mod.mode.cfb.encrypt(algo, key, private_key, new Uint8Array(mod.cipher[algo].blockSize), config);
24586 }
24587 }
24588 }
24589
24590 // GPG4Browsers - An OpenPGP implementation in javascript
24591
24592 /**
24593 * Implementation of the Key Material Packet (Tag 5,6,7,14)
24594 *
24595 * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:
24596 * A key material packet contains all the information about a public or
24597 * private key. There are four variants of this packet type, and two
24598 * major versions.
24599 *
24600 * A Public-Key packet starts a series of packets that forms an OpenPGP
24601 * key (sometimes called an OpenPGP certificate).
24602 */
24603 class PublicKeyPacket {
24604 static get tag() {
24605 return enums.packet.publicKey;
24606 }
24607
24608 /**
24609 * @param {Date} [date] - Creation date
24610 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24611 */
24612 constructor(date = new Date(), config = defaultConfig) {
24613 /**
24614 * Packet version
24615 * @type {Integer}
24616 */
24617 this.version = config.v5Keys ? 5 : 4;
24618 /**
24619 * Key creation date.
24620 * @type {Date}
24621 */
24622 this.created = util.normalizeDate(date);
24623 /**
24624 * Public key algorithm.
24625 * @type {String}
24626 */
24627 this.algorithm = null;
24628 /**
24629 * Algorithm specific public params
24630 * @type {Object}
24631 */
24632 this.publicParams = null;
24633 /**
24634 * Time until expiration in days (V3 only)
24635 * @type {Integer}
24636 */
24637 this.expirationTimeV3 = 0;
24638 /**
24639 * Fingerprint bytes
24640 * @type {Uint8Array}
24641 */
24642 this.fingerprint = null;
24643 /**
24644 * KeyID
24645 * @type {module:type/keyid~KeyID}
24646 */
24647 this.keyID = null;
24648 }
24649
24650 /**
24651 * Create a PublicKeyPacket from a SecretKeyPacket
24652 * @param {SecretKeyPacket} secretKeyPacket - key packet to convert
24653 * @returns {PublicKeyPacket} public key packet
24654 * @static
24655 */
24656 static fromSecretKeyPacket(secretKeyPacket) {
24657 const keyPacket = new PublicKeyPacket();
24658 const { version, created, algorithm, publicParams, keyID, fingerprint } = secretKeyPacket;
24659 keyPacket.version = version;
24660 keyPacket.created = created;
24661 keyPacket.algorithm = algorithm;
24662 keyPacket.publicParams = publicParams;
24663 keyPacket.keyID = keyID;
24664 keyPacket.fingerprint = fingerprint;
24665 return keyPacket;
24666 }
24667
24668 /**
24669 * 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}
24670 * @param {Uint8Array} bytes - Input array to read the packet from
24671 * @returns {Object} This object with attributes set by the parser
24672 * @async
24673 */
24674 async read(bytes) {
24675 let pos = 0;
24676 // A one-octet version number (3, 4 or 5).
24677 this.version = bytes[pos++];
24678
24679 if (this.version === 4 || this.version === 5) {
24680 // - A four-octet number denoting the time that the key was created.
24681 this.created = util.readDate(bytes.subarray(pos, pos + 4));
24682 pos += 4;
24683
24684 // - A one-octet number denoting the public-key algorithm of this key.
24685 this.algorithm = enums.read(enums.publicKey, bytes[pos++]);
24686 const algo = enums.write(enums.publicKey, this.algorithm);
24687
24688 if (this.version === 5) {
24689 // - A four-octet scalar octet count for the following key material.
24690 pos += 4;
24691 }
24692
24693 // - A series of values comprising the key material.
24694 try {
24695 const { read, publicParams } = mod.parsePublicKeyParams(algo, bytes.subarray(pos));
24696 this.publicParams = publicParams;
24697 pos += read;
24698 } catch (err) {
24699 throw new Error('Error reading MPIs');
24700 }
24701
24702 // we set the fingerprint and keyID already to make it possible to put together the key packets directly in the Key constructor
24703 await this.computeFingerprintAndKeyID();
24704 return pos;
24705 }
24706 throw new UnsupportedError(`Version ${this.version} of the key packet is unsupported.`);
24707 }
24708
24709 /**
24710 * Creates an OpenPGP public key packet for the given key.
24711 * @returns {Uint8Array} Bytes encoding the public key OpenPGP packet.
24712 */
24713 write() {
24714 const arr = [];
24715 // Version
24716 arr.push(new Uint8Array([this.version]));
24717 arr.push(util.writeDate(this.created));
24718 // A one-octet number denoting the public-key algorithm of this key
24719 const algo = enums.write(enums.publicKey, this.algorithm);
24720 arr.push(new Uint8Array([algo]));
24721
24722 const params = mod.serializeParams(algo, this.publicParams);
24723 if (this.version === 5) {
24724 // A four-octet scalar octet count for the following key material
24725 arr.push(util.writeNumber(params.length, 4));
24726 }
24727 // Algorithm-specific params
24728 arr.push(params);
24729 return util.concatUint8Array(arr);
24730 }
24731
24732 /**
24733 * Write packet in order to be hashed; either for a signature or a fingerprint
24734 * @param {Integer} version - target version of signature or key
24735 */
24736 writeForHash(version) {
24737 const bytes = this.writePublicKey();
24738
24739 if (version === 5) {
24740 return util.concatUint8Array([new Uint8Array([0x9A]), util.writeNumber(bytes.length, 4), bytes]);
24741 }
24742 return util.concatUint8Array([new Uint8Array([0x99]), util.writeNumber(bytes.length, 2), bytes]);
24743 }
24744
24745 /**
24746 * Check whether secret-key data is available in decrypted form. Returns null for public keys.
24747 * @returns {Boolean|null}
24748 */
24749 isDecrypted() {
24750 return null;
24751 }
24752
24753 /**
24754 * Returns the creation time of the key
24755 * @returns {Date}
24756 */
24757 getCreationTime() {
24758 return this.created;
24759 }
24760
24761 /**
24762 * Return the key ID of the key
24763 * @returns {module:type/keyid~KeyID} The 8-byte key ID
24764 */
24765 getKeyID() {
24766 return this.keyID;
24767 }
24768
24769 /**
24770 * Computes and set the key ID and fingerprint of the key
24771 * @async
24772 */
24773 async computeFingerprintAndKeyID() {
24774 await this.computeFingerprint();
24775 this.keyID = new KeyID();
24776
24777 if (this.version === 5) {
24778 this.keyID.read(this.fingerprint.subarray(0, 8));
24779 } else if (this.version === 4) {
24780 this.keyID.read(this.fingerprint.subarray(12, 20));
24781 } else {
24782 throw new Error('Unsupported key version');
24783 }
24784 }
24785
24786 /**
24787 * Computes and set the fingerprint of the key
24788 */
24789 async computeFingerprint() {
24790 const toHash = this.writeForHash(this.version);
24791
24792 if (this.version === 5) {
24793 this.fingerprint = await mod.hash.sha256(toHash);
24794 } else if (this.version === 4) {
24795 this.fingerprint = await mod.hash.sha1(toHash);
24796 } else {
24797 throw new Error('Unsupported key version');
24798 }
24799 }
24800
24801 /**
24802 * Returns the fingerprint of the key, as an array of bytes
24803 * @returns {Uint8Array} A Uint8Array containing the fingerprint
24804 */
24805 getFingerprintBytes() {
24806 return this.fingerprint;
24807 }
24808
24809 /**
24810 * Calculates and returns the fingerprint of the key, as a string
24811 * @returns {String} A string containing the fingerprint in lowercase hex
24812 */
24813 getFingerprint() {
24814 return util.uint8ArrayToHex(this.getFingerprintBytes());
24815 }
24816
24817 /**
24818 * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint
24819 * @returns {Boolean} Whether the two keys have the same version and public key data.
24820 */
24821 hasSameFingerprintAs(other) {
24822 return this.version === other.version && util.equalsUint8Array(this.writePublicKey(), other.writePublicKey());
24823 }
24824
24825 /**
24826 * Returns algorithm information
24827 * @returns {Object} An object of the form {algorithm: String, bits:int, curve:String}.
24828 */
24829 getAlgorithmInfo() {
24830 const result = {};
24831 result.algorithm = this.algorithm;
24832 // RSA, DSA or ElGamal public modulo
24833 const modulo = this.publicParams.n || this.publicParams.p;
24834 if (modulo) {
24835 result.bits = util.uint8ArrayBitLength(modulo);
24836 } else {
24837 result.curve = this.publicParams.oid.getName();
24838 }
24839 return result;
24840 }
24841 }
24842
24843 /**
24844 * Alias of read()
24845 * @see PublicKeyPacket#read
24846 */
24847 PublicKeyPacket.prototype.readPublicKey = PublicKeyPacket.prototype.read;
24848
24849 /**
24850 * Alias of write()
24851 * @see PublicKeyPacket#write
24852 */
24853 PublicKeyPacket.prototype.writePublicKey = PublicKeyPacket.prototype.write;
24854
24855 // GPG4Browsers - An OpenPGP implementation in javascript
24856
24857 // A SE packet can contain the following packet types
24858 const allowedPackets$3 = /*#__PURE__*/ util.constructAllowedPackets([
24859 LiteralDataPacket,
24860 CompressedDataPacket,
24861 OnePassSignaturePacket,
24862 SignaturePacket
24863 ]);
24864
24865 /**
24866 * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)
24867 *
24868 * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:
24869 * The Symmetrically Encrypted Data packet contains data encrypted with a
24870 * symmetric-key algorithm. When it has been decrypted, it contains other
24871 * packets (usually a literal data packet or compressed data packet, but in
24872 * theory other Symmetrically Encrypted Data packets or sequences of packets
24873 * that form whole OpenPGP messages).
24874 */
24875 class SymmetricallyEncryptedDataPacket {
24876 static get tag() {
24877 return enums.packet.symmetricallyEncryptedData;
24878 }
24879
24880 constructor() {
24881 /**
24882 * Encrypted secret-key data
24883 */
24884 this.encrypted = null;
24885 /**
24886 * Decrypted packets contained within.
24887 * @type {PacketList}
24888 */
24889 this.packets = null;
24890 }
24891
24892 read(bytes) {
24893 this.encrypted = bytes;
24894 }
24895
24896 write() {
24897 return this.encrypted;
24898 }
24899
24900 /**
24901 * Decrypt the symmetrically-encrypted packet data
24902 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
24903 * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use
24904 * @param {Uint8Array} key - The key of cipher blocksize length to be used
24905 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24906
24907 * @throws {Error} if decryption was not successful
24908 * @async
24909 */
24910 async decrypt(sessionKeyAlgorithm, key, config = defaultConfig) {
24911 // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error
24912 if (!config.allowUnauthenticatedMessages) {
24913 throw new Error('Message is not authenticated.');
24914 }
24915
24916 const encrypted = await readToEnd(clone(this.encrypted));
24917 const decrypted = await mod.mode.cfb.decrypt(sessionKeyAlgorithm, key,
24918 encrypted.subarray(mod.cipher[sessionKeyAlgorithm].blockSize + 2),
24919 encrypted.subarray(2, mod.cipher[sessionKeyAlgorithm].blockSize + 2)
24920 );
24921
24922 this.packets = await PacketList.fromBinary(decrypted, allowedPackets$3, config);
24923 }
24924
24925 /**
24926 * Encrypt the symmetrically-encrypted packet data
24927 * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
24928 * @param {module:enums.symmetric} sessionKeyAlgorithm - Symmetric key algorithm to use
24929 * @param {Uint8Array} key - The key of cipher blocksize length to be used
24930 * @param {Object} [config] - Full configuration, defaults to openpgp.config
24931 * @throws {Error} if encryption was not successful
24932 * @async
24933 */
24934 async encrypt(algo, key, config = defaultConfig) {
24935 const data = this.packets.write();
24936
24937 const prefix = await mod.getPrefixRandom(algo);
24938 const FRE = await mod.mode.cfb.encrypt(algo, key, prefix, new Uint8Array(mod.cipher[algo].blockSize), config);
24939 const ciphertext = await mod.mode.cfb.encrypt(algo, key, data, FRE.subarray(2), config);
24940 this.encrypted = util.concat([FRE, ciphertext]);
24941 }
24942 }
24943
24944 // GPG4Browsers - An OpenPGP implementation in javascript
24945
24946 /**
24947 * Implementation of the strange "Marker packet" (Tag 10)
24948 *
24949 * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:
24950 * An experimental version of PGP used this packet as the Literal
24951 * packet, but no released version of PGP generated Literal packets with this
24952 * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as
24953 * the Marker packet.
24954 *
24955 * The body of this packet consists of:
24956 * The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8).
24957 *
24958 * Such a packet MUST be ignored when received. It may be placed at the
24959 * beginning of a message that uses features not available in PGP
24960 * version 2.6 in order to cause that version to report that newer
24961 * software is necessary to process the message.
24962 */
24963 class MarkerPacket {
24964 static get tag() {
24965 return enums.packet.marker;
24966 }
24967
24968 /**
24969 * Parsing function for a marker data packet (tag 10).
24970 * @param {Uint8Array} bytes - Payload of a tag 10 packet
24971 * @returns {Boolean} whether the packet payload contains "PGP"
24972 */
24973 read(bytes) {
24974 if (bytes[0] === 0x50 && // P
24975 bytes[1] === 0x47 && // G
24976 bytes[2] === 0x50) { // P
24977 return true;
24978 }
24979 return false;
24980 }
24981
24982 write() {
24983 return new Uint8Array([0x50, 0x47, 0x50]);
24984 }
24985 }
24986
24987 // GPG4Browsers - An OpenPGP implementation in javascript
24988
24989 /**
24990 * A Public-Subkey packet (tag 14) has exactly the same format as a
24991 * Public-Key packet, but denotes a subkey. One or more subkeys may be
24992 * associated with a top-level key. By convention, the top-level key
24993 * provides signature services, and the subkeys provide encryption
24994 * services.
24995 * @extends PublicKeyPacket
24996 */
24997 class PublicSubkeyPacket extends PublicKeyPacket {
24998 static get tag() {
24999 return enums.packet.publicSubkey;
25000 }
25001
25002 /**
25003 * @param {Date} [date] - Creation date
25004 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25005 */
25006 // eslint-disable-next-line no-useless-constructor
25007 constructor(date, config) {
25008 super(date, config);
25009 }
25010
25011 /**
25012 * Create a PublicSubkeyPacket from a SecretSubkeyPacket
25013 * @param {SecretSubkeyPacket} secretSubkeyPacket - subkey packet to convert
25014 * @returns {SecretSubkeyPacket} public key packet
25015 * @static
25016 */
25017 static fromSecretSubkeyPacket(secretSubkeyPacket) {
25018 const keyPacket = new PublicSubkeyPacket();
25019 const { version, created, algorithm, publicParams, keyID, fingerprint } = secretSubkeyPacket;
25020 keyPacket.version = version;
25021 keyPacket.created = created;
25022 keyPacket.algorithm = algorithm;
25023 keyPacket.publicParams = publicParams;
25024 keyPacket.keyID = keyID;
25025 keyPacket.fingerprint = fingerprint;
25026 return keyPacket;
25027 }
25028 }
25029
25030 // GPG4Browsers - An OpenPGP implementation in javascript
25031
25032 /**
25033 * Implementation of the User Attribute Packet (Tag 17)
25034 *
25035 * The User Attribute packet is a variation of the User ID packet. It
25036 * is capable of storing more types of data than the User ID packet,
25037 * which is limited to text. Like the User ID packet, a User Attribute
25038 * packet may be certified by the key owner ("self-signed") or any other
25039 * key owner who cares to certify it. Except as noted, a User Attribute
25040 * packet may be used anywhere that a User ID packet may be used.
25041 *
25042 * While User Attribute packets are not a required part of the OpenPGP
25043 * standard, implementations SHOULD provide at least enough
25044 * compatibility to properly handle a certification signature on the
25045 * User Attribute packet. A simple way to do this is by treating the
25046 * User Attribute packet as a User ID packet with opaque contents, but
25047 * an implementation may use any method desired.
25048 */
25049 class UserAttributePacket {
25050 static get tag() {
25051 return enums.packet.userAttribute;
25052 }
25053
25054 constructor() {
25055 this.attributes = [];
25056 }
25057
25058 /**
25059 * parsing function for a user attribute packet (tag 17).
25060 * @param {Uint8Array} input - Payload of a tag 17 packet
25061 */
25062 read(bytes) {
25063 let i = 0;
25064 while (i < bytes.length) {
25065 const len = readSimpleLength(bytes.subarray(i, bytes.length));
25066 i += len.offset;
25067
25068 this.attributes.push(util.uint8ArrayToString(bytes.subarray(i, i + len.len)));
25069 i += len.len;
25070 }
25071 }
25072
25073 /**
25074 * Creates a binary representation of the user attribute packet
25075 * @returns {Uint8Array} String representation.
25076 */
25077 write() {
25078 const arr = [];
25079 for (let i = 0; i < this.attributes.length; i++) {
25080 arr.push(writeSimpleLength(this.attributes[i].length));
25081 arr.push(util.stringToUint8Array(this.attributes[i]));
25082 }
25083 return util.concatUint8Array(arr);
25084 }
25085
25086 /**
25087 * Compare for equality
25088 * @param {UserAttributePacket} usrAttr
25089 * @returns {Boolean} True if equal.
25090 */
25091 equals(usrAttr) {
25092 if (!usrAttr || !(usrAttr instanceof UserAttributePacket)) {
25093 return false;
25094 }
25095 return this.attributes.every(function(attr, index) {
25096 return attr === usrAttr.attributes[index];
25097 });
25098 }
25099 }
25100
25101 // GPG4Browsers - An OpenPGP implementation in javascript
25102
25103 /**
25104 * A Secret-Key packet contains all the information that is found in a
25105 * Public-Key packet, including the public-key material, but also
25106 * includes the secret-key material after all the public-key fields.
25107 * @extends PublicKeyPacket
25108 */
25109 class SecretKeyPacket extends PublicKeyPacket {
25110 static get tag() {
25111 return enums.packet.secretKey;
25112 }
25113
25114 /**
25115 * @param {Date} [date] - Creation date
25116 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25117 */
25118 constructor(date = new Date(), config = defaultConfig) {
25119 super(date, config);
25120 /**
25121 * Secret-key data
25122 */
25123 this.keyMaterial = null;
25124 /**
25125 * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.
25126 */
25127 this.isEncrypted = null;
25128 /**
25129 * S2K usage
25130 * @type {Integer}
25131 */
25132 this.s2kUsage = 0;
25133 /**
25134 * S2K object
25135 * @type {type/s2k}
25136 */
25137 this.s2k = null;
25138 /**
25139 * Symmetric algorithm
25140 * @type {String}
25141 */
25142 this.symmetric = null;
25143 /**
25144 * AEAD algorithm
25145 * @type {String}
25146 */
25147 this.aead = null;
25148 /**
25149 * Decrypted private parameters, referenced by name
25150 * @type {Object}
25151 */
25152 this.privateParams = null;
25153 }
25154
25155 // 5.5.3. Secret-Key Packet Formats
25156
25157 /**
25158 * Internal parser for private keys as specified in
25159 * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}
25160 * @param {String} bytes - Input string to read the packet from
25161 * @async
25162 */
25163 async read(bytes) {
25164 // - A Public-Key or Public-Subkey packet, as described above.
25165 let i = await this.readPublicKey(bytes);
25166
25167 // - One octet indicating string-to-key usage conventions. Zero
25168 // indicates that the secret-key data is not encrypted. 255 or 254
25169 // indicates that a string-to-key specifier is being given. Any
25170 // other value is a symmetric-key encryption algorithm identifier.
25171 this.s2kUsage = bytes[i++];
25172
25173 // - Only for a version 5 packet, a one-octet scalar octet count of
25174 // the next 4 optional fields.
25175 if (this.version === 5) {
25176 i++;
25177 }
25178
25179 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25180 // one-octet symmetric encryption algorithm.
25181 if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {
25182 this.symmetric = bytes[i++];
25183 this.symmetric = enums.read(enums.symmetric, this.symmetric);
25184
25185 // - [Optional] If string-to-key usage octet was 253, a one-octet
25186 // AEAD algorithm.
25187 if (this.s2kUsage === 253) {
25188 this.aead = bytes[i++];
25189 this.aead = enums.read(enums.aead, this.aead);
25190 }
25191
25192 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25193 // string-to-key specifier. The length of the string-to-key
25194 // specifier is implied by its type, as described above.
25195 this.s2k = new S2K();
25196 i += this.s2k.read(bytes.subarray(i, bytes.length));
25197
25198 if (this.s2k.type === 'gnu-dummy') {
25199 return;
25200 }
25201 } else if (this.s2kUsage) {
25202 this.symmetric = this.s2kUsage;
25203 this.symmetric = enums.read(enums.symmetric, this.symmetric);
25204 }
25205
25206 // - [Optional] If secret data is encrypted (string-to-key usage octet
25207 // not zero), an Initial Vector (IV) of the same length as the
25208 // cipher's block size.
25209 if (this.s2kUsage) {
25210 this.iv = bytes.subarray(
25211 i,
25212 i + mod.cipher[this.symmetric].blockSize
25213 );
25214
25215 i += this.iv.length;
25216 }
25217
25218 // - Only for a version 5 packet, a four-octet scalar octet count for
25219 // the following key material.
25220 if (this.version === 5) {
25221 i += 4;
25222 }
25223
25224 // - Plain or encrypted multiprecision integers comprising the secret
25225 // key data. These algorithm-specific fields are as described
25226 // below.
25227 this.keyMaterial = bytes.subarray(i);
25228 this.isEncrypted = !!this.s2kUsage;
25229
25230 if (!this.isEncrypted) {
25231 const cleartext = this.keyMaterial.subarray(0, -2);
25232 if (!util.equalsUint8Array(util.writeChecksum(cleartext), this.keyMaterial.subarray(-2))) {
25233 throw new Error('Key checksum mismatch');
25234 }
25235 try {
25236 const algo = enums.write(enums.publicKey, this.algorithm);
25237 const { privateParams } = mod.parsePrivateKeyParams(algo, cleartext, this.publicParams);
25238 this.privateParams = privateParams;
25239 } catch (err) {
25240 throw new Error('Error reading MPIs');
25241 }
25242 }
25243 }
25244
25245 /**
25246 * Creates an OpenPGP key packet for the given key.
25247 * @returns {Uint8Array} A string of bytes containing the secret key OpenPGP packet.
25248 */
25249 write() {
25250 const arr = [this.writePublicKey()];
25251
25252 arr.push(new Uint8Array([this.s2kUsage]));
25253
25254 const optionalFieldsArr = [];
25255 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25256 // one- octet symmetric encryption algorithm.
25257 if (this.s2kUsage === 255 || this.s2kUsage === 254 || this.s2kUsage === 253) {
25258 optionalFieldsArr.push(enums.write(enums.symmetric, this.symmetric));
25259
25260 // - [Optional] If string-to-key usage octet was 253, a one-octet
25261 // AEAD algorithm.
25262 if (this.s2kUsage === 253) {
25263 optionalFieldsArr.push(enums.write(enums.aead, this.aead));
25264 }
25265
25266 // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
25267 // string-to-key specifier. The length of the string-to-key
25268 // specifier is implied by its type, as described above.
25269 optionalFieldsArr.push(...this.s2k.write());
25270 }
25271
25272 // - [Optional] If secret data is encrypted (string-to-key usage octet
25273 // not zero), an Initial Vector (IV) of the same length as the
25274 // cipher's block size.
25275 if (this.s2kUsage && this.s2k.type !== 'gnu-dummy') {
25276 optionalFieldsArr.push(...this.iv);
25277 }
25278
25279 if (this.version === 5) {
25280 arr.push(new Uint8Array([optionalFieldsArr.length]));
25281 }
25282 arr.push(new Uint8Array(optionalFieldsArr));
25283
25284 if (!this.isDummy()) {
25285 if (!this.s2kUsage) {
25286 const algo = enums.write(enums.publicKey, this.algorithm);
25287 this.keyMaterial = mod.serializeParams(algo, this.privateParams);
25288 }
25289
25290 if (this.version === 5) {
25291 arr.push(util.writeNumber(this.keyMaterial.length, 4));
25292 }
25293 arr.push(this.keyMaterial);
25294
25295 if (!this.s2kUsage) {
25296 arr.push(util.writeChecksum(this.keyMaterial));
25297 }
25298 }
25299
25300 return util.concatUint8Array(arr);
25301 }
25302
25303 /**
25304 * Check whether secret-key data is available in decrypted form.
25305 * Returns false for gnu-dummy keys and null for public keys.
25306 * @returns {Boolean|null}
25307 */
25308 isDecrypted() {
25309 return this.isEncrypted === false;
25310 }
25311
25312 /**
25313 * Check whether this is a gnu-dummy key
25314 * @returns {Boolean}
25315 */
25316 isDummy() {
25317 return !!(this.s2k && this.s2k.type === 'gnu-dummy');
25318 }
25319
25320 /**
25321 * Remove private key material, converting the key to a dummy one.
25322 * The resulting key cannot be used for signing/decrypting but can still verify signatures.
25323 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25324 */
25325 makeDummy(config = defaultConfig) {
25326 if (this.isDummy()) {
25327 return;
25328 }
25329 if (this.isDecrypted()) {
25330 this.clearPrivateParams();
25331 }
25332 this.isEncrypted = null;
25333 this.keyMaterial = null;
25334 this.s2k = new S2K(config);
25335 this.s2k.algorithm = 0;
25336 this.s2k.c = 0;
25337 this.s2k.type = 'gnu-dummy';
25338 this.s2kUsage = 254;
25339 this.symmetric = 'aes256';
25340 }
25341
25342 /**
25343 * Encrypt the payload. By default, we use aes256 and iterated, salted string
25344 * to key specifier. If the key is in a decrypted state (isEncrypted === false)
25345 * and the passphrase is empty or undefined, the key will be set as not encrypted.
25346 * This can be used to remove passphrase protection after calling decrypt().
25347 * @param {String} passphrase
25348 * @param {Object} [config] - Full configuration, defaults to openpgp.config
25349 * @throws {Error} if encryption was not successful
25350 * @async
25351 */
25352 async encrypt(passphrase, config = defaultConfig) {
25353 if (this.isDummy()) {
25354 return;
25355 }
25356
25357 if (!this.isDecrypted()) {
25358 throw new Error('Key packet is already encrypted');
25359 }
25360
25361 if (this.isDecrypted() && !passphrase) {
25362 this.s2kUsage = 0;
25363 return;
25364 } else if (!passphrase) {
25365 throw new Error('The key must be decrypted before removing passphrase protection.');
25366 }
25367
25368 this.s2k = new S2K(config);
25369 this.s2k.salt = await mod.random.getRandomBytes(8);
25370 const algo = enums.write(enums.publicKey, this.algorithm);
25371 const cleartext = mod.serializeParams(algo, this.privateParams);
25372 this.symmetric = 'aes256';
25373 const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);
25374 const blockLen = mod.cipher[this.symmetric].blockSize;
25375 this.iv = await mod.random.getRandomBytes(blockLen);
25376
25377 if (config.aeadProtect) {
25378 this.s2kUsage = 253;
25379 this.aead = 'eax';
25380 const mode = mod.mode[this.aead];
25381 const modeInstance = await mode(this.symmetric, key);
25382 this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array());
25383 } else {
25384 this.s2kUsage = 254;
25385 this.keyMaterial = await mod.mode.cfb.encrypt(this.symmetric, key, util.concatUint8Array([
25386 cleartext,
25387 await mod.hash.sha1(cleartext, config)
25388 ]), this.iv, config);
25389 }
25390 }
25391
25392 /**
25393 * Decrypts the private key params which are needed to use the key.
25394 * Successful decryption does not imply key integrity, call validate() to confirm that.
25395 * {@link SecretKeyPacket.isDecrypted} should be false, as
25396 * otherwise calls to this function will throw an error.
25397 * @param {String} passphrase - The passphrase for this private key as string
25398 * @throws {Error} if the key is already decrypted, or if decryption was not successful
25399 * @async
25400 */
25401 async decrypt(passphrase) {
25402 if (this.isDummy()) {
25403 return false;
25404 }
25405
25406 if (this.isDecrypted()) {
25407 throw new Error('Key packet is already decrypted.');
25408 }
25409
25410 let key;
25411 if (this.s2kUsage === 254 || this.s2kUsage === 253) {
25412 key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);
25413 } else if (this.s2kUsage === 255) {
25414 throw new Error('Encrypted private key is authenticated using an insecure two-byte hash');
25415 } else {
25416 throw new Error('Private key is encrypted using an insecure S2K function: unsalted MD5');
25417 }
25418
25419 let cleartext;
25420 if (this.s2kUsage === 253) {
25421 const mode = mod.mode[this.aead];
25422 try {
25423 const modeInstance = await mode(this.symmetric, key);
25424 cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array());
25425 } catch (err) {
25426 if (err.message === 'Authentication tag mismatch') {
25427 throw new Error('Incorrect key passphrase: ' + err.message);
25428 }
25429 throw err;
25430 }
25431 } else {
25432 const cleartextWithHash = await mod.mode.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);
25433
25434 cleartext = cleartextWithHash.subarray(0, -20);
25435 const hash = await mod.hash.sha1(cleartext);
25436
25437 if (!util.equalsUint8Array(hash, cleartextWithHash.subarray(-20))) {
25438 throw new Error('Incorrect key passphrase');
25439 }
25440 }
25441
25442 try {
25443 const algo = enums.write(enums.publicKey, this.algorithm);
25444 const { privateParams } = mod.parsePrivateKeyParams(algo, cleartext, this.publicParams);
25445 this.privateParams = privateParams;
25446 } catch (err) {
25447 throw new Error('Error reading MPIs');
25448 }
25449 this.isEncrypted = false;
25450 this.keyMaterial = null;
25451 this.s2kUsage = 0;
25452 }
25453
25454 /**
25455 * Checks that the key parameters are consistent
25456 * @throws {Error} if validation was not successful
25457 * @async
25458 */
25459 async validate() {
25460 if (this.isDummy()) {
25461 return;
25462 }
25463
25464 if (!this.isDecrypted()) {
25465 throw new Error('Key is not decrypted');
25466 }
25467
25468 const algo = enums.write(enums.publicKey, this.algorithm);
25469
25470 let validParams;
25471 try {
25472 // this can throw if some parameters are undefined
25473 validParams = await mod.validateParams(algo, this.publicParams, this.privateParams);
25474 } catch (_) {
25475 validParams = false;
25476 }
25477 if (!validParams) {
25478 throw new Error('Key is invalid');
25479 }
25480 }
25481
25482 async generate(bits, curve) {
25483 const algo = enums.write(enums.publicKey, this.algorithm);
25484 const { privateParams, publicParams } = await mod.generateParams(algo, bits, curve);
25485 this.privateParams = privateParams;
25486 this.publicParams = publicParams;
25487 this.isEncrypted = false;
25488 }
25489
25490 /**
25491 * Clear private key parameters
25492 */
25493 clearPrivateParams() {
25494 if (this.isDummy()) {
25495 return;
25496 }
25497
25498 Object.keys(this.privateParams).forEach(name => {
25499 const param = this.privateParams[name];
25500 param.fill(0);
25501 delete this.privateParams[name];
25502 });
25503 this.privateParams = null;
25504 this.isEncrypted = true;
25505 }
25506 }
25507
25508 async function produceEncryptionKey(s2k, passphrase, algorithm) {
25509 return s2k.produceKey(
25510 passphrase,
25511 mod.cipher[algorithm].keySize
25512 );
25513 }
25514
25515 var emailAddresses = createCommonjsModule(function (module) {
25516 // email-addresses.js - RFC 5322 email address parser
25517 // v 3.1.0
25518 //
25519 // http://tools.ietf.org/html/rfc5322
25520 //
25521 // This library does not validate email addresses.
25522 // emailAddresses attempts to parse addresses using the (fairly liberal)
25523 // grammar specified in RFC 5322.
25524 //
25525 // email-addresses returns {
25526 // ast: <an abstract syntax tree based on rfc5322>,
25527 // addresses: [{
25528 // node: <node in ast for this address>,
25529 // name: <display-name>,
25530 // address: <addr-spec>,
25531 // local: <local-part>,
25532 // domain: <domain>
25533 // }, ...]
25534 // }
25535 //
25536 // emailAddresses.parseOneAddress and emailAddresses.parseAddressList
25537 // work as you might expect. Try it out.
25538 //
25539 // Many thanks to Dominic Sayers and his documentation on the is_email function,
25540 // http://code.google.com/p/isemail/ , which helped greatly in writing this parser.
25541
25542 (function (global) {
25543
25544 function parse5322(opts) {
25545
25546 // tokenizing functions
25547
25548 function inStr() { return pos < len; }
25549 function curTok() { return parseString[pos]; }
25550 function getPos() { return pos; }
25551 function setPos(i) { pos = i; }
25552 function nextTok() { pos += 1; }
25553 function initialize() {
25554 pos = 0;
25555 len = parseString.length;
25556 }
25557
25558 // parser helper functions
25559
25560 function o(name, value) {
25561 return {
25562 name: name,
25563 tokens: value || "",
25564 semantic: value || "",
25565 children: []
25566 };
25567 }
25568
25569 function wrap(name, ast) {
25570 var n;
25571 if (ast === null) { return null; }
25572 n = o(name);
25573 n.tokens = ast.tokens;
25574 n.semantic = ast.semantic;
25575 n.children.push(ast);
25576 return n;
25577 }
25578
25579 function add(parent, child) {
25580 if (child !== null) {
25581 parent.tokens += child.tokens;
25582 parent.semantic += child.semantic;
25583 }
25584 parent.children.push(child);
25585 return parent;
25586 }
25587
25588 function compareToken(fxnCompare) {
25589 var tok;
25590 if (!inStr()) { return null; }
25591 tok = curTok();
25592 if (fxnCompare(tok)) {
25593 nextTok();
25594 return o('token', tok);
25595 }
25596 return null;
25597 }
25598
25599 function literal(lit) {
25600 return function literalFunc() {
25601 return wrap('literal', compareToken(function (tok) {
25602 return tok === lit;
25603 }));
25604 };
25605 }
25606
25607 function and() {
25608 var args = arguments;
25609 return function andFunc() {
25610 var i, s, result, start;
25611 start = getPos();
25612 s = o('and');
25613 for (i = 0; i < args.length; i += 1) {
25614 result = args[i]();
25615 if (result === null) {
25616 setPos(start);
25617 return null;
25618 }
25619 add(s, result);
25620 }
25621 return s;
25622 };
25623 }
25624
25625 function or() {
25626 var args = arguments;
25627 return function orFunc() {
25628 var i, result, start;
25629 start = getPos();
25630 for (i = 0; i < args.length; i += 1) {
25631 result = args[i]();
25632 if (result !== null) {
25633 return result;
25634 }
25635 setPos(start);
25636 }
25637 return null;
25638 };
25639 }
25640
25641 function opt(prod) {
25642 return function optFunc() {
25643 var result, start;
25644 start = getPos();
25645 result = prod();
25646 if (result !== null) {
25647 return result;
25648 }
25649 else {
25650 setPos(start);
25651 return o('opt');
25652 }
25653 };
25654 }
25655
25656 function invis(prod) {
25657 return function invisFunc() {
25658 var result = prod();
25659 if (result !== null) {
25660 result.semantic = "";
25661 }
25662 return result;
25663 };
25664 }
25665
25666 function colwsp(prod) {
25667 return function collapseSemanticWhitespace() {
25668 var result = prod();
25669 if (result !== null && result.semantic.length > 0) {
25670 result.semantic = " ";
25671 }
25672 return result;
25673 };
25674 }
25675
25676 function star(prod, minimum) {
25677 return function starFunc() {
25678 var s, result, count, start, min;
25679 start = getPos();
25680 s = o('star');
25681 count = 0;
25682 min = minimum === undefined ? 0 : minimum;
25683 while ((result = prod()) !== null) {
25684 count = count + 1;
25685 add(s, result);
25686 }
25687 if (count >= min) {
25688 return s;
25689 }
25690 else {
25691 setPos(start);
25692 return null;
25693 }
25694 };
25695 }
25696
25697 // One expects names to get normalized like this:
25698 // " First Last " -> "First Last"
25699 // "First Last" -> "First Last"
25700 // "First Last" -> "First Last"
25701 function collapseWhitespace(s) {
25702 return s.replace(/([ \t]|\r\n)+/g, ' ').replace(/^\s*/, '').replace(/\s*$/, '');
25703 }
25704
25705 // UTF-8 pseudo-production (RFC 6532)
25706 // RFC 6532 extends RFC 5322 productions to include UTF-8
25707 // using the following productions:
25708 // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4
25709 // UTF8-2 = <Defined in Section 4 of RFC3629>
25710 // UTF8-3 = <Defined in Section 4 of RFC3629>
25711 // UTF8-4 = <Defined in Section 4 of RFC3629>
25712 //
25713 // For reference, the extended RFC 5322 productions are:
25714 // VCHAR =/ UTF8-non-ascii
25715 // ctext =/ UTF8-non-ascii
25716 // atext =/ UTF8-non-ascii
25717 // qtext =/ UTF8-non-ascii
25718 // dtext =/ UTF8-non-ascii
25719 function isUTF8NonAscii(tok) {
25720 // In JavaScript, we just deal directly with Unicode code points,
25721 // so we aren't checking individual bytes for UTF-8 encoding.
25722 // Just check that the character is non-ascii.
25723 return tok.charCodeAt(0) >= 128;
25724 }
25725
25726
25727 // common productions (RFC 5234)
25728 // http://tools.ietf.org/html/rfc5234
25729 // B.1. Core Rules
25730
25731 // CR = %x0D
25732 // ; carriage return
25733 function cr() { return wrap('cr', literal('\r')()); }
25734
25735 // CRLF = CR LF
25736 // ; Internet standard newline
25737 function crlf() { return wrap('crlf', and(cr, lf)()); }
25738
25739 // DQUOTE = %x22
25740 // ; " (Double Quote)
25741 function dquote() { return wrap('dquote', literal('"')()); }
25742
25743 // HTAB = %x09
25744 // ; horizontal tab
25745 function htab() { return wrap('htab', literal('\t')()); }
25746
25747 // LF = %x0A
25748 // ; linefeed
25749 function lf() { return wrap('lf', literal('\n')()); }
25750
25751 // SP = %x20
25752 function sp() { return wrap('sp', literal(' ')()); }
25753
25754 // VCHAR = %x21-7E
25755 // ; visible (printing) characters
25756 function vchar() {
25757 return wrap('vchar', compareToken(function vcharFunc(tok) {
25758 var code = tok.charCodeAt(0);
25759 var accept = (0x21 <= code && code <= 0x7E);
25760 if (opts.rfc6532) {
25761 accept = accept || isUTF8NonAscii(tok);
25762 }
25763 return accept;
25764 }));
25765 }
25766
25767 // WSP = SP / HTAB
25768 // ; white space
25769 function wsp() { return wrap('wsp', or(sp, htab)()); }
25770
25771
25772 // email productions (RFC 5322)
25773 // http://tools.ietf.org/html/rfc5322
25774 // 3.2.1. Quoted characters
25775
25776 // quoted-pair = ("\" (VCHAR / WSP)) / obs-qp
25777 function quotedPair() {
25778 var qp = wrap('quoted-pair',
25779 or(
25780 and(literal('\\'), or(vchar, wsp)),
25781 obsQP
25782 )());
25783 if (qp === null) { return null; }
25784 // a quoted pair will be two characters, and the "\" character
25785 // should be semantically "invisible" (RFC 5322 3.2.1)
25786 qp.semantic = qp.semantic[1];
25787 return qp;
25788 }
25789
25790 // 3.2.2. Folding White Space and Comments
25791
25792 // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS
25793 function fws() {
25794 return wrap('fws', or(
25795 obsFws,
25796 and(
25797 opt(and(
25798 star(wsp),
25799 invis(crlf)
25800 )),
25801 star(wsp, 1)
25802 )
25803 )());
25804 }
25805
25806 // ctext = %d33-39 / ; Printable US-ASCII
25807 // %d42-91 / ; characters not including
25808 // %d93-126 / ; "(", ")", or "\"
25809 // obs-ctext
25810 function ctext() {
25811 return wrap('ctext', or(
25812 function ctextFunc1() {
25813 return compareToken(function ctextFunc2(tok) {
25814 var code = tok.charCodeAt(0);
25815 var accept =
25816 (33 <= code && code <= 39) ||
25817 (42 <= code && code <= 91) ||
25818 (93 <= code && code <= 126);
25819 if (opts.rfc6532) {
25820 accept = accept || isUTF8NonAscii(tok);
25821 }
25822 return accept;
25823 });
25824 },
25825 obsCtext
25826 )());
25827 }
25828
25829 // ccontent = ctext / quoted-pair / comment
25830 function ccontent() {
25831 return wrap('ccontent', or(ctext, quotedPair, comment)());
25832 }
25833
25834 // comment = "(" *([FWS] ccontent) [FWS] ")"
25835 function comment() {
25836 return wrap('comment', and(
25837 literal('('),
25838 star(and(opt(fws), ccontent)),
25839 opt(fws),
25840 literal(')')
25841 )());
25842 }
25843
25844 // CFWS = (1*([FWS] comment) [FWS]) / FWS
25845 function cfws() {
25846 return wrap('cfws', or(
25847 and(
25848 star(
25849 and(opt(fws), comment),
25850 1
25851 ),
25852 opt(fws)
25853 ),
25854 fws
25855 )());
25856 }
25857
25858 // 3.2.3. Atom
25859
25860 //atext = ALPHA / DIGIT / ; Printable US-ASCII
25861 // "!" / "#" / ; characters not including
25862 // "$" / "%" / ; specials. Used for atoms.
25863 // "&" / "'" /
25864 // "*" / "+" /
25865 // "-" / "/" /
25866 // "=" / "?" /
25867 // "^" / "_" /
25868 // "`" / "{" /
25869 // "|" / "}" /
25870 // "~"
25871 function atext() {
25872 return wrap('atext', compareToken(function atextFunc(tok) {
25873 var accept =
25874 ('a' <= tok && tok <= 'z') ||
25875 ('A' <= tok && tok <= 'Z') ||
25876 ('0' <= tok && tok <= '9') ||
25877 (['!', '#', '$', '%', '&', '\'', '*', '+', '-', '/',
25878 '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0);
25879 if (opts.rfc6532) {
25880 accept = accept || isUTF8NonAscii(tok);
25881 }
25882 return accept;
25883 }));
25884 }
25885
25886 // atom = [CFWS] 1*atext [CFWS]
25887 function atom() {
25888 return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))());
25889 }
25890
25891 // dot-atom-text = 1*atext *("." 1*atext)
25892 function dotAtomText() {
25893 var s, maybeText;
25894 s = wrap('dot-atom-text', star(atext, 1)());
25895 if (s === null) { return s; }
25896 maybeText = star(and(literal('.'), star(atext, 1)))();
25897 if (maybeText !== null) {
25898 add(s, maybeText);
25899 }
25900 return s;
25901 }
25902
25903 // dot-atom = [CFWS] dot-atom-text [CFWS]
25904 function dotAtom() {
25905 return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))());
25906 }
25907
25908 // 3.2.4. Quoted Strings
25909
25910 // qtext = %d33 / ; Printable US-ASCII
25911 // %d35-91 / ; characters not including
25912 // %d93-126 / ; "\" or the quote character
25913 // obs-qtext
25914 function qtext() {
25915 return wrap('qtext', or(
25916 function qtextFunc1() {
25917 return compareToken(function qtextFunc2(tok) {
25918 var code = tok.charCodeAt(0);
25919 var accept =
25920 (33 === code) ||
25921 (35 <= code && code <= 91) ||
25922 (93 <= code && code <= 126);
25923 if (opts.rfc6532) {
25924 accept = accept || isUTF8NonAscii(tok);
25925 }
25926 return accept;
25927 });
25928 },
25929 obsQtext
25930 )());
25931 }
25932
25933 // qcontent = qtext / quoted-pair
25934 function qcontent() {
25935 return wrap('qcontent', or(qtext, quotedPair)());
25936 }
25937
25938 // quoted-string = [CFWS]
25939 // DQUOTE *([FWS] qcontent) [FWS] DQUOTE
25940 // [CFWS]
25941 function quotedString() {
25942 return wrap('quoted-string', and(
25943 invis(opt(cfws)),
25944 invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote),
25945 invis(opt(cfws))
25946 )());
25947 }
25948
25949 // 3.2.5 Miscellaneous Tokens
25950
25951 // word = atom / quoted-string
25952 function word() {
25953 return wrap('word', or(atom, quotedString)());
25954 }
25955
25956 // phrase = 1*word / obs-phrase
25957 function phrase() {
25958 return wrap('phrase', or(obsPhrase, star(word, 1))());
25959 }
25960
25961 // 3.4. Address Specification
25962 // address = mailbox / group
25963 function address() {
25964 return wrap('address', or(mailbox, group)());
25965 }
25966
25967 // mailbox = name-addr / addr-spec
25968 function mailbox() {
25969 return wrap('mailbox', or(nameAddr, addrSpec)());
25970 }
25971
25972 // name-addr = [display-name] angle-addr
25973 function nameAddr() {
25974 return wrap('name-addr', and(opt(displayName), angleAddr)());
25975 }
25976
25977 // angle-addr = [CFWS] "<" addr-spec ">" [CFWS] /
25978 // obs-angle-addr
25979 function angleAddr() {
25980 return wrap('angle-addr', or(
25981 and(
25982 invis(opt(cfws)),
25983 literal('<'),
25984 addrSpec,
25985 literal('>'),
25986 invis(opt(cfws))
25987 ),
25988 obsAngleAddr
25989 )());
25990 }
25991
25992 // group = display-name ":" [group-list] ";" [CFWS]
25993 function group() {
25994 return wrap('group', and(
25995 displayName,
25996 literal(':'),
25997 opt(groupList),
25998 literal(';'),
25999 invis(opt(cfws))
26000 )());
26001 }
26002
26003 // display-name = phrase
26004 function displayName() {
26005 return wrap('display-name', function phraseFixedSemantic() {
26006 var result = phrase();
26007 if (result !== null) {
26008 result.semantic = collapseWhitespace(result.semantic);
26009 }
26010 return result;
26011 }());
26012 }
26013
26014 // mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list
26015 function mailboxList() {
26016 return wrap('mailbox-list', or(
26017 and(
26018 mailbox,
26019 star(and(literal(','), mailbox))
26020 ),
26021 obsMboxList
26022 )());
26023 }
26024
26025 // address-list = (address *("," address)) / obs-addr-list
26026 function addressList() {
26027 return wrap('address-list', or(
26028 and(
26029 address,
26030 star(and(literal(','), address))
26031 ),
26032 obsAddrList
26033 )());
26034 }
26035
26036 // group-list = mailbox-list / CFWS / obs-group-list
26037 function groupList() {
26038 return wrap('group-list', or(
26039 mailboxList,
26040 invis(cfws),
26041 obsGroupList
26042 )());
26043 }
26044
26045 // 3.4.1 Addr-Spec Specification
26046
26047 // local-part = dot-atom / quoted-string / obs-local-part
26048 function localPart() {
26049 // note: quoted-string, dotAtom are proper subsets of obs-local-part
26050 // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree
26051 return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)());
26052 }
26053
26054 // dtext = %d33-90 / ; Printable US-ASCII
26055 // %d94-126 / ; characters not including
26056 // obs-dtext ; "[", "]", or "\"
26057 function dtext() {
26058 return wrap('dtext', or(
26059 function dtextFunc1() {
26060 return compareToken(function dtextFunc2(tok) {
26061 var code = tok.charCodeAt(0);
26062 var accept =
26063 (33 <= code && code <= 90) ||
26064 (94 <= code && code <= 126);
26065 if (opts.rfc6532) {
26066 accept = accept || isUTF8NonAscii(tok);
26067 }
26068 return accept;
26069 });
26070 },
26071 obsDtext
26072 )()
26073 );
26074 }
26075
26076 // domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
26077 function domainLiteral() {
26078 return wrap('domain-literal', and(
26079 invis(opt(cfws)),
26080 literal('['),
26081 star(and(opt(fws), dtext)),
26082 opt(fws),
26083 literal(']'),
26084 invis(opt(cfws))
26085 )());
26086 }
26087
26088 // domain = dot-atom / domain-literal / obs-domain
26089 function domain() {
26090 return wrap('domain', function domainCheckTLD() {
26091 var result = or(obsDomain, dotAtom, domainLiteral)();
26092 if (opts.rejectTLD) {
26093 if (result && result.semantic && result.semantic.indexOf('.') < 0) {
26094 return null;
26095 }
26096 }
26097 // strip all whitespace from domains
26098 if (result) {
26099 result.semantic = result.semantic.replace(/\s+/g, '');
26100 }
26101 return result;
26102 }());
26103 }
26104
26105 // addr-spec = local-part "@" domain
26106 function addrSpec() {
26107 return wrap('addr-spec', and(
26108 localPart, literal('@'), domain
26109 )());
26110 }
26111
26112 // 3.6.2 Originator Fields
26113 // Below we only parse the field body, not the name of the field
26114 // like "From:", "Sender:", or "Reply-To:". Other libraries that
26115 // parse email headers can parse those and defer to these productions
26116 // for the "RFC 5322" part.
26117
26118 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
26119 // from = "From:" (mailbox-list / address-list) CRLF
26120 function fromSpec() {
26121 return wrap('from', or(
26122 mailboxList,
26123 addressList
26124 )());
26125 }
26126
26127 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
26128 // sender = "Sender:" (mailbox / address) CRLF
26129 function senderSpec() {
26130 return wrap('sender', or(
26131 mailbox,
26132 address
26133 )());
26134 }
26135
26136 // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
26137 // reply-to = "Reply-To:" address-list CRLF
26138 function replyToSpec() {
26139 return wrap('reply-to', addressList());
26140 }
26141
26142 // 4.1. Miscellaneous Obsolete Tokens
26143
26144 // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
26145 // %d11 / ; characters that do not
26146 // %d12 / ; include the carriage
26147 // %d14-31 / ; return, line feed, and
26148 // %d127 ; white space characters
26149 function obsNoWsCtl() {
26150 return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) {
26151 var code = tok.charCodeAt(0);
26152 return ((1 <= code && code <= 8) ||
26153 (11 === code || 12 === code) ||
26154 (14 <= code && code <= 31) ||
26155 (127 === code));
26156 }));
26157 }
26158
26159 // obs-ctext = obs-NO-WS-CTL
26160 function obsCtext() { return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl()); }
26161
26162 // obs-qtext = obs-NO-WS-CTL
26163 function obsQtext() { return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl()); }
26164
26165 // obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR)
26166 function obsQP() {
26167 return opts.strict ? null : wrap('obs-qp', and(
26168 literal('\\'),
26169 or(literal('\0'), obsNoWsCtl, lf, cr)
26170 )());
26171 }
26172
26173 // obs-phrase = word *(word / "." / CFWS)
26174 function obsPhrase() {
26175 if (opts.strict ) return null;
26176 return opts.atInDisplayName ? wrap('obs-phrase', and(
26177 word,
26178 star(or(word, literal('.'), literal('@'), colwsp(cfws)))
26179 )()) :
26180 wrap('obs-phrase', and(
26181 word,
26182 star(or(word, literal('.'), colwsp(cfws)))
26183 )());
26184 }
26185
26186 // 4.2. Obsolete Folding White Space
26187
26188 // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908
26189 // obs-FWS = 1*([CRLF] WSP)
26190 function obsFws() {
26191 return opts.strict ? null : wrap('obs-FWS', star(
26192 and(invis(opt(crlf)), wsp),
26193 1
26194 )());
26195 }
26196
26197 // 4.4. Obsolete Addressing
26198
26199 // obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS]
26200 function obsAngleAddr() {
26201 return opts.strict ? null : wrap('obs-angle-addr', and(
26202 invis(opt(cfws)),
26203 literal('<'),
26204 obsRoute,
26205 addrSpec,
26206 literal('>'),
26207 invis(opt(cfws))
26208 )());
26209 }
26210
26211 // obs-route = obs-domain-list ":"
26212 function obsRoute() {
26213 return opts.strict ? null : wrap('obs-route', and(
26214 obsDomainList,
26215 literal(':')
26216 )());
26217 }
26218
26219 // obs-domain-list = *(CFWS / ",") "@" domain
26220 // *("," [CFWS] ["@" domain])
26221 function obsDomainList() {
26222 return opts.strict ? null : wrap('obs-domain-list', and(
26223 star(or(invis(cfws), literal(','))),
26224 literal('@'),
26225 domain,
26226 star(and(
26227 literal(','),
26228 invis(opt(cfws)),
26229 opt(and(literal('@'), domain))
26230 ))
26231 )());
26232 }
26233
26234 // obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS])
26235 function obsMboxList() {
26236 return opts.strict ? null : wrap('obs-mbox-list', and(
26237 star(and(
26238 invis(opt(cfws)),
26239 literal(',')
26240 )),
26241 mailbox,
26242 star(and(
26243 literal(','),
26244 opt(and(
26245 mailbox,
26246 invis(cfws)
26247 ))
26248 ))
26249 )());
26250 }
26251
26252 // obs-addr-list = *([CFWS] ",") address *("," [address / CFWS])
26253 function obsAddrList() {
26254 return opts.strict ? null : wrap('obs-addr-list', and(
26255 star(and(
26256 invis(opt(cfws)),
26257 literal(',')
26258 )),
26259 address,
26260 star(and(
26261 literal(','),
26262 opt(and(
26263 address,
26264 invis(cfws)
26265 ))
26266 ))
26267 )());
26268 }
26269
26270 // obs-group-list = 1*([CFWS] ",") [CFWS]
26271 function obsGroupList() {
26272 return opts.strict ? null : wrap('obs-group-list', and(
26273 star(and(
26274 invis(opt(cfws)),
26275 literal(',')
26276 ), 1),
26277 invis(opt(cfws))
26278 )());
26279 }
26280
26281 // obs-local-part = word *("." word)
26282 function obsLocalPart() {
26283 return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))());
26284 }
26285
26286 // obs-domain = atom *("." atom)
26287 function obsDomain() {
26288 return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))());
26289 }
26290
26291 // obs-dtext = obs-NO-WS-CTL / quoted-pair
26292 function obsDtext() {
26293 return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)());
26294 }
26295
26296 /////////////////////////////////////////////////////
26297
26298 // ast analysis
26299
26300 function findNode(name, root) {
26301 var i, stack, node;
26302 if (root === null || root === undefined) { return null; }
26303 stack = [root];
26304 while (stack.length > 0) {
26305 node = stack.pop();
26306 if (node.name === name) {
26307 return node;
26308 }
26309 for (i = node.children.length - 1; i >= 0; i -= 1) {
26310 stack.push(node.children[i]);
26311 }
26312 }
26313 return null;
26314 }
26315
26316 function findAllNodes(name, root) {
26317 var i, stack, node, result;
26318 if (root === null || root === undefined) { return null; }
26319 stack = [root];
26320 result = [];
26321 while (stack.length > 0) {
26322 node = stack.pop();
26323 if (node.name === name) {
26324 result.push(node);
26325 }
26326 for (i = node.children.length - 1; i >= 0; i -= 1) {
26327 stack.push(node.children[i]);
26328 }
26329 }
26330 return result;
26331 }
26332
26333 function findAllNodesNoChildren(names, root) {
26334 var i, stack, node, result, namesLookup;
26335 if (root === null || root === undefined) { return null; }
26336 stack = [root];
26337 result = [];
26338 namesLookup = {};
26339 for (i = 0; i < names.length; i += 1) {
26340 namesLookup[names[i]] = true;
26341 }
26342
26343 while (stack.length > 0) {
26344 node = stack.pop();
26345 if (node.name in namesLookup) {
26346 result.push(node);
26347 // don't look at children (hence findAllNodesNoChildren)
26348 } else {
26349 for (i = node.children.length - 1; i >= 0; i -= 1) {
26350 stack.push(node.children[i]);
26351 }
26352 }
26353 }
26354 return result;
26355 }
26356
26357 function giveResult(ast) {
26358 var addresses, groupsAndMailboxes, i, groupOrMailbox, result;
26359 if (ast === null) {
26360 return null;
26361 }
26362 addresses = [];
26363
26364 // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'.
26365 groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast);
26366 for (i = 0; i < groupsAndMailboxes.length; i += 1) {
26367 groupOrMailbox = groupsAndMailboxes[i];
26368 if (groupOrMailbox.name === 'group') {
26369 addresses.push(giveResultGroup(groupOrMailbox));
26370 } else if (groupOrMailbox.name === 'mailbox') {
26371 addresses.push(giveResultMailbox(groupOrMailbox));
26372 }
26373 }
26374
26375 result = {
26376 ast: ast,
26377 addresses: addresses,
26378 };
26379 if (opts.simple) {
26380 result = simplifyResult(result);
26381 }
26382 if (opts.oneResult) {
26383 return oneResult(result);
26384 }
26385 if (opts.simple) {
26386 return result && result.addresses;
26387 } else {
26388 return result;
26389 }
26390 }
26391
26392 function giveResultGroup(group) {
26393 var i;
26394 var groupName = findNode('display-name', group);
26395 var groupResultMailboxes = [];
26396 var mailboxes = findAllNodesNoChildren(['mailbox'], group);
26397 for (i = 0; i < mailboxes.length; i += 1) {
26398 groupResultMailboxes.push(giveResultMailbox(mailboxes[i]));
26399 }
26400 return {
26401 node: group,
26402 parts: {
26403 name: groupName,
26404 },
26405 type: group.name, // 'group'
26406 name: grabSemantic(groupName),
26407 addresses: groupResultMailboxes,
26408 };
26409 }
26410
26411 function giveResultMailbox(mailbox) {
26412 var name = findNode('display-name', mailbox);
26413 var aspec = findNode('addr-spec', mailbox);
26414 var cfws = findAllNodes('cfws', mailbox);
26415 var comments = findAllNodesNoChildren(['comment'], mailbox);
26416
26417
26418 var local = findNode('local-part', aspec);
26419 var domain = findNode('domain', aspec);
26420 return {
26421 node: mailbox,
26422 parts: {
26423 name: name,
26424 address: aspec,
26425 local: local,
26426 domain: domain,
26427 comments: cfws
26428 },
26429 type: mailbox.name, // 'mailbox'
26430 name: grabSemantic(name),
26431 address: grabSemantic(aspec),
26432 local: grabSemantic(local),
26433 domain: grabSemantic(domain),
26434 comments: concatComments(comments),
26435 groupName: grabSemantic(mailbox.groupName),
26436 };
26437 }
26438
26439 function grabSemantic(n) {
26440 return n !== null && n !== undefined ? n.semantic : null;
26441 }
26442
26443 function simplifyResult(result) {
26444 var i;
26445 if (result && result.addresses) {
26446 for (i = 0; i < result.addresses.length; i += 1) {
26447 delete result.addresses[i].node;
26448 }
26449 }
26450 return result;
26451 }
26452
26453 function concatComments(comments) {
26454 var result = '';
26455 if (comments) {
26456 for (var i = 0; i < comments.length; i += 1) {
26457 result += grabSemantic(comments[i]);
26458 }
26459 }
26460 return result;
26461 }
26462
26463 function oneResult(result) {
26464 if (!result) { return null; }
26465 if (!opts.partial && result.addresses.length > 1) { return null; }
26466 return result.addresses && result.addresses[0];
26467 }
26468
26469 /////////////////////////////////////////////////////
26470
26471 var parseString, pos, len, parsed, startProduction;
26472
26473 opts = handleOpts(opts, {});
26474 if (opts === null) { return null; }
26475
26476 parseString = opts.input;
26477
26478 startProduction = {
26479 'address': address,
26480 'address-list': addressList,
26481 'angle-addr': angleAddr,
26482 'from': fromSpec,
26483 'group': group,
26484 'mailbox': mailbox,
26485 'mailbox-list': mailboxList,
26486 'reply-to': replyToSpec,
26487 'sender': senderSpec,
26488 }[opts.startAt] || addressList;
26489
26490 if (!opts.strict) {
26491 initialize();
26492 opts.strict = true;
26493 parsed = startProduction(parseString);
26494 if (opts.partial || !inStr()) {
26495 return giveResult(parsed);
26496 }
26497 opts.strict = false;
26498 }
26499
26500 initialize();
26501 parsed = startProduction(parseString);
26502 if (!opts.partial && inStr()) { return null; }
26503 return giveResult(parsed);
26504 }
26505
26506 function parseOneAddressSimple(opts) {
26507 return parse5322(handleOpts(opts, {
26508 oneResult: true,
26509 rfc6532: true,
26510 simple: true,
26511 startAt: 'address-list',
26512 }));
26513 }
26514
26515 function parseAddressListSimple(opts) {
26516 return parse5322(handleOpts(opts, {
26517 rfc6532: true,
26518 simple: true,
26519 startAt: 'address-list',
26520 }));
26521 }
26522
26523 function parseFromSimple(opts) {
26524 return parse5322(handleOpts(opts, {
26525 rfc6532: true,
26526 simple: true,
26527 startAt: 'from',
26528 }));
26529 }
26530
26531 function parseSenderSimple(opts) {
26532 return parse5322(handleOpts(opts, {
26533 oneResult: true,
26534 rfc6532: true,
26535 simple: true,
26536 startAt: 'sender',
26537 }));
26538 }
26539
26540 function parseReplyToSimple(opts) {
26541 return parse5322(handleOpts(opts, {
26542 rfc6532: true,
26543 simple: true,
26544 startAt: 'reply-to',
26545 }));
26546 }
26547
26548 function handleOpts(opts, defs) {
26549 function isString(str) {
26550 return Object.prototype.toString.call(str) === '[object String]';
26551 }
26552
26553 function isObject(o) {
26554 return o === Object(o);
26555 }
26556
26557 function isNullUndef(o) {
26558 return o === null || o === undefined;
26559 }
26560
26561 var defaults, o;
26562
26563 if (isString(opts)) {
26564 opts = { input: opts };
26565 } else if (!isObject(opts)) {
26566 return null;
26567 }
26568
26569 if (!isString(opts.input)) { return null; }
26570 if (!defs) { return null; }
26571
26572 defaults = {
26573 oneResult: false,
26574 partial: false,
26575 rejectTLD: false,
26576 rfc6532: false,
26577 simple: false,
26578 startAt: 'address-list',
26579 strict: false,
26580 atInDisplayName: false
26581 };
26582
26583 for (o in defaults) {
26584 if (isNullUndef(opts[o])) {
26585 opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o];
26586 }
26587 }
26588 return opts;
26589 }
26590
26591 parse5322.parseOneAddress = parseOneAddressSimple;
26592 parse5322.parseAddressList = parseAddressListSimple;
26593 parse5322.parseFrom = parseFromSimple;
26594 parse5322.parseSender = parseSenderSimple;
26595 parse5322.parseReplyTo = parseReplyToSimple;
26596
26597 {
26598 module.exports = parse5322;
26599 }
26600
26601 }());
26602 });
26603
26604 // GPG4Browsers - An OpenPGP implementation in javascript
26605
26606 /**
26607 * Implementation of the User ID Packet (Tag 13)
26608 *
26609 * A User ID packet consists of UTF-8 text that is intended to represent
26610 * the name and email address of the key holder. By convention, it
26611 * includes an RFC 2822 [RFC2822] mail name-addr, but there are no
26612 * restrictions on its content. The packet length in the header
26613 * specifies the length of the User ID.
26614 */
26615 class UserIDPacket {
26616 static get tag() {
26617 return enums.packet.userID;
26618 }
26619
26620 constructor() {
26621 /** A string containing the user id. Usually in the form
26622 * John Doe <john@example.com>
26623 * @type {String}
26624 */
26625 this.userID = '';
26626
26627 this.name = '';
26628 this.email = '';
26629 this.comment = '';
26630 }
26631
26632 /**
26633 * Create UserIDPacket instance from object
26634 * @param {Object} userID - Object specifying userID name, email and comment
26635 * @returns {UserIDPacket}
26636 * @static
26637 */
26638 static fromObject(userID) {
26639 if (util.isString(userID) ||
26640 (userID.name && !util.isString(userID.name)) ||
26641 (userID.email && !util.isEmailAddress(userID.email)) ||
26642 (userID.comment && !util.isString(userID.comment))) {
26643 throw new Error('Invalid user ID format');
26644 }
26645 const packet = new UserIDPacket();
26646 Object.assign(packet, userID);
26647 const components = [];
26648 if (packet.name) components.push(packet.name);
26649 if (packet.comment) components.push(`(${packet.comment})`);
26650 if (packet.email) components.push(`<${packet.email}>`);
26651 packet.userID = components.join(' ');
26652 return packet;
26653 }
26654
26655 /**
26656 * Parsing function for a user id packet (tag 13).
26657 * @param {Uint8Array} input - Payload of a tag 13 packet
26658 */
26659 read(bytes, config = defaultConfig) {
26660 const userID = util.decodeUTF8(bytes);
26661 if (userID.length > config.maxUserIDLength) {
26662 throw new Error('User ID string is too long');
26663 }
26664 try {
26665 const { name, address: email, comments } = emailAddresses.parseOneAddress({ input: userID, atInDisplayName: true });
26666 this.comment = comments.replace(/^\(|\)$/g, '');
26667 this.name = name;
26668 this.email = email;
26669 } catch (e) {}
26670 this.userID = userID;
26671 }
26672
26673 /**
26674 * Creates a binary representation of the user id packet
26675 * @returns {Uint8Array} Binary representation.
26676 */
26677 write() {
26678 return util.encodeUTF8(this.userID);
26679 }
26680
26681 equals(otherUserID) {
26682 return otherUserID && otherUserID.userID === this.userID;
26683 }
26684 }
26685
26686 // GPG4Browsers - An OpenPGP implementation in javascript
26687
26688 /**
26689 * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret
26690 * Key packet and has exactly the same format.
26691 * @extends SecretKeyPacket
26692 */
26693 class SecretSubkeyPacket extends SecretKeyPacket {
26694 static get tag() {
26695 return enums.packet.secretSubkey;
26696 }
26697
26698 /**
26699 * @param {Date} [date] - Creation date
26700 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26701 */
26702 constructor(date = new Date(), config = defaultConfig) {
26703 super(date, config);
26704 }
26705 }
26706
26707 /**
26708 * Implementation of the Trust Packet (Tag 12)
26709 *
26710 * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:
26711 * The Trust packet is used only within keyrings and is not normally
26712 * exported. Trust packets contain data that record the user's
26713 * specifications of which key holders are trustworthy introducers,
26714 * along with other information that implementing software uses for
26715 * trust information. The format of Trust packets is defined by a given
26716 * implementation.
26717 *
26718 * Trust packets SHOULD NOT be emitted to output streams that are
26719 * transferred to other users, and they SHOULD be ignored on any input
26720 * other than local keyring files.
26721 */
26722 class TrustPacket {
26723 static get tag() {
26724 return enums.packet.trust;
26725 }
26726
26727 /**
26728 * Parsing function for a trust packet (tag 12).
26729 * Currently not implemented as we ignore trust packets
26730 */
26731 read() {
26732 throw new UnsupportedError('Trust packets are not supported');
26733 }
26734
26735 write() {
26736 throw new UnsupportedError('Trust packets are not supported');
26737 }
26738 }
26739
26740 // GPG4Browsers - An OpenPGP implementation in javascript
26741
26742 // A Signature can contain the following packets
26743 const allowedPackets$4 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
26744
26745 /**
26746 * Class that represents an OpenPGP signature.
26747 */
26748 class Signature {
26749 /**
26750 * @param {PacketList} packetlist - The signature packets
26751 */
26752 constructor(packetlist) {
26753 this.packets = packetlist || new PacketList();
26754 }
26755
26756 /**
26757 * Returns binary encoded signature
26758 * @returns {ReadableStream<Uint8Array>} Binary signature.
26759 */
26760 write() {
26761 return this.packets.write();
26762 }
26763
26764 /**
26765 * Returns ASCII armored text of signature
26766 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26767 * @returns {ReadableStream<String>} ASCII armor.
26768 */
26769 armor(config = defaultConfig) {
26770 return armor(enums.armor.signature, this.write(), undefined, undefined, undefined, config);
26771 }
26772
26773 /**
26774 * Returns an array of KeyIDs of all of the issuers who created this signature
26775 * @returns {Array<KeyID>} The Key IDs of the signing keys
26776 */
26777 getSigningKeyIDs() {
26778 return this.packets.map(packet => packet.issuerKeyID);
26779 }
26780 }
26781
26782 /**
26783 * reads an (optionally armored) OpenPGP signature and returns a signature object
26784 * @param {Object} options
26785 * @param {String} [options.armoredSignature] - Armored signature to be parsed
26786 * @param {Uint8Array} [options.binarySignature] - Binary signature to be parsed
26787 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
26788 * @returns {Promise<Signature>} New signature object.
26789 * @async
26790 * @static
26791 */
26792 async function readSignature({ armoredSignature, binarySignature, config, ...rest }) {
26793 config = { ...defaultConfig, ...config };
26794 let input = armoredSignature || binarySignature;
26795 if (!input) {
26796 throw new Error('readSignature: must pass options object containing `armoredSignature` or `binarySignature`');
26797 }
26798 if (armoredSignature && !util.isString(armoredSignature)) {
26799 throw new Error('readSignature: options.armoredSignature must be a string');
26800 }
26801 if (binarySignature && !util.isUint8Array(binarySignature)) {
26802 throw new Error('readSignature: options.binarySignature must be a Uint8Array');
26803 }
26804 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
26805
26806 if (armoredSignature) {
26807 const { type, data } = await unarmor(input, config);
26808 if (type !== enums.armor.signature) {
26809 throw new Error('Armored text not of type signature');
26810 }
26811 input = data;
26812 }
26813 const packetlist = await PacketList.fromBinary(input, allowedPackets$4, config);
26814 return new Signature(packetlist);
26815 }
26816
26817 /**
26818 * @fileoverview Provides helpers methods for key module
26819 * @module key/helper
26820 * @private
26821 */
26822
26823 async function generateSecretSubkey(options, config) {
26824 const secretSubkeyPacket = new SecretSubkeyPacket(options.date, config);
26825 secretSubkeyPacket.packets = null;
26826 secretSubkeyPacket.algorithm = enums.read(enums.publicKey, options.algorithm);
26827 await secretSubkeyPacket.generate(options.rsaBits, options.curve);
26828 await secretSubkeyPacket.computeFingerprintAndKeyID();
26829 return secretSubkeyPacket;
26830 }
26831
26832 async function generateSecretKey(options, config) {
26833 const secretKeyPacket = new SecretKeyPacket(options.date, config);
26834 secretKeyPacket.packets = null;
26835 secretKeyPacket.algorithm = enums.read(enums.publicKey, options.algorithm);
26836 await secretKeyPacket.generate(options.rsaBits, options.curve, options.config);
26837 await secretKeyPacket.computeFingerprintAndKeyID();
26838 return secretKeyPacket;
26839 }
26840
26841 /**
26842 * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.
26843 * @param {Array<SignaturePacket>} signatures - List of signatures
26844 * @param {PublicKeyPacket|PublicSubkeyPacket} publicKey - Public key packet to verify the signature
26845 * @param {Date} date - Use the given date instead of the current time
26846 * @param {Object} config - full configuration
26847 * @returns {Promise<SignaturePacket>} The latest valid signature.
26848 * @async
26849 */
26850 async function getLatestValidSignature(signatures, publicKey, signatureType, dataToVerify, date = new Date(), config) {
26851 let latestValid;
26852 let exception;
26853 for (let i = signatures.length - 1; i >= 0; i--) {
26854 try {
26855 if (
26856 (!latestValid || signatures[i].created >= latestValid.created)
26857 ) {
26858 await signatures[i].verify(publicKey, signatureType, dataToVerify, date, undefined, config);
26859 latestValid = signatures[i];
26860 }
26861 } catch (e) {
26862 exception = e;
26863 }
26864 }
26865 if (!latestValid) {
26866 throw util.wrapError(
26867 `Could not find valid ${enums.read(enums.signature, signatureType)} signature in key ${publicKey.getKeyID().toHex()}`
26868 .replace('certGeneric ', 'self-')
26869 .replace(/([a-z])([A-Z])/g, (_, $1, $2) => $1 + ' ' + $2.toLowerCase())
26870 , exception);
26871 }
26872 return latestValid;
26873 }
26874
26875 function isDataExpired(keyPacket, signature, date = new Date()) {
26876 const normDate = util.normalizeDate(date);
26877 if (normDate !== null) {
26878 const expirationTime = getKeyExpirationTime(keyPacket, signature);
26879 return !(keyPacket.created <= normDate && normDate < expirationTime);
26880 }
26881 return false;
26882 }
26883
26884 /**
26885 * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}
26886 * @param {SecretSubkeyPacket} subkey - Subkey key packet
26887 * @param {SecretKeyPacket} primaryKey - Primary key packet
26888 * @param {Object} options
26889 * @param {Object} config - Full configuration
26890 */
26891 async function createBindingSignature(subkey, primaryKey, options, config) {
26892 const dataToSign = {};
26893 dataToSign.key = primaryKey;
26894 dataToSign.bind = subkey;
26895 const subkeySignaturePacket = new SignaturePacket();
26896 subkeySignaturePacket.signatureType = enums.signature.subkeyBinding;
26897 subkeySignaturePacket.publicKeyAlgorithm = primaryKey.algorithm;
26898 subkeySignaturePacket.hashAlgorithm = await getPreferredHashAlgo$1(null, subkey, undefined, undefined, config);
26899 if (options.sign) {
26900 subkeySignaturePacket.keyFlags = [enums.keyFlags.signData];
26901 subkeySignaturePacket.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, {
26902 signatureType: enums.signature.keyBinding
26903 }, options.date, undefined, undefined, config);
26904 } else {
26905 subkeySignaturePacket.keyFlags = [enums.keyFlags.encryptCommunication | enums.keyFlags.encryptStorage];
26906 }
26907 if (options.keyExpirationTime > 0) {
26908 subkeySignaturePacket.keyExpirationTime = options.keyExpirationTime;
26909 subkeySignaturePacket.keyNeverExpires = false;
26910 }
26911 await subkeySignaturePacket.sign(primaryKey, dataToSign, options.date);
26912 return subkeySignaturePacket;
26913 }
26914
26915 /**
26916 * Returns the preferred signature hash algorithm of a key
26917 * @param {Key} [key] - The key to get preferences from
26918 * @param {SecretKeyPacket|SecretSubkeyPacket} keyPacket - key packet used for signing
26919 * @param {Date} [date] - Use the given date for verification instead of the current time
26920 * @param {Object} [userID] - User ID
26921 * @param {Object} config - full configuration
26922 * @returns {Promise<String>}
26923 * @async
26924 */
26925 async function getPreferredHashAlgo$1(key, keyPacket, date = new Date(), userID = {}, config) {
26926 let hashAlgo = config.preferredHashAlgorithm;
26927 let prefAlgo = hashAlgo;
26928 if (key) {
26929 const primaryUser = await key.getPrimaryUser(date, userID, config);
26930 if (primaryUser.selfCertification.preferredHashAlgorithms) {
26931 [prefAlgo] = primaryUser.selfCertification.preferredHashAlgorithms;
26932 hashAlgo = mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ?
26933 prefAlgo : hashAlgo;
26934 }
26935 }
26936 switch (Object.getPrototypeOf(keyPacket)) {
26937 case SecretKeyPacket.prototype:
26938 case PublicKeyPacket.prototype:
26939 case SecretSubkeyPacket.prototype:
26940 case PublicSubkeyPacket.prototype:
26941 switch (keyPacket.algorithm) {
26942 case 'ecdh':
26943 case 'ecdsa':
26944 case 'eddsa':
26945 prefAlgo = mod.publicKey.elliptic.getPreferredHashAlgo(keyPacket.publicParams.oid);
26946 }
26947 }
26948 return mod.hash.getHashByteLength(hashAlgo) <= mod.hash.getHashByteLength(prefAlgo) ?
26949 prefAlgo : hashAlgo;
26950 }
26951
26952 /**
26953 * Returns the preferred symmetric/aead/compression algorithm for a set of keys
26954 * @param {symmetric|aead|compression} type - Type of preference to return
26955 * @param {Array<Key>} [keys] - Set of keys
26956 * @param {Date} [date] - Use the given date for verification instead of the current time
26957 * @param {Array} [userIDs] - User IDs
26958 * @param {Object} [config] - Full configuration, defaults to openpgp.config
26959 * @returns {Promise<module:enums.symmetric|aead|compression>} Preferred algorithm
26960 * @async
26961 */
26962 async function getPreferredAlgo(type, keys = [], date = new Date(), userIDs = [], config = defaultConfig) {
26963 const defaultAlgo = { // these are all must-implement in rfc4880bis
26964 'symmetric': enums.symmetric.aes128,
26965 'aead': enums.aead.eax,
26966 'compression': enums.compression.uncompressed
26967 }[type];
26968 const preferredSenderAlgo = {
26969 'symmetric': config.preferredSymmetricAlgorithm,
26970 'aead': config.preferredAEADAlgorithm,
26971 'compression': config.preferredCompressionAlgorithm
26972 }[type];
26973 const prefPropertyName = {
26974 'symmetric': 'preferredSymmetricAlgorithms',
26975 'aead': 'preferredAEADAlgorithms',
26976 'compression': 'preferredCompressionAlgorithms'
26977 }[type];
26978
26979 // if preferredSenderAlgo appears in the prefs of all recipients, we pick it
26980 // otherwise we use the default algo
26981 // if no keys are available, preferredSenderAlgo is returned
26982 const senderAlgoSupport = await Promise.all(keys.map(async function(key, i) {
26983 const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);
26984 const recipientPrefs = primaryUser.selfCertification[prefPropertyName];
26985 return !!recipientPrefs && recipientPrefs.indexOf(preferredSenderAlgo) >= 0;
26986 }));
26987 return senderAlgoSupport.every(Boolean) ? preferredSenderAlgo : defaultAlgo;
26988 }
26989
26990 /**
26991 * Create signature packet
26992 * @param {Object} dataToSign - Contains packets to be signed
26993 * @param {PrivateKey} privateKey - key to get preferences from
26994 * @param {SecretKeyPacket|
26995 * SecretSubkeyPacket} signingKeyPacket secret key packet for signing
26996 * @param {Object} [signatureProperties] - Properties to write on the signature packet before signing
26997 * @param {Date} [date] - Override the creationtime of the signature
26998 * @param {Object} [userID] - User ID
26999 * @param {Object} [detached] - Whether to create a detached signature packet
27000 * @param {Object} config - full configuration
27001 * @returns {Promise<SignaturePacket>} Signature packet.
27002 */
27003 async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userID, detached = false, config) {
27004 if (signingKeyPacket.isDummy()) {
27005 throw new Error('Cannot sign with a gnu-dummy key.');
27006 }
27007 if (!signingKeyPacket.isDecrypted()) {
27008 throw new Error('Signing key is not decrypted.');
27009 }
27010 const signaturePacket = new SignaturePacket();
27011 Object.assign(signaturePacket, signatureProperties);
27012 signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;
27013 signaturePacket.hashAlgorithm = await getPreferredHashAlgo$1(privateKey, signingKeyPacket, date, userID, config);
27014 await signaturePacket.sign(signingKeyPacket, dataToSign, date, detached);
27015 return signaturePacket;
27016 }
27017
27018 /**
27019 * Merges signatures from source[attr] to dest[attr]
27020 * @param {Object} source
27021 * @param {Object} dest
27022 * @param {String} attr
27023 * @param {Date} [date] - date to use for signature expiration check, instead of the current time
27024 * @param {Function} [checkFn] - signature only merged if true
27025 */
27026 async function mergeSignatures(source, dest, attr, date = new Date(), checkFn) {
27027 source = source[attr];
27028 if (source) {
27029 if (!dest[attr].length) {
27030 dest[attr] = source;
27031 } else {
27032 await Promise.all(source.map(async function(sourceSig) {
27033 if (!sourceSig.isExpired(date) && (!checkFn || await checkFn(sourceSig)) &&
27034 !dest[attr].some(function(destSig) {
27035 return util.equalsUint8Array(destSig.writeParams(), sourceSig.writeParams());
27036 })) {
27037 dest[attr].push(sourceSig);
27038 }
27039 }));
27040 }
27041 }
27042 }
27043
27044 /**
27045 * Checks if a given certificate or binding signature is revoked
27046 * @param {SecretKeyPacket|
27047 * PublicKeyPacket} primaryKey The primary key packet
27048 * @param {Object} dataToVerify - The data to check
27049 * @param {Array<SignaturePacket>} revocations - The revocation signatures to check
27050 * @param {SignaturePacket} signature - The certificate or signature to check
27051 * @param {PublicSubkeyPacket|
27052 * SecretSubkeyPacket|
27053 * PublicKeyPacket|
27054 * SecretKeyPacket} key, optional The key packet to verify the signature, instead of the primary key
27055 * @param {Date} date - Use the given date instead of the current time
27056 * @param {Object} config - Full configuration
27057 * @returns {Promise<Boolean>} True if the signature revokes the data.
27058 * @async
27059 */
27060 async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date(), config) {
27061 key = key || primaryKey;
27062 const revocationKeyIDs = [];
27063 await Promise.all(revocations.map(async function(revocationSignature) {
27064 try {
27065 if (
27066 // Note: a third-party revocation signature could legitimately revoke a
27067 // self-signature if the signature has an authorized revocation key.
27068 // However, we don't support passing authorized revocation keys, nor
27069 // verifying such revocation signatures. Instead, we indicate an error
27070 // when parsing a key with an authorized revocation key, and ignore
27071 // third-party revocation signatures here. (It could also be revoking a
27072 // third-party key certification, which should only affect
27073 // `verifyAllCertifications`.)
27074 !signature || revocationSignature.issuerKeyID.equals(signature.issuerKeyID)
27075 ) {
27076 await revocationSignature.verify(
27077 key, signatureType, dataToVerify, config.revocationsExpire ? date : null, false, config
27078 );
27079
27080 // TODO get an identifier of the revoked object instead
27081 revocationKeyIDs.push(revocationSignature.issuerKeyID);
27082 }
27083 } catch (e) {}
27084 }));
27085 // TODO further verify that this is the signature that should be revoked
27086 if (signature) {
27087 signature.revoked = revocationKeyIDs.some(keyID => keyID.equals(signature.issuerKeyID)) ? true :
27088 signature.revoked || false;
27089 return signature.revoked;
27090 }
27091 return revocationKeyIDs.length > 0;
27092 }
27093
27094 /**
27095 * Returns key expiration time based on the given certification signature.
27096 * The expiration time of the signature is ignored.
27097 * @param {PublicSubkeyPacket|PublicKeyPacket} keyPacket - key to check
27098 * @param {SignaturePacket} signature - signature to process
27099 * @returns {Date|Infinity} expiration time or infinity if the key does not expire
27100 */
27101 function getKeyExpirationTime(keyPacket, signature) {
27102 let expirationTime;
27103 // check V4 expiration time
27104 if (signature.keyNeverExpires === false) {
27105 expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;
27106 }
27107 return expirationTime ? new Date(expirationTime) : Infinity;
27108 }
27109
27110 /**
27111 * Returns whether aead is supported by all keys in the set
27112 * @param {Array<Key>} keys - Set of keys
27113 * @param {Date} [date] - Use the given date for verification instead of the current time
27114 * @param {Array} [userIDs] - User IDs
27115 * @param {Object} config - full configuration
27116 * @returns {Promise<Boolean>}
27117 * @async
27118 */
27119 async function isAEADSupported(keys, date = new Date(), userIDs = [], config = defaultConfig) {
27120 let supported = true;
27121 // TODO replace when Promise.some or Promise.any are implemented
27122 await Promise.all(keys.map(async function(key, i) {
27123 const primaryUser = await key.getPrimaryUser(date, userIDs[i], config);
27124 if (!primaryUser.selfCertification.features ||
27125 !(primaryUser.selfCertification.features[0] & enums.features.aead)) {
27126 supported = false;
27127 }
27128 }));
27129 return supported;
27130 }
27131
27132 function sanitizeKeyOptions(options, subkeyDefaults = {}) {
27133 options.type = options.type || subkeyDefaults.type;
27134 options.curve = options.curve || subkeyDefaults.curve;
27135 options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;
27136 options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;
27137 options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
27138 options.date = options.date || subkeyDefaults.date;
27139
27140 options.sign = options.sign || false;
27141
27142 switch (options.type) {
27143 case 'ecc':
27144 try {
27145 options.curve = enums.write(enums.curve, options.curve);
27146 } catch (e) {
27147 throw new Error('Invalid curve');
27148 }
27149 if (options.curve === enums.curve.ed25519 || options.curve === enums.curve.curve25519) {
27150 options.curve = options.sign ? enums.curve.ed25519 : enums.curve.curve25519;
27151 }
27152 if (options.sign) {
27153 options.algorithm = options.curve === enums.curve.ed25519 ? enums.publicKey.eddsa : enums.publicKey.ecdsa;
27154 } else {
27155 options.algorithm = enums.publicKey.ecdh;
27156 }
27157 break;
27158 case 'rsa':
27159 options.algorithm = enums.publicKey.rsaEncryptSign;
27160 break;
27161 default:
27162 throw new Error(`Unsupported key type ${options.type}`);
27163 }
27164 return options;
27165 }
27166
27167 function isValidSigningKeyPacket(keyPacket, signature) {
27168 const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);
27169 return keyAlgo !== enums.publicKey.rsaEncrypt &&
27170 keyAlgo !== enums.publicKey.elgamal &&
27171 keyAlgo !== enums.publicKey.ecdh &&
27172 (!signature.keyFlags ||
27173 (signature.keyFlags[0] & enums.keyFlags.signData) !== 0);
27174 }
27175
27176 function isValidEncryptionKeyPacket(keyPacket, signature) {
27177 const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);
27178 return keyAlgo !== enums.publicKey.dsa &&
27179 keyAlgo !== enums.publicKey.rsaSign &&
27180 keyAlgo !== enums.publicKey.ecdsa &&
27181 keyAlgo !== enums.publicKey.eddsa &&
27182 (!signature.keyFlags ||
27183 (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||
27184 (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0);
27185 }
27186
27187 function isValidDecryptionKeyPacket(signature, config) {
27188 if (config.allowInsecureDecryptionWithSigningKeys) {
27189 // This is only relevant for RSA keys, all other signing algorithms cannot decrypt
27190 return true;
27191 }
27192
27193 return !signature.keyFlags ||
27194 (signature.keyFlags[0] & enums.keyFlags.encryptCommunication) !== 0 ||
27195 (signature.keyFlags[0] & enums.keyFlags.encryptStorage) !== 0;
27196 }
27197
27198 /**
27199 * Check key against blacklisted algorithms and minimum strength requirements.
27200 * @param {SecretKeyPacket|PublicKeyPacket|
27201 * SecretSubkeyPacket|PublicSubkeyPacket} keyPacket
27202 * @param {Config} config
27203 * @throws {Error} if the key packet does not meet the requirements
27204 */
27205 function checkKeyRequirements(keyPacket, config) {
27206 const keyAlgo = enums.write(enums.publicKey, keyPacket.algorithm);
27207 if (config.rejectPublicKeyAlgorithms.has(keyAlgo)) {
27208 throw new Error(`${keyPacket.algorithm} keys are considered too weak.`);
27209 }
27210 const algoInfo = keyPacket.getAlgorithmInfo();
27211 switch (keyAlgo) {
27212 case enums.publicKey.rsaEncryptSign:
27213 case enums.publicKey.rsaSign:
27214 case enums.publicKey.rsaEncrypt:
27215 if (algoInfo.bits < config.minRSABits) {
27216 throw new Error(`RSA keys shorter than ${config.minRSABits} bits are considered too weak.`);
27217 }
27218 break;
27219 case enums.publicKey.ecdsa:
27220 case enums.publicKey.eddsa:
27221 case enums.publicKey.ecdh:
27222 if (config.rejectCurves.has(algoInfo.curve)) {
27223 throw new Error(`Support for ${keyPacket.algorithm} keys using curve ${algoInfo.curve} is disabled.`);
27224 }
27225 break;
27226 }
27227 }
27228
27229 /**
27230 * @module key/User
27231 * @private
27232 */
27233
27234 /**
27235 * Class that represents an user ID or attribute packet and the relevant signatures.
27236 * @param {UserIDPacket|UserAttributePacket} userPacket - packet containing the user info
27237 * @param {Key} mainKey - reference to main Key object containing the primary key and subkeys that the user is associated with
27238 */
27239 class User {
27240 constructor(userPacket, mainKey) {
27241 this.userID = userPacket.constructor.tag === enums.packet.userID ? userPacket : null;
27242 this.userAttribute = userPacket.constructor.tag === enums.packet.userAttribute ? userPacket : null;
27243 this.selfCertifications = [];
27244 this.otherCertifications = [];
27245 this.revocationSignatures = [];
27246 this.mainKey = mainKey;
27247 }
27248
27249 /**
27250 * Transforms structured user data to packetlist
27251 * @returns {PacketList}
27252 */
27253 toPacketList() {
27254 const packetlist = new PacketList();
27255 packetlist.push(this.userID || this.userAttribute);
27256 packetlist.push(...this.revocationSignatures);
27257 packetlist.push(...this.selfCertifications);
27258 packetlist.push(...this.otherCertifications);
27259 return packetlist;
27260 }
27261
27262 /**
27263 * Shallow clone
27264 * @returns {User}
27265 */
27266 clone() {
27267 const user = new User(this.userID || this.userAttribute, this.mainKey);
27268 user.selfCertifications = [...this.selfCertifications];
27269 user.otherCertifications = [...this.otherCertifications];
27270 user.revocationSignatures = [...this.revocationSignatures];
27271 return user;
27272 }
27273
27274 /**
27275 * Generate third-party certifications over this user and its primary key
27276 * @param {Array<PrivateKey>} signingKeys - Decrypted private keys for signing
27277 * @param {Date} [date] - Date to use as creation date of the certificate, instead of the current time
27278 * @param {Object} config - Full configuration
27279 * @returns {Promise<User>} New user with new certifications.
27280 * @async
27281 */
27282 async certify(signingKeys, date, config) {
27283 const primaryKey = this.mainKey.keyPacket;
27284 const dataToSign = {
27285 userID: this.userID,
27286 userAttribute: this.userAttribute,
27287 key: primaryKey
27288 };
27289 const user = new User(dataToSign.userID || dataToSign.userAttribute, this.mainKey);
27290 user.otherCertifications = await Promise.all(signingKeys.map(async function(privateKey) {
27291 if (!privateKey.isPrivate()) {
27292 throw new Error('Need private key for signing');
27293 }
27294 if (privateKey.hasSameFingerprintAs(primaryKey)) {
27295 throw new Error("The user's own key can only be used for self-certifications");
27296 }
27297 const signingKey = await privateKey.getSigningKey(undefined, date, undefined, config);
27298 return createSignaturePacket(dataToSign, privateKey, signingKey.keyPacket, {
27299 // Most OpenPGP implementations use generic certification (0x10)
27300 signatureType: enums.signature.certGeneric,
27301 keyFlags: [enums.keyFlags.certifyKeys | enums.keyFlags.signData]
27302 }, date, undefined, undefined, config);
27303 }));
27304 await user.update(this, date, config);
27305 return user;
27306 }
27307
27308 /**
27309 * Checks if a given certificate of the user is revoked
27310 * @param {SignaturePacket} certificate - The certificate to verify
27311 * @param {PublicSubkeyPacket|
27312 * SecretSubkeyPacket|
27313 * PublicKeyPacket|
27314 * SecretKeyPacket} [keyPacket] The key packet to verify the signature, instead of the primary key
27315 * @param {Date} [date] - Use the given date for verification instead of the current time
27316 * @param {Object} config - Full configuration
27317 * @returns {Promise<Boolean>} True if the certificate is revoked.
27318 * @async
27319 */
27320 async isRevoked(certificate, keyPacket, date = new Date(), config) {
27321 const primaryKey = this.mainKey.keyPacket;
27322 return isDataRevoked(primaryKey, enums.signature.certRevocation, {
27323 key: primaryKey,
27324 userID: this.userID,
27325 userAttribute: this.userAttribute
27326 }, this.revocationSignatures, certificate, keyPacket, date, config);
27327 }
27328
27329 /**
27330 * Verifies the user certificate.
27331 * @param {SignaturePacket} certificate - A certificate of this user
27332 * @param {Array<PublicKey>} verificationKeys - Array of keys to verify certificate signatures
27333 * @param {Date} [date] - Use the given date instead of the current time
27334 * @param {Object} config - Full configuration
27335 * @returns {Promise<true|null>} true if the certificate could be verified, or null if the verification keys do not correspond to the certificate
27336 * @throws if the user certificate is invalid.
27337 * @async
27338 */
27339 async verifyCertificate(certificate, verificationKeys, date = new Date(), config) {
27340 const that = this;
27341 const primaryKey = this.mainKey.keyPacket;
27342 const dataToVerify = {
27343 userID: this.userID,
27344 userAttribute: this.userAttribute,
27345 key: primaryKey
27346 };
27347 const { issuerKeyID } = certificate;
27348 const issuerKeys = verificationKeys.filter(key => key.getKeys(issuerKeyID).length > 0);
27349 if (issuerKeys.length === 0) {
27350 return null;
27351 }
27352 await Promise.all(issuerKeys.map(async key => {
27353 const signingKey = await key.getSigningKey(issuerKeyID, certificate.created, undefined, config);
27354 if (certificate.revoked || await that.isRevoked(certificate, signingKey.keyPacket, date, config)) {
27355 throw new Error('User certificate is revoked');
27356 }
27357 try {
27358 await certificate.verify(signingKey.keyPacket, enums.signature.certGeneric, dataToVerify, date, undefined, config);
27359 } catch (e) {
27360 throw util.wrapError('User certificate is invalid', e);
27361 }
27362 }));
27363 return true;
27364 }
27365
27366 /**
27367 * Verifies all user certificates
27368 * @param {Array<PublicKey>} verificationKeys - Array of keys to verify certificate signatures
27369 * @param {Date} [date] - Use the given date instead of the current time
27370 * @param {Object} config - Full configuration
27371 * @returns {Promise<Array<{
27372 * keyID: module:type/keyid~KeyID,
27373 * valid: Boolean | null
27374 * }>>} List of signer's keyID and validity of signature.
27375 * Signature validity is null if the verification keys do not correspond to the certificate.
27376 * @async
27377 */
27378 async verifyAllCertifications(verificationKeys, date = new Date(), config) {
27379 const that = this;
27380 const certifications = this.selfCertifications.concat(this.otherCertifications);
27381 return Promise.all(certifications.map(async certification => ({
27382 keyID: certification.issuerKeyID,
27383 valid: await that.verifyCertificate(certification, verificationKeys, date, config).catch(() => false)
27384 })));
27385 }
27386
27387 /**
27388 * Verify User. Checks for existence of self signatures, revocation signatures
27389 * and validity of self signature.
27390 * @param {Date} date - Use the given date instead of the current time
27391 * @param {Object} config - Full configuration
27392 * @returns {Promise<true>} Status of user.
27393 * @throws {Error} if there are no valid self signatures.
27394 * @async
27395 */
27396 async verify(date = new Date(), config) {
27397 if (!this.selfCertifications.length) {
27398 throw new Error('No self-certifications found');
27399 }
27400 const that = this;
27401 const primaryKey = this.mainKey.keyPacket;
27402 const dataToVerify = {
27403 userID: this.userID,
27404 userAttribute: this.userAttribute,
27405 key: primaryKey
27406 };
27407 // TODO replace when Promise.some or Promise.any are implemented
27408 let exception;
27409 for (let i = this.selfCertifications.length - 1; i >= 0; i--) {
27410 try {
27411 const selfCertification = this.selfCertifications[i];
27412 if (selfCertification.revoked || await that.isRevoked(selfCertification, undefined, date, config)) {
27413 throw new Error('Self-certification is revoked');
27414 }
27415 try {
27416 await selfCertification.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, undefined, config);
27417 } catch (e) {
27418 throw util.wrapError('Self-certification is invalid', e);
27419 }
27420 return true;
27421 } catch (e) {
27422 exception = e;
27423 }
27424 }
27425 throw exception;
27426 }
27427
27428 /**
27429 * Update user with new components from specified user
27430 * @param {User} sourceUser - Source user to merge
27431 * @param {Date} date - Date to verify the validity of signatures
27432 * @param {Object} config - Full configuration
27433 * @returns {Promise<undefined>}
27434 * @async
27435 */
27436 async update(sourceUser, date, config) {
27437 const primaryKey = this.mainKey.keyPacket;
27438 const dataToVerify = {
27439 userID: this.userID,
27440 userAttribute: this.userAttribute,
27441 key: primaryKey
27442 };
27443 // self signatures
27444 await mergeSignatures(sourceUser, this, 'selfCertifications', date, async function(srcSelfSig) {
27445 try {
27446 await srcSelfSig.verify(primaryKey, enums.signature.certGeneric, dataToVerify, date, false, config);
27447 return true;
27448 } catch (e) {
27449 return false;
27450 }
27451 });
27452 // other signatures
27453 await mergeSignatures(sourceUser, this, 'otherCertifications', date);
27454 // revocation signatures
27455 await mergeSignatures(sourceUser, this, 'revocationSignatures', date, function(srcRevSig) {
27456 return isDataRevoked(primaryKey, enums.signature.certRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);
27457 });
27458 }
27459 }
27460
27461 /**
27462 * @module key/Subkey
27463 * @private
27464 */
27465
27466 /**
27467 * Class that represents a subkey packet and the relevant signatures.
27468 * @borrows PublicSubkeyPacket#getKeyID as Subkey#getKeyID
27469 * @borrows PublicSubkeyPacket#getFingerprint as Subkey#getFingerprint
27470 * @borrows PublicSubkeyPacket#hasSameFingerprintAs as Subkey#hasSameFingerprintAs
27471 * @borrows PublicSubkeyPacket#getAlgorithmInfo as Subkey#getAlgorithmInfo
27472 * @borrows PublicSubkeyPacket#getCreationTime as Subkey#getCreationTime
27473 * @borrows PublicSubkeyPacket#isDecrypted as Subkey#isDecrypted
27474 */
27475 class Subkey {
27476 /**
27477 * @param {SecretSubkeyPacket|PublicSubkeyPacket} subkeyPacket - subkey packet to hold in the Subkey
27478 * @param {Key} mainKey - reference to main Key object, containing the primary key packet corresponding to the subkey
27479 */
27480 constructor(subkeyPacket, mainKey) {
27481 this.keyPacket = subkeyPacket;
27482 this.bindingSignatures = [];
27483 this.revocationSignatures = [];
27484 this.mainKey = mainKey;
27485 }
27486
27487 /**
27488 * Transforms structured subkey data to packetlist
27489 * @returns {PacketList}
27490 */
27491 toPacketList() {
27492 const packetlist = new PacketList();
27493 packetlist.push(this.keyPacket);
27494 packetlist.push(...this.revocationSignatures);
27495 packetlist.push(...this.bindingSignatures);
27496 return packetlist;
27497 }
27498
27499 /**
27500 * Shallow clone
27501 * @return {Subkey}
27502 */
27503 clone() {
27504 const subkey = new Subkey(this.keyPacket, this.mainKey);
27505 subkey.bindingSignatures = [...this.bindingSignatures];
27506 subkey.revocationSignatures = [...this.revocationSignatures];
27507 return subkey;
27508 }
27509
27510 /**
27511 * Checks if a binding signature of a subkey is revoked
27512 * @param {SignaturePacket} signature - The binding signature to verify
27513 * @param {PublicSubkeyPacket|
27514 * SecretSubkeyPacket|
27515 * PublicKeyPacket|
27516 * SecretKeyPacket} key, optional The key to verify the signature
27517 * @param {Date} [date] - Use the given date for verification instead of the current time
27518 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27519 * @returns {Promise<Boolean>} True if the binding signature is revoked.
27520 * @async
27521 */
27522 async isRevoked(signature, key, date = new Date(), config = defaultConfig) {
27523 const primaryKey = this.mainKey.keyPacket;
27524 return isDataRevoked(
27525 primaryKey, enums.signature.subkeyRevocation, {
27526 key: primaryKey,
27527 bind: this.keyPacket
27528 }, this.revocationSignatures, signature, key, date, config
27529 );
27530 }
27531
27532 /**
27533 * Verify subkey. Checks for revocation signatures, expiration time
27534 * and valid binding signature.
27535 * @param {Date} date - Use the given date instead of the current time
27536 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27537 * @returns {Promise<SignaturePacket>}
27538 * @throws {Error} if the subkey is invalid.
27539 * @async
27540 */
27541 async verify(date = new Date(), config = defaultConfig) {
27542 const primaryKey = this.mainKey.keyPacket;
27543 const dataToVerify = { key: primaryKey, bind: this.keyPacket };
27544 // check subkey binding signatures
27545 const bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
27546 // check binding signature is not revoked
27547 if (bindingSignature.revoked || await this.isRevoked(bindingSignature, null, date, config)) {
27548 throw new Error('Subkey is revoked');
27549 }
27550 // check for expiration time
27551 if (isDataExpired(this.keyPacket, bindingSignature, date)) {
27552 throw new Error('Subkey is expired');
27553 }
27554 return bindingSignature;
27555 }
27556
27557 /**
27558 * Returns the expiration time of the subkey or Infinity if key does not expire.
27559 * Returns null if the subkey is invalid.
27560 * @param {Date} date - Use the given date instead of the current time
27561 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27562 * @returns {Promise<Date | Infinity | null>}
27563 * @async
27564 */
27565 async getExpirationTime(date = new Date(), config = defaultConfig) {
27566 const primaryKey = this.mainKey.keyPacket;
27567 const dataToVerify = { key: primaryKey, bind: this.keyPacket };
27568 let bindingSignature;
27569 try {
27570 bindingSignature = await getLatestValidSignature(this.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
27571 } catch (e) {
27572 return null;
27573 }
27574 const keyExpiry = getKeyExpirationTime(this.keyPacket, bindingSignature);
27575 const sigExpiry = bindingSignature.getExpirationTime();
27576 return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;
27577 }
27578
27579 /**
27580 * Update subkey with new components from specified subkey
27581 * @param {Subkey} subkey - Source subkey to merge
27582 * @param {Date} [date] - Date to verify validity of signatures
27583 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27584 * @throws {Error} if update failed
27585 * @async
27586 */
27587 async update(subkey, date = new Date(), config = defaultConfig) {
27588 const primaryKey = this.mainKey.keyPacket;
27589 if (!this.hasSameFingerprintAs(subkey)) {
27590 throw new Error('Subkey update method: fingerprints of subkeys not equal');
27591 }
27592 // key packet
27593 if (this.keyPacket.constructor.tag === enums.packet.publicSubkey &&
27594 subkey.keyPacket.constructor.tag === enums.packet.secretSubkey) {
27595 this.keyPacket = subkey.keyPacket;
27596 }
27597 // update missing binding signatures
27598 const that = this;
27599 const dataToVerify = { key: primaryKey, bind: that.keyPacket };
27600 await mergeSignatures(subkey, this, 'bindingSignatures', date, async function(srcBindSig) {
27601 for (let i = 0; i < that.bindingSignatures.length; i++) {
27602 if (that.bindingSignatures[i].issuerKeyID.equals(srcBindSig.issuerKeyID)) {
27603 if (srcBindSig.created > that.bindingSignatures[i].created) {
27604 that.bindingSignatures[i] = srcBindSig;
27605 }
27606 return false;
27607 }
27608 }
27609 try {
27610 await srcBindSig.verify(primaryKey, enums.signature.subkeyBinding, dataToVerify, date, undefined, config);
27611 return true;
27612 } catch (e) {
27613 return false;
27614 }
27615 });
27616 // revocation signatures
27617 await mergeSignatures(subkey, this, 'revocationSignatures', date, function(srcRevSig) {
27618 return isDataRevoked(primaryKey, enums.signature.subkeyRevocation, dataToVerify, [srcRevSig], undefined, undefined, date, config);
27619 });
27620 }
27621
27622 /**
27623 * Revokes the subkey
27624 * @param {SecretKeyPacket} primaryKey - decrypted private primary key for revocation
27625 * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation
27626 * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
27627 * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation
27628 * @param {Date} date - optional, override the creationtime of the revocation signature
27629 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27630 * @returns {Promise<Subkey>} New subkey with revocation signature.
27631 * @async
27632 */
27633 async revoke(
27634 primaryKey,
27635 {
27636 flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,
27637 string: reasonForRevocationString = ''
27638 } = {},
27639 date = new Date(),
27640 config = defaultConfig
27641 ) {
27642 const dataToSign = { key: primaryKey, bind: this.keyPacket };
27643 const subkey = new Subkey(this.keyPacket, this.mainKey);
27644 subkey.revocationSignatures.push(await createSignaturePacket(dataToSign, null, primaryKey, {
27645 signatureType: enums.signature.subkeyRevocation,
27646 reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),
27647 reasonForRevocationString
27648 }, date, undefined, false, config));
27649 await subkey.update(this);
27650 return subkey;
27651 }
27652
27653 hasSameFingerprintAs(other) {
27654 return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);
27655 }
27656 }
27657
27658 ['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {
27659 Subkey.prototype[name] =
27660 function() {
27661 return this.keyPacket[name]();
27662 };
27663 });
27664
27665 // GPG4Browsers - An OpenPGP implementation in javascript
27666
27667 // A key revocation certificate can contain the following packets
27668 const allowedRevocationPackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
27669
27670 /**
27671 * Abstract class that represents an OpenPGP key. Must contain a primary key.
27672 * Can contain additional subkeys, signatures, user ids, user attributes.
27673 * @borrows PublicKeyPacket#getKeyID as Key#getKeyID
27674 * @borrows PublicKeyPacket#getFingerprint as Key#getFingerprint
27675 * @borrows PublicKeyPacket#hasSameFingerprintAs as Key#hasSameFingerprintAs
27676 * @borrows PublicKeyPacket#getAlgorithmInfo as Key#getAlgorithmInfo
27677 * @borrows PublicKeyPacket#getCreationTime as Key#getCreationTime
27678 */
27679 class Key {
27680 /**
27681 * Transforms packetlist to structured key data
27682 * @param {PacketList} packetlist - The packets that form a key
27683 * @param {Set<enums.packet>} disallowedPackets - disallowed packet tags
27684 */
27685 packetListToStructure(packetlist, disallowedPackets = new Set()) {
27686 let user;
27687 let primaryKeyID;
27688 let subkey;
27689 for (const packet of packetlist) {
27690 const tag = packet.constructor.tag;
27691 if (disallowedPackets.has(tag)) {
27692 throw new Error(`Unexpected packet type: ${tag}`);
27693 }
27694 switch (tag) {
27695 case enums.packet.publicKey:
27696 case enums.packet.secretKey:
27697 if (this.keyPacket) {
27698 throw new Error('Key block contains multiple keys');
27699 }
27700 this.keyPacket = packet;
27701 primaryKeyID = this.getKeyID();
27702 if (!primaryKeyID) {
27703 throw new Error('Missing Key ID');
27704 }
27705 break;
27706 case enums.packet.userID:
27707 case enums.packet.userAttribute:
27708 user = new User(packet, this);
27709 this.users.push(user);
27710 break;
27711 case enums.packet.publicSubkey:
27712 case enums.packet.secretSubkey:
27713 user = null;
27714 subkey = new Subkey(packet, this);
27715 this.subkeys.push(subkey);
27716 break;
27717 case enums.packet.signature:
27718 switch (packet.signatureType) {
27719 case enums.signature.certGeneric:
27720 case enums.signature.certPersona:
27721 case enums.signature.certCasual:
27722 case enums.signature.certPositive:
27723 if (!user) {
27724 util.printDebug('Dropping certification signatures without preceding user packet');
27725 continue;
27726 }
27727 if (packet.issuerKeyID.equals(primaryKeyID)) {
27728 user.selfCertifications.push(packet);
27729 } else {
27730 user.otherCertifications.push(packet);
27731 }
27732 break;
27733 case enums.signature.certRevocation:
27734 if (user) {
27735 user.revocationSignatures.push(packet);
27736 } else {
27737 this.directSignatures.push(packet);
27738 }
27739 break;
27740 case enums.signature.key:
27741 this.directSignatures.push(packet);
27742 break;
27743 case enums.signature.subkeyBinding:
27744 if (!subkey) {
27745 util.printDebug('Dropping subkey binding signature without preceding subkey packet');
27746 continue;
27747 }
27748 subkey.bindingSignatures.push(packet);
27749 break;
27750 case enums.signature.keyRevocation:
27751 this.revocationSignatures.push(packet);
27752 break;
27753 case enums.signature.subkeyRevocation:
27754 if (!subkey) {
27755 util.printDebug('Dropping subkey revocation signature without preceding subkey packet');
27756 continue;
27757 }
27758 subkey.revocationSignatures.push(packet);
27759 break;
27760 }
27761 break;
27762 }
27763 }
27764 }
27765
27766 /**
27767 * Transforms structured key data to packetlist
27768 * @returns {PacketList} The packets that form a key.
27769 */
27770 toPacketList() {
27771 const packetlist = new PacketList();
27772 packetlist.push(this.keyPacket);
27773 packetlist.push(...this.revocationSignatures);
27774 packetlist.push(...this.directSignatures);
27775 this.users.map(user => packetlist.push(...user.toPacketList()));
27776 this.subkeys.map(subkey => packetlist.push(...subkey.toPacketList()));
27777 return packetlist;
27778 }
27779
27780 /**
27781 * Clones the key object
27782 * @param {Boolean} [deep=false] Whether to return a deep clone
27783 * @returns {Promise<Key>} Clone of the key.
27784 */
27785 clone(deep = false) {
27786 const key = new this.constructor(this.toPacketList());
27787 if (deep) {
27788 key.getKeys().forEach(k => {
27789 // shallow clone the key packets
27790 k.keyPacket = Object.create(
27791 Object.getPrototypeOf(k.keyPacket),
27792 Object.getOwnPropertyDescriptors(k.keyPacket)
27793 );
27794 if (!k.keyPacket.isDecrypted()) return;
27795 // deep clone the private params, which are cleared during encryption
27796 const privateParams = {};
27797 Object.keys(k.keyPacket.privateParams).forEach(name => {
27798 privateParams[name] = new Uint8Array(k.keyPacket.privateParams[name]);
27799 });
27800 k.keyPacket.privateParams = privateParams;
27801 });
27802 }
27803 return key;
27804 }
27805
27806 /**
27807 * Returns an array containing all public or private subkeys matching keyID;
27808 * If no keyID is given, returns all subkeys.
27809 * @param {type/keyID} [keyID] - key ID to look for
27810 * @returns {Array<Subkey>} array of subkeys
27811 */
27812 getSubkeys(keyID = null) {
27813 const subkeys = this.subkeys.filter(subkey => (
27814 !keyID || subkey.getKeyID().equals(keyID, true)
27815 ));
27816 return subkeys;
27817 }
27818
27819 /**
27820 * Returns an array containing all public or private keys matching keyID.
27821 * If no keyID is given, returns all keys, starting with the primary key.
27822 * @param {type/keyid~KeyID} [keyID] - key ID to look for
27823 * @returns {Array<Key|Subkey>} array of keys
27824 */
27825 getKeys(keyID = null) {
27826 const keys = [];
27827 if (!keyID || this.getKeyID().equals(keyID, true)) {
27828 keys.push(this);
27829 }
27830 return keys.concat(this.getSubkeys(keyID));
27831 }
27832
27833 /**
27834 * Returns key IDs of all keys
27835 * @returns {Array<module:type/keyid~KeyID>}
27836 */
27837 getKeyIDs() {
27838 return this.getKeys().map(key => key.getKeyID());
27839 }
27840
27841 /**
27842 * Returns userIDs
27843 * @returns {Array<string>} Array of userIDs.
27844 */
27845 getUserIDs() {
27846 return this.users.map(user => {
27847 return user.userID ? user.userID.userID : null;
27848 }).filter(userID => userID !== null);
27849 }
27850
27851 /**
27852 * Returns binary encoded key
27853 * @returns {Uint8Array} Binary key.
27854 */
27855 write() {
27856 return this.toPacketList().write();
27857 }
27858
27859 /**
27860 * Returns last created key or key by given keyID that is available for signing and verification
27861 * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve
27862 * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date
27863 * @param {Object} [userID] - filter keys for the given user ID
27864 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27865 * @returns {Promise<Key|Subkey>} signing key
27866 * @throws if no valid signing key was found
27867 * @async
27868 */
27869 async getSigningKey(keyID = null, date = new Date(), userID = {}, config = defaultConfig) {
27870 await this.verifyPrimaryKey(date, userID, config);
27871 const primaryKey = this.keyPacket;
27872 const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);
27873 let exception;
27874 for (const subkey of subkeys) {
27875 if (!keyID || subkey.getKeyID().equals(keyID)) {
27876 try {
27877 await subkey.verify(date, config);
27878 const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };
27879 const bindingSignature = await getLatestValidSignature(
27880 subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config
27881 );
27882 if (!isValidSigningKeyPacket(subkey.keyPacket, bindingSignature)) {
27883 continue;
27884 }
27885 if (!bindingSignature.embeddedSignature) {
27886 throw new Error('Missing embedded signature');
27887 }
27888 // verify embedded signature
27889 await getLatestValidSignature(
27890 [bindingSignature.embeddedSignature], subkey.keyPacket, enums.signature.keyBinding, dataToVerify, date, config
27891 );
27892 checkKeyRequirements(subkey.keyPacket, config);
27893 return subkey;
27894 } catch (e) {
27895 exception = e;
27896 }
27897 }
27898 }
27899
27900 try {
27901 const primaryUser = await this.getPrimaryUser(date, userID, config);
27902 if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&
27903 isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification, config)) {
27904 checkKeyRequirements(primaryKey, config);
27905 return this;
27906 }
27907 } catch (e) {
27908 exception = e;
27909 }
27910 throw util.wrapError('Could not find valid signing key packet in key ' + this.getKeyID().toHex(), exception);
27911 }
27912
27913 /**
27914 * Returns last created key or key by given keyID that is available for encryption or decryption
27915 * @param {module:type/keyid~KeyID} [keyID] - key ID of a specific key to retrieve
27916 * @param {Date} [date] - use the fiven date date to to check key validity instead of the current date
27917 * @param {Object} [userID] - filter keys for the given user ID
27918 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27919 * @returns {Promise<Key|Subkey>} encryption key
27920 * @throws if no valid encryption key was found
27921 * @async
27922 */
27923 async getEncryptionKey(keyID, date = new Date(), userID = {}, config = defaultConfig) {
27924 await this.verifyPrimaryKey(date, userID, config);
27925 const primaryKey = this.keyPacket;
27926 // V4: by convention subkeys are preferred for encryption service
27927 const subkeys = this.subkeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);
27928 let exception;
27929 for (const subkey of subkeys) {
27930 if (!keyID || subkey.getKeyID().equals(keyID)) {
27931 try {
27932 await subkey.verify(date, config);
27933 const dataToVerify = { key: primaryKey, bind: subkey.keyPacket };
27934 const bindingSignature = await getLatestValidSignature(subkey.bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
27935 if (isValidEncryptionKeyPacket(subkey.keyPacket, bindingSignature)) {
27936 checkKeyRequirements(subkey.keyPacket, config);
27937 return subkey;
27938 }
27939 } catch (e) {
27940 exception = e;
27941 }
27942 }
27943 }
27944
27945 try {
27946 // if no valid subkey for encryption, evaluate primary key
27947 const primaryUser = await this.getPrimaryUser(date, userID, config);
27948 if ((!keyID || primaryKey.getKeyID().equals(keyID)) &&
27949 isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) {
27950 checkKeyRequirements(primaryKey, config);
27951 return this;
27952 }
27953 } catch (e) {
27954 exception = e;
27955 }
27956 throw util.wrapError('Could not find valid encryption key packet in key ' + this.getKeyID().toHex(), exception);
27957 }
27958
27959 /**
27960 * Checks if a signature on a key is revoked
27961 * @param {SignaturePacket} signature - The signature to verify
27962 * @param {PublicSubkeyPacket|
27963 * SecretSubkeyPacket|
27964 * PublicKeyPacket|
27965 * SecretKeyPacket} key, optional The key to verify the signature
27966 * @param {Date} [date] - Use the given date for verification, instead of the current time
27967 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27968 * @returns {Promise<Boolean>} True if the certificate is revoked.
27969 * @async
27970 */
27971 async isRevoked(signature, key, date = new Date(), config = defaultConfig) {
27972 return isDataRevoked(
27973 this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date, config
27974 );
27975 }
27976
27977 /**
27978 * Verify primary key. Checks for revocation signatures, expiration time
27979 * and valid self signature. Throws if the primary key is invalid.
27980 * @param {Date} [date] - Use the given date for verification instead of the current time
27981 * @param {Object} [userID] - User ID
27982 * @param {Object} [config] - Full configuration, defaults to openpgp.config
27983 * @throws {Error} If key verification failed
27984 * @async
27985 */
27986 async verifyPrimaryKey(date = new Date(), userID = {}, config = defaultConfig) {
27987 const primaryKey = this.keyPacket;
27988 // check for key revocation signatures
27989 if (await this.isRevoked(null, null, date, config)) {
27990 throw new Error('Primary key is revoked');
27991 }
27992 // check for valid, unrevoked, unexpired self signature
27993 const { selfCertification } = await this.getPrimaryUser(date, userID, config);
27994 // check for expiration time in binding signatures
27995 if (isDataExpired(primaryKey, selfCertification, date)) {
27996 throw new Error('Primary key is expired');
27997 }
27998 // check for expiration time in direct signatures
27999 const directSignature = await getLatestValidSignature(
28000 this.directSignatures, primaryKey, enums.signature.key, { key: primaryKey }, date, config
28001 ).catch(() => {}); // invalid signatures are discarded, to avoid breaking the key
28002
28003 if (directSignature && isDataExpired(primaryKey, directSignature, date)) {
28004 throw new Error('Primary key is expired');
28005 }
28006 }
28007
28008 /**
28009 * Returns the expiration date of the primary key, considering self-certifications and direct-key signatures.
28010 * Returns `Infinity` if the key doesn't expire, or `null` if the key is revoked or invalid.
28011 * @param {Object} [userID] - User ID to consider instead of the primary user
28012 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28013 * @returns {Promise<Date | Infinity | null>}
28014 * @async
28015 */
28016 async getExpirationTime(userID, config = defaultConfig) {
28017 let primaryKeyExpiry;
28018 try {
28019 const { selfCertification } = await this.getPrimaryUser(null, userID, config);
28020 const selfSigKeyExpiry = getKeyExpirationTime(this.keyPacket, selfCertification);
28021 const selfSigExpiry = selfCertification.getExpirationTime();
28022 const directSignature = await getLatestValidSignature(
28023 this.directSignatures, this.keyPacket, enums.signature.key, { key: this.keyPacket }, null, config
28024 ).catch(() => {});
28025 if (directSignature) {
28026 const directSigKeyExpiry = getKeyExpirationTime(this.keyPacket, directSignature);
28027 // We do not support the edge case where the direct signature expires, since it would invalidate the corresponding key expiration,
28028 // causing a discountinous validy period for the key
28029 primaryKeyExpiry = Math.min(selfSigKeyExpiry, selfSigExpiry, directSigKeyExpiry);
28030 } else {
28031 primaryKeyExpiry = selfSigKeyExpiry < selfSigExpiry ? selfSigKeyExpiry : selfSigExpiry;
28032 }
28033 } catch (e) {
28034 primaryKeyExpiry = null;
28035 }
28036
28037 return util.normalizeDate(primaryKeyExpiry);
28038 }
28039
28040
28041 /**
28042 * Returns primary user and most significant (latest valid) self signature
28043 * - if multiple primary users exist, returns the one with the latest self signature
28044 * - otherwise, returns the user with the latest self signature
28045 * @param {Date} [date] - Use the given date for verification instead of the current time
28046 * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
28047 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28048 * @returns {Promise<{
28049 * user: User,
28050 * selfCertification: SignaturePacket
28051 * }>} The primary user and the self signature
28052 * @async
28053 */
28054 async getPrimaryUser(date = new Date(), userID = {}, config = defaultConfig) {
28055 const primaryKey = this.keyPacket;
28056 const users = [];
28057 let exception;
28058 for (let i = 0; i < this.users.length; i++) {
28059 try {
28060 const user = this.users[i];
28061 if (!user.userID) {
28062 continue;
28063 }
28064 if (
28065 (userID.name !== undefined && user.userID.name !== userID.name) ||
28066 (userID.email !== undefined && user.userID.email !== userID.email) ||
28067 (userID.comment !== undefined && user.userID.comment !== userID.comment)
28068 ) {
28069 throw new Error('Could not find user that matches that user ID');
28070 }
28071 const dataToVerify = { userID: user.userID, key: primaryKey };
28072 const selfCertification = await getLatestValidSignature(user.selfCertifications, primaryKey, enums.signature.certGeneric, dataToVerify, date, config);
28073 users.push({ index: i, user, selfCertification });
28074 } catch (e) {
28075 exception = e;
28076 }
28077 }
28078 if (!users.length) {
28079 throw exception || new Error('Could not find primary user');
28080 }
28081 await Promise.all(users.map(async function (a) {
28082 return a.user.revoked || a.user.isRevoked(a.selfCertification, null, date, config);
28083 }));
28084 // sort by primary user flag and signature creation time
28085 const primaryUser = users.sort(function(a, b) {
28086 const A = a.selfCertification;
28087 const B = b.selfCertification;
28088 return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;
28089 }).pop();
28090 const { user, selfCertification: cert } = primaryUser;
28091 if (cert.revoked || await user.isRevoked(cert, null, date, config)) {
28092 throw new Error('Primary user is revoked');
28093 }
28094 return primaryUser;
28095 }
28096
28097 /**
28098 * Update key with new components from specified key with same key ID:
28099 * users, subkeys, certificates are merged into the destination key,
28100 * duplicates and expired signatures are ignored.
28101 *
28102 * If the source key is a private key and the destination key is public,
28103 * a private key is returned.
28104 * @param {Key} sourceKey - Source key to merge
28105 * @param {Date} [date] - Date to verify validity of signatures and keys
28106 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28107 * @returns {Promise<Key>} updated key
28108 * @async
28109 */
28110 async update(sourceKey, date = new Date(), config = defaultConfig) {
28111 if (!this.hasSameFingerprintAs(sourceKey)) {
28112 throw new Error('Primary key fingerprints must be equal to update the key');
28113 }
28114 if (!this.isPrivate() && sourceKey.isPrivate()) {
28115 // check for equal subkey packets
28116 const equal = (this.subkeys.length === sourceKey.subkeys.length) &&
28117 (this.subkeys.every(destSubkey => {
28118 return sourceKey.subkeys.some(srcSubkey => {
28119 return destSubkey.hasSameFingerprintAs(srcSubkey);
28120 });
28121 }));
28122 if (!equal) {
28123 throw new Error('Cannot update public key with private key if subkeys mismatch');
28124 }
28125
28126 return sourceKey.update(this, config);
28127 }
28128 // from here on, either:
28129 // - destination key is private, source key is public
28130 // - the keys are of the same type
28131 // hence we don't need to convert the destination key type
28132 const updatedKey = this.clone();
28133 // revocation signatures
28134 await mergeSignatures(sourceKey, updatedKey, 'revocationSignatures', date, srcRevSig => {
28135 return isDataRevoked(updatedKey.keyPacket, enums.signature.keyRevocation, updatedKey, [srcRevSig], null, sourceKey.keyPacket, date, config);
28136 });
28137 // direct signatures
28138 await mergeSignatures(sourceKey, updatedKey, 'directSignatures', date);
28139 // update users
28140 await Promise.all(sourceKey.users.map(async srcUser => {
28141 // multiple users with the same ID/attribute are not explicitly disallowed by the spec
28142 // hence we support them, just in case
28143 const usersToUpdate = updatedKey.users.filter(dstUser => (
28144 (srcUser.userID && srcUser.userID.equals(dstUser.userID)) ||
28145 (srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute))
28146 ));
28147 if (usersToUpdate.length > 0) {
28148 await Promise.all(
28149 usersToUpdate.map(userToUpdate => userToUpdate.update(srcUser, date, config))
28150 );
28151 } else {
28152 const newUser = srcUser.clone();
28153 newUser.mainKey = updatedKey;
28154 updatedKey.users.push(newUser);
28155 }
28156 }));
28157 // update subkeys
28158 await Promise.all(sourceKey.subkeys.map(async srcSubkey => {
28159 // multiple subkeys with same fingerprint might be preset
28160 const subkeysToUpdate = updatedKey.subkeys.filter(dstSubkey => (
28161 dstSubkey.hasSameFingerprintAs(srcSubkey)
28162 ));
28163 if (subkeysToUpdate.length > 0) {
28164 await Promise.all(
28165 subkeysToUpdate.map(subkeyToUpdate => subkeyToUpdate.update(srcSubkey, date, config))
28166 );
28167 } else {
28168 const newSubkey = srcSubkey.clone();
28169 newSubkey.mainKey = updatedKey;
28170 updatedKey.subkeys.push(newSubkey);
28171 }
28172 }));
28173
28174 return updatedKey;
28175 }
28176
28177 /**
28178 * Get revocation certificate from a revoked key.
28179 * (To get a revocation certificate for an unrevoked key, call revoke() first.)
28180 * @param {Date} date - Use the given date instead of the current time
28181 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28182 * @returns {Promise<String>} Armored revocation certificate.
28183 * @async
28184 */
28185 async getRevocationCertificate(date = new Date(), config = defaultConfig) {
28186 const dataToVerify = { key: this.keyPacket };
28187 const revocationSignature = await getLatestValidSignature(this.revocationSignatures, this.keyPacket, enums.signature.keyRevocation, dataToVerify, date, config);
28188 const packetlist = new PacketList();
28189 packetlist.push(revocationSignature);
28190 return armor(enums.armor.publicKey, packetlist.write(), null, null, 'This is a revocation certificate');
28191 }
28192
28193 /**
28194 * Applies a revocation certificate to a key
28195 * This adds the first signature packet in the armored text to the key,
28196 * if it is a valid revocation signature.
28197 * @param {String} revocationCertificate - armored revocation certificate
28198 * @param {Date} [date] - Date to verify the certificate
28199 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28200 * @returns {Promise<Key>} Revoked key.
28201 * @async
28202 */
28203 async applyRevocationCertificate(revocationCertificate, date = new Date(), config = defaultConfig) {
28204 const input = await unarmor(revocationCertificate, config);
28205 const packetlist = await PacketList.fromBinary(input.data, allowedRevocationPackets, config);
28206 const revocationSignature = packetlist.findPacket(enums.packet.signature);
28207 if (!revocationSignature || revocationSignature.signatureType !== enums.signature.keyRevocation) {
28208 throw new Error('Could not find revocation signature packet');
28209 }
28210 if (!revocationSignature.issuerKeyID.equals(this.getKeyID())) {
28211 throw new Error('Revocation signature does not match key');
28212 }
28213 try {
28214 await revocationSignature.verify(this.keyPacket, enums.signature.keyRevocation, { key: this.keyPacket }, date, undefined, config);
28215 } catch (e) {
28216 throw util.wrapError('Could not verify revocation signature', e);
28217 }
28218 const key = this.clone();
28219 key.revocationSignatures.push(revocationSignature);
28220 return key;
28221 }
28222
28223 /**
28224 * Signs primary user of key
28225 * @param {Array<PrivateKey>} privateKeys - decrypted private keys for signing
28226 * @param {Date} [date] - Use the given date for verification instead of the current time
28227 * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
28228 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28229 * @returns {Promise<Key>} Key with new certificate signature.
28230 * @async
28231 */
28232 async signPrimaryUser(privateKeys, date, userID, config = defaultConfig) {
28233 const { index, user } = await this.getPrimaryUser(date, userID, config);
28234 const userSign = await user.certify(privateKeys, date, config);
28235 const key = this.clone();
28236 key.users[index] = userSign;
28237 return key;
28238 }
28239
28240 /**
28241 * Signs all users of key
28242 * @param {Array<PrivateKey>} privateKeys - decrypted private keys for signing
28243 * @param {Date} [date] - Use the given date for signing, instead of the current time
28244 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28245 * @returns {Promise<Key>} Key with new certificate signature.
28246 * @async
28247 */
28248 async signAllUsers(privateKeys, date = new Date(), config = defaultConfig) {
28249 const key = this.clone();
28250 key.users = await Promise.all(this.users.map(function(user) {
28251 return user.certify(privateKeys, date, config);
28252 }));
28253 return key;
28254 }
28255
28256 /**
28257 * Verifies primary user of key
28258 * - if no arguments are given, verifies the self certificates;
28259 * - otherwise, verifies all certificates signed with given keys.
28260 * @param {Array<PublicKey>} [verificationKeys] - array of keys to verify certificate signatures, instead of the primary key
28261 * @param {Date} [date] - Use the given date for verification instead of the current time
28262 * @param {Object} [userID] - User ID to get instead of the primary user, if it exists
28263 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28264 * @returns {Promise<Array<{
28265 * keyID: module:type/keyid~KeyID,
28266 * valid: Boolean|null
28267 * }>>} List of signer's keyID and validity of signature.
28268 * Signature validity is null if the verification keys do not correspond to the certificate.
28269 * @async
28270 */
28271 async verifyPrimaryUser(verificationKeys, date = new Date(), userID, config = defaultConfig) {
28272 const primaryKey = this.keyPacket;
28273 const { user } = await this.getPrimaryUser(date, userID, config);
28274 const results = verificationKeys ?
28275 await user.verifyAllCertifications(verificationKeys, date, config) :
28276 [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];
28277 return results;
28278 }
28279
28280 /**
28281 * Verifies all users of key
28282 * - if no arguments are given, verifies the self certificates;
28283 * - otherwise, verifies all certificates signed with given keys.
28284 * @param {Array<PublicKey>} [verificationKeys] - array of keys to verify certificate signatures
28285 * @param {Date} [date] - Use the given date for verification instead of the current time
28286 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28287 * @returns {Promise<Array<{
28288 * userID: String,
28289 * keyID: module:type/keyid~KeyID,
28290 * valid: Boolean|null
28291 * }>>} List of userID, signer's keyID and validity of signature.
28292 * Signature validity is null if the verification keys do not correspond to the certificate.
28293 * @async
28294 */
28295 async verifyAllUsers(verificationKeys, date = new Date(), config = defaultConfig) {
28296 const primaryKey = this.keyPacket;
28297 const results = [];
28298 await Promise.all(this.users.map(async user => {
28299 const signatures = verificationKeys ?
28300 await user.verifyAllCertifications(verificationKeys, date, config) :
28301 [{ keyID: primaryKey.getKeyID(), valid: await user.verify(date, config).catch(() => false) }];
28302
28303 results.push(...signatures.map(
28304 signature => ({
28305 userID: user.userID.userID,
28306 keyID: signature.keyID,
28307 valid: signature.valid
28308 }))
28309 );
28310 }));
28311 return results;
28312 }
28313 }
28314
28315 ['getKeyID', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'hasSameFingerprintAs'].forEach(name => {
28316 Key.prototype[name] =
28317 Subkey.prototype[name];
28318 });
28319
28320 /**
28321 * Creates a PublicKey or PrivateKey depending on the packetlist in input
28322 * @param {PacketList} - packets to parse
28323 * @return {Key} parsed key
28324 * @throws if no key packet was found
28325 */
28326 function createKey(packetlist) {
28327 for (const packet of packetlist) {
28328 switch (packet.constructor.tag) {
28329 case enums.packet.secretKey:
28330 return new PrivateKey(packetlist);
28331 case enums.packet.publicKey:
28332 return new PublicKey(packetlist);
28333 }
28334 }
28335 throw new Error('No key packet found');
28336 }
28337
28338 // This library is free software; you can redistribute it and/or
28339
28340 /**
28341 * Class that represents an OpenPGP Public Key
28342 */
28343 class PublicKey extends Key {
28344 /**
28345 * @param {PacketList} packetlist - The packets that form this key
28346 */
28347 constructor(packetlist) {
28348 super();
28349 this.keyPacket = null;
28350 this.revocationSignatures = [];
28351 this.directSignatures = [];
28352 this.users = [];
28353 this.subkeys = [];
28354 if (packetlist) {
28355 this.packetListToStructure(packetlist, new Set([enums.packet.secretKey, enums.packet.secretSubkey]));
28356 if (!this.keyPacket) {
28357 throw new Error('Invalid key: missing public-key packet');
28358 }
28359 }
28360 }
28361
28362 /**
28363 * Returns true if this is a private key
28364 * @returns {false}
28365 */
28366 isPrivate() {
28367 return false;
28368 }
28369
28370 /**
28371 * Returns key as public key (shallow copy)
28372 * @returns {PublicKey} New public Key
28373 */
28374 toPublic() {
28375 return this;
28376 }
28377
28378 /**
28379 * Returns ASCII armored text of key
28380 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28381 * @returns {ReadableStream<String>} ASCII armor.
28382 */
28383 armor(config = defaultConfig) {
28384 return armor(enums.armor.publicKey, this.toPacketList().write(), undefined, undefined, undefined, config);
28385 }
28386 }
28387
28388 /**
28389 * Class that represents an OpenPGP Private key
28390 */
28391 class PrivateKey extends PublicKey {
28392 /**
28393 * @param {PacketList} packetlist - The packets that form this key
28394 */
28395 constructor(packetlist) {
28396 super();
28397 this.packetListToStructure(packetlist, new Set([enums.packet.publicKey, enums.packet.publicSubkey]));
28398 if (!this.keyPacket) {
28399 throw new Error('Invalid key: missing private-key packet');
28400 }
28401 }
28402
28403 /**
28404 * Returns true if this is a private key
28405 * @returns {Boolean}
28406 */
28407 isPrivate() {
28408 return true;
28409 }
28410
28411 /**
28412 * Returns key as public key (shallow copy)
28413 * @returns {PublicKey} New public Key
28414 */
28415 toPublic() {
28416 const packetlist = new PacketList();
28417 const keyPackets = this.toPacketList();
28418 for (const keyPacket of keyPackets) {
28419 switch (keyPacket.constructor.tag) {
28420 case enums.packet.secretKey: {
28421 const pubKeyPacket = PublicKeyPacket.fromSecretKeyPacket(keyPacket);
28422 packetlist.push(pubKeyPacket);
28423 break;
28424 }
28425 case enums.packet.secretSubkey: {
28426 const pubSubkeyPacket = PublicSubkeyPacket.fromSecretSubkeyPacket(keyPacket);
28427 packetlist.push(pubSubkeyPacket);
28428 break;
28429 }
28430 default:
28431 packetlist.push(keyPacket);
28432 }
28433 }
28434 return new PublicKey(packetlist);
28435 }
28436
28437 /**
28438 * Returns ASCII armored text of key
28439 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28440 * @returns {ReadableStream<String>} ASCII armor.
28441 */
28442 armor(config = defaultConfig) {
28443 return armor(enums.armor.privateKey, this.toPacketList().write(), undefined, undefined, undefined, config);
28444 }
28445
28446 /**
28447 * Returns all keys that are available for decryption, matching the keyID when given
28448 * This is useful to retrieve keys for session key decryption
28449 * @param {module:type/keyid~KeyID} keyID, optional
28450 * @param {Date} date, optional
28451 * @param {String} userID, optional
28452 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28453 * @returns {Promise<Array<Key|Subkey>>} Array of decryption keys.
28454 * @async
28455 */
28456 async getDecryptionKeys(keyID, date = new Date(), userID = {}, config = defaultConfig) {
28457 const primaryKey = this.keyPacket;
28458 const keys = [];
28459 for (let i = 0; i < this.subkeys.length; i++) {
28460 if (!keyID || this.subkeys[i].getKeyID().equals(keyID, true)) {
28461 try {
28462 const dataToVerify = { key: primaryKey, bind: this.subkeys[i].keyPacket };
28463 const bindingSignature = await getLatestValidSignature(this.subkeys[i].bindingSignatures, primaryKey, enums.signature.subkeyBinding, dataToVerify, date, config);
28464 if (isValidDecryptionKeyPacket(bindingSignature, config)) {
28465 keys.push(this.subkeys[i]);
28466 }
28467 } catch (e) {}
28468 }
28469 }
28470
28471 // evaluate primary key
28472 const primaryUser = await this.getPrimaryUser(date, userID, config);
28473 if ((!keyID || primaryKey.getKeyID().equals(keyID, true)) &&
28474 isValidDecryptionKeyPacket(primaryUser.selfCertification, config)) {
28475 keys.push(this);
28476 }
28477
28478 return keys;
28479 }
28480
28481 /**
28482 * Returns true if the primary key or any subkey is decrypted.
28483 * A dummy key is considered encrypted.
28484 */
28485 isDecrypted() {
28486 return this.getKeys().some(({ keyPacket }) => keyPacket.isDecrypted());
28487 }
28488
28489 /**
28490 * Check whether the private and public primary key parameters correspond
28491 * Together with verification of binding signatures, this guarantees key integrity
28492 * In case of gnu-dummy primary key, it is enough to validate any signing subkeys
28493 * otherwise all encryption subkeys are validated
28494 * If only gnu-dummy keys are found, we cannot properly validate so we throw an error
28495 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28496 * @throws {Error} if validation was not successful and the key cannot be trusted
28497 * @async
28498 */
28499 async validate(config = defaultConfig) {
28500 if (!this.isPrivate()) {
28501 throw new Error('Cannot validate a public key');
28502 }
28503
28504 let signingKeyPacket;
28505 if (!this.keyPacket.isDummy()) {
28506 signingKeyPacket = this.keyPacket;
28507 } else {
28508 /**
28509 * It is enough to validate any signing keys
28510 * since its binding signatures are also checked
28511 */
28512 const signingKey = await this.getSigningKey(null, null, undefined, { ...config, rejectPublicKeyAlgorithms: new Set(), minRSABits: 0 });
28513 // This could again be a dummy key
28514 if (signingKey && !signingKey.keyPacket.isDummy()) {
28515 signingKeyPacket = signingKey.keyPacket;
28516 }
28517 }
28518
28519 if (signingKeyPacket) {
28520 return signingKeyPacket.validate();
28521 } else {
28522 const keys = this.getKeys();
28523 const allDummies = keys.map(key => key.keyPacket.isDummy()).every(Boolean);
28524 if (allDummies) {
28525 throw new Error('Cannot validate an all-gnu-dummy key');
28526 }
28527
28528 return Promise.all(keys.map(async key => key.keyPacket.validate()));
28529 }
28530 }
28531
28532 /**
28533 * Clear private key parameters
28534 */
28535 clearPrivateParams() {
28536 this.getKeys().forEach(({ keyPacket }) => {
28537 if (keyPacket.isDecrypted()) {
28538 keyPacket.clearPrivateParams();
28539 }
28540 });
28541 }
28542
28543 /**
28544 * Revokes the key
28545 * @param {Object} reasonForRevocation - optional, object indicating the reason for revocation
28546 * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
28547 * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation
28548 * @param {Date} date - optional, override the creationtime of the revocation signature
28549 * @param {Object} [config] - Full configuration, defaults to openpgp.config
28550 * @returns {Promise<PrivateKey>} New key with revocation signature.
28551 * @async
28552 */
28553 async revoke(
28554 {
28555 flag: reasonForRevocationFlag = enums.reasonForRevocation.noReason,
28556 string: reasonForRevocationString = ''
28557 } = {},
28558 date = new Date(),
28559 config = defaultConfig
28560 ) {
28561 if (!this.isPrivate()) {
28562 throw new Error('Need private key for revoking');
28563 }
28564 const dataToSign = { key: this.keyPacket };
28565 const key = this.clone();
28566 key.revocationSignatures.push(await createSignaturePacket(dataToSign, null, this.keyPacket, {
28567 signatureType: enums.signature.keyRevocation,
28568 reasonForRevocationFlag: enums.write(enums.reasonForRevocation, reasonForRevocationFlag),
28569 reasonForRevocationString
28570 }, date, undefined, undefined, config));
28571 return key;
28572 }
28573
28574
28575 /**
28576 * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.
28577 * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key. DSA primary keys default to RSA subkeys.
28578 * @param {ecc|rsa} options.type The subkey algorithm: ECC or RSA
28579 * @param {String} options.curve (optional) Elliptic curve for ECC keys
28580 * @param {Integer} options.rsaBits (optional) Number of bits for RSA subkeys
28581 * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires
28582 * @param {Date} options.date (optional) Override the creation date of the key and the key signatures
28583 * @param {Boolean} options.sign (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false
28584 * @param {Object} options.config (optional) custom configuration settings to overwrite those in [config]{@link module:config}
28585 * @returns {Promise<PrivateKey>}
28586 * @async
28587 */
28588 async addSubkey(options = {}) {
28589 const config = { ...defaultConfig, ...options.config };
28590 if (options.passphrase) {
28591 throw new Error('Subkey could not be encrypted here, please encrypt whole key');
28592 }
28593 if (options.rsaBits < config.minRSABits) {
28594 throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${options.rsaBits}`);
28595 }
28596 const secretKeyPacket = this.keyPacket;
28597 if (secretKeyPacket.isDummy()) {
28598 throw new Error('Cannot add subkey to gnu-dummy primary key');
28599 }
28600 if (!secretKeyPacket.isDecrypted()) {
28601 throw new Error('Key is not decrypted');
28602 }
28603 const defaultOptions = secretKeyPacket.getAlgorithmInfo();
28604 defaultOptions.type = defaultOptions.curve ? 'ecc' : 'rsa'; // DSA keys default to RSA
28605 defaultOptions.rsaBits = defaultOptions.bits || 4096;
28606 defaultOptions.curve = defaultOptions.curve || 'curve25519';
28607 options = sanitizeKeyOptions(options, defaultOptions);
28608 const keyPacket = await generateSecretSubkey(options);
28609 const bindingSignature = await createBindingSignature(keyPacket, secretKeyPacket, options, config);
28610 const packetList = this.toPacketList();
28611 packetList.push(keyPacket, bindingSignature);
28612 return new PrivateKey(packetList);
28613 }
28614 }
28615
28616 // OpenPGP.js - An OpenPGP implementation in javascript
28617
28618 // A Key can contain the following packets
28619 const allowedKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([
28620 PublicKeyPacket,
28621 PublicSubkeyPacket,
28622 SecretKeyPacket,
28623 SecretSubkeyPacket,
28624 UserIDPacket,
28625 UserAttributePacket,
28626 SignaturePacket
28627 ]);
28628
28629 /**
28630 * Generates a new OpenPGP key. Supports RSA and ECC keys.
28631 * By default, primary and subkeys will be of same type.
28632 * @param {ecc|rsa} options.type The primary key algorithm type: ECC or RSA
28633 * @param {String} options.curve Elliptic curve for ECC keys
28634 * @param {Integer} options.rsaBits Number of bits for RSA keys
28635 * @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' }
28636 * @param {String} options.passphrase Passphrase used to encrypt the resulting private key
28637 * @param {Number} options.keyExpirationTime (optional) Number of seconds from the key creation time after which the key expires
28638 * @param {Date} options.date Creation date of the key and the key signatures
28639 * @param {Object} config - Full configuration
28640 * @param {Array<Object>} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
28641 * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt
28642 * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}
28643 * @async
28644 * @static
28645 * @private
28646 */
28647 async function generate$2(options, config) {
28648 options.sign = true; // primary key is always a signing key
28649 options = sanitizeKeyOptions(options);
28650 options.subkeys = options.subkeys.map((subkey, index) => sanitizeKeyOptions(options.subkeys[index], options));
28651 let promises = [generateSecretKey(options, config)];
28652 promises = promises.concat(options.subkeys.map(options => generateSecretSubkey(options, config)));
28653 const packets = await Promise.all(promises);
28654
28655 const key = await wrapKeyObject(packets[0], packets.slice(1), options, config);
28656 const revocationCertificate = await key.getRevocationCertificate(options.date, config);
28657 key.revocationSignatures = [];
28658 return { key, revocationCertificate };
28659 }
28660
28661 /**
28662 * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.
28663 * @param {PrivateKey} options.privateKey The private key to reformat
28664 * @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' }
28665 * @param {String} options.passphrase Passphrase used to encrypt the resulting private key
28666 * @param {Number} options.keyExpirationTime Number of seconds from the key creation time after which the key expires
28667 * @param {Date} options.date Override the creation date of the key signatures
28668 * @param {Array<Object>} options.subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
28669 * @param {Object} config - Full configuration
28670 *
28671 * @returns {Promise<{{ key: PrivateKey, revocationCertificate: String }}>}
28672 * @async
28673 * @static
28674 * @private
28675 */
28676 async function reformat(options, config) {
28677 options = sanitize(options);
28678 const { privateKey } = options;
28679
28680 if (!privateKey.isPrivate()) {
28681 throw new Error('Cannot reformat a public key');
28682 }
28683
28684 if (privateKey.keyPacket.isDummy()) {
28685 throw new Error('Cannot reformat a gnu-dummy primary key');
28686 }
28687
28688 const isDecrypted = privateKey.getKeys().every(({ keyPacket }) => keyPacket.isDecrypted());
28689 if (!isDecrypted) {
28690 throw new Error('Key is not decrypted');
28691 }
28692
28693 const secretKeyPacket = privateKey.keyPacket;
28694
28695 if (!options.subkeys) {
28696 options.subkeys = await Promise.all(privateKey.subkeys.map(async subkey => {
28697 const secretSubkeyPacket = subkey.keyPacket;
28698 const dataToVerify = { key: secretKeyPacket, bind: secretSubkeyPacket };
28699 const bindingSignature = await (
28700 getLatestValidSignature(subkey.bindingSignatures, secretKeyPacket, enums.signature.subkeyBinding, dataToVerify, null, config)
28701 ).catch(() => ({}));
28702 return {
28703 sign: bindingSignature.keyFlags && (bindingSignature.keyFlags[0] & enums.keyFlags.signData)
28704 };
28705 }));
28706 }
28707
28708 const secretSubkeyPackets = privateKey.subkeys.map(subkey => subkey.keyPacket);
28709 if (options.subkeys.length !== secretSubkeyPackets.length) {
28710 throw new Error('Number of subkey options does not match number of subkeys');
28711 }
28712
28713 options.subkeys = options.subkeys.map(subkeyOptions => sanitize(subkeyOptions, options));
28714
28715 const key = await wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config);
28716 const revocationCertificate = await key.getRevocationCertificate(options.date, config);
28717 key.revocationSignatures = [];
28718 return { key, revocationCertificate };
28719
28720 function sanitize(options, subkeyDefaults = {}) {
28721 options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;
28722 options.passphrase = util.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
28723 options.date = options.date || subkeyDefaults.date;
28724
28725 return options;
28726 }
28727 }
28728
28729 /**
28730 * Construct PrivateKey object from the given key packets, add certification signatures and set passphrase protection
28731 * The new key includes a revocation certificate that must be removed before returning the key, otherwise the key is considered revoked.
28732 * @param {SecretKeyPacket} secretKeyPacket
28733 * @param {SecretSubkeyPacket} secretSubkeyPackets
28734 * @param {Object} options
28735 * @param {Object} config - Full configuration
28736 * @returns {PrivateKey}
28737 */
28738 async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options, config) {
28739 // set passphrase protection
28740 if (options.passphrase) {
28741 await secretKeyPacket.encrypt(options.passphrase, config);
28742 }
28743
28744 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
28745 const subkeyPassphrase = options.subkeys[index].passphrase;
28746 if (subkeyPassphrase) {
28747 await secretSubkeyPacket.encrypt(subkeyPassphrase, config);
28748 }
28749 }));
28750
28751 const packetlist = new PacketList();
28752 packetlist.push(secretKeyPacket);
28753
28754 await Promise.all(options.userIDs.map(async function(userID, index) {
28755 function createPreferredAlgos(algos, preferredAlgo) {
28756 return [preferredAlgo, ...algos.filter(algo => algo !== preferredAlgo)];
28757 }
28758
28759 const userIDPacket = UserIDPacket.fromObject(userID);
28760 const dataToSign = {};
28761 dataToSign.userID = userIDPacket;
28762 dataToSign.key = secretKeyPacket;
28763 const signaturePacket = new SignaturePacket();
28764 signaturePacket.signatureType = enums.signature.certGeneric;
28765 signaturePacket.publicKeyAlgorithm = secretKeyPacket.algorithm;
28766 signaturePacket.hashAlgorithm = await getPreferredHashAlgo$1(null, secretKeyPacket, undefined, undefined, config);
28767 signaturePacket.keyFlags = [enums.keyFlags.certifyKeys | enums.keyFlags.signData];
28768 signaturePacket.preferredSymmetricAlgorithms = createPreferredAlgos([
28769 // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support)
28770 enums.symmetric.aes256,
28771 enums.symmetric.aes128,
28772 enums.symmetric.aes192
28773 ], config.preferredSymmetricAlgorithm);
28774 if (config.aeadProtect) {
28775 signaturePacket.preferredAEADAlgorithms = createPreferredAlgos([
28776 enums.aead.eax,
28777 enums.aead.ocb
28778 ], config.preferredAEADAlgorithm);
28779 }
28780 signaturePacket.preferredHashAlgorithms = createPreferredAlgos([
28781 // prefer fast asm.js implementations (SHA-256)
28782 enums.hash.sha256,
28783 enums.hash.sha512
28784 ], config.preferredHashAlgorithm);
28785 signaturePacket.preferredCompressionAlgorithms = createPreferredAlgos([
28786 enums.compression.zlib,
28787 enums.compression.zip,
28788 enums.compression.uncompressed
28789 ], config.preferredCompressionAlgorithm);
28790 if (index === 0) {
28791 signaturePacket.isPrimaryUserID = true;
28792 }
28793 // integrity protection always enabled
28794 signaturePacket.features = [0];
28795 signaturePacket.features[0] |= enums.features.modificationDetection;
28796 if (config.aeadProtect) {
28797 signaturePacket.features[0] |= enums.features.aead;
28798 }
28799 if (config.v5Keys) {
28800 signaturePacket.features[0] |= enums.features.v5Keys;
28801 }
28802 if (options.keyExpirationTime > 0) {
28803 signaturePacket.keyExpirationTime = options.keyExpirationTime;
28804 signaturePacket.keyNeverExpires = false;
28805 }
28806 await signaturePacket.sign(secretKeyPacket, dataToSign, options.date);
28807
28808 return { userIDPacket, signaturePacket };
28809 })).then(list => {
28810 list.forEach(({ userIDPacket, signaturePacket }) => {
28811 packetlist.push(userIDPacket);
28812 packetlist.push(signaturePacket);
28813 });
28814 });
28815
28816 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
28817 const subkeyOptions = options.subkeys[index];
28818 const subkeySignaturePacket = await createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions, config);
28819 return { secretSubkeyPacket, subkeySignaturePacket };
28820 })).then(packets => {
28821 packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {
28822 packetlist.push(secretSubkeyPacket);
28823 packetlist.push(subkeySignaturePacket);
28824 });
28825 });
28826
28827 // Add revocation signature packet for creating a revocation certificate.
28828 // This packet should be removed before returning the key.
28829 const dataToSign = { key: secretKeyPacket };
28830 packetlist.push(await createSignaturePacket(dataToSign, null, secretKeyPacket, {
28831 signatureType: enums.signature.keyRevocation,
28832 reasonForRevocationFlag: enums.reasonForRevocation.noReason,
28833 reasonForRevocationString: ''
28834 }, options.date, undefined, undefined, config));
28835
28836 if (options.passphrase) {
28837 secretKeyPacket.clearPrivateParams();
28838 }
28839
28840 await Promise.all(secretSubkeyPackets.map(async function(secretSubkeyPacket, index) {
28841 const subkeyPassphrase = options.subkeys[index].passphrase;
28842 if (subkeyPassphrase) {
28843 secretSubkeyPacket.clearPrivateParams();
28844 }
28845 }));
28846
28847 return new PrivateKey(packetlist);
28848 }
28849
28850 /**
28851 * Reads an (optionally armored) OpenPGP key and returns a key object
28852 * @param {Object} options
28853 * @param {String} [options.armoredKey] - Armored key to be parsed
28854 * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed
28855 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
28856 * @returns {Promise<Key>} Key object.
28857 * @async
28858 * @static
28859 */
28860 async function readKey({ armoredKey, binaryKey, config, ...rest }) {
28861 config = { ...defaultConfig, ...config };
28862 if (!armoredKey && !binaryKey) {
28863 throw new Error('readKey: must pass options object containing `armoredKey` or `binaryKey`');
28864 }
28865 if (armoredKey && !util.isString(armoredKey)) {
28866 throw new Error('readKey: options.armoredKey must be a string');
28867 }
28868 if (binaryKey && !util.isUint8Array(binaryKey)) {
28869 throw new Error('readKey: options.binaryKey must be a Uint8Array');
28870 }
28871 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
28872
28873 let input;
28874 if (armoredKey) {
28875 const { type, data } = await unarmor(armoredKey, config);
28876 if (!(type === enums.armor.publicKey || type === enums.armor.privateKey)) {
28877 throw new Error('Armored text not of type key');
28878 }
28879 input = data;
28880 } else {
28881 input = binaryKey;
28882 }
28883 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);
28884 return createKey(packetlist);
28885 }
28886
28887 /**
28888 * Reads an (optionally armored) OpenPGP private key and returns a PrivateKey object
28889 * @param {Object} options
28890 * @param {String} [options.armoredKey] - Armored key to be parsed
28891 * @param {Uint8Array} [options.binaryKey] - Binary key to be parsed
28892 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
28893 * @returns {Promise<PrivateKey>} Key object.
28894 * @async
28895 * @static
28896 */
28897 async function readPrivateKey({ armoredKey, binaryKey, config, ...rest }) {
28898 config = { ...defaultConfig, ...config };
28899 if (!armoredKey && !binaryKey) {
28900 throw new Error('readPrivateKey: must pass options object containing `armoredKey` or `binaryKey`');
28901 }
28902 if (armoredKey && !util.isString(armoredKey)) {
28903 throw new Error('readPrivateKey: options.armoredKey must be a string');
28904 }
28905 if (binaryKey && !util.isUint8Array(binaryKey)) {
28906 throw new Error('readPrivateKey: options.binaryKey must be a Uint8Array');
28907 }
28908 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
28909
28910 let input;
28911 if (armoredKey) {
28912 const { type, data } = await unarmor(armoredKey, config);
28913 if (!(type === enums.armor.privateKey)) {
28914 throw new Error('Armored text not of type private key');
28915 }
28916 input = data;
28917 } else {
28918 input = binaryKey;
28919 }
28920 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);
28921 return new PrivateKey(packetlist);
28922 }
28923
28924 /**
28925 * Reads an (optionally armored) OpenPGP key block and returns a list of key objects
28926 * @param {Object} options
28927 * @param {String} [options.armoredKeys] - Armored keys to be parsed
28928 * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed
28929 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
28930 * @returns {Promise<Array<Key>>} Key objects.
28931 * @async
28932 * @static
28933 */
28934 async function readKeys({ armoredKeys, binaryKeys, config, ...rest }) {
28935 config = { ...defaultConfig, ...config };
28936 let input = armoredKeys || binaryKeys;
28937 if (!input) {
28938 throw new Error('readKeys: must pass options object containing `armoredKeys` or `binaryKeys`');
28939 }
28940 if (armoredKeys && !util.isString(armoredKeys)) {
28941 throw new Error('readKeys: options.armoredKeys must be a string');
28942 }
28943 if (binaryKeys && !util.isUint8Array(binaryKeys)) {
28944 throw new Error('readKeys: options.binaryKeys must be a Uint8Array');
28945 }
28946 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
28947
28948 if (armoredKeys) {
28949 const { type, data } = await unarmor(armoredKeys, config);
28950 if (type !== enums.armor.publicKey && type !== enums.armor.privateKey) {
28951 throw new Error('Armored text not of type key');
28952 }
28953 input = data;
28954 }
28955 const keys = [];
28956 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);
28957 const keyIndex = packetlist.indexOfTag(enums.packet.publicKey, enums.packet.secretKey);
28958 if (keyIndex.length === 0) {
28959 throw new Error('No key packet found');
28960 }
28961 for (let i = 0; i < keyIndex.length; i++) {
28962 const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);
28963 const newKey = createKey(oneKeyList);
28964 keys.push(newKey);
28965 }
28966 return keys;
28967 }
28968
28969 /**
28970 * Reads an (optionally armored) OpenPGP private key block and returns a list of PrivateKey objects
28971 * @param {Object} options
28972 * @param {String} [options.armoredKeys] - Armored keys to be parsed
28973 * @param {Uint8Array} [options.binaryKeys] - Binary keys to be parsed
28974 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
28975 * @returns {Promise<Array<PrivateKey>>} Key objects.
28976 * @async
28977 * @static
28978 */
28979 async function readPrivateKeys({ armoredKeys, binaryKeys, config }) {
28980 config = { ...defaultConfig, ...config };
28981 let input = armoredKeys || binaryKeys;
28982 if (!input) {
28983 throw new Error('readPrivateKeys: must pass options object containing `armoredKeys` or `binaryKeys`');
28984 }
28985 if (armoredKeys && !util.isString(armoredKeys)) {
28986 throw new Error('readPrivateKeys: options.armoredKeys must be a string');
28987 }
28988 if (binaryKeys && !util.isUint8Array(binaryKeys)) {
28989 throw new Error('readPrivateKeys: options.binaryKeys must be a Uint8Array');
28990 }
28991 if (armoredKeys) {
28992 const { type, data } = await unarmor(armoredKeys, config);
28993 if (type !== enums.armor.privateKey) {
28994 throw new Error('Armored text not of type private key');
28995 }
28996 input = data;
28997 }
28998 const keys = [];
28999 const packetlist = await PacketList.fromBinary(input, allowedKeyPackets, config);
29000 const keyIndex = packetlist.indexOfTag(enums.packet.secretKey);
29001 if (keyIndex.length === 0) {
29002 throw new Error('No secret key packet found');
29003 }
29004 for (let i = 0; i < keyIndex.length; i++) {
29005 const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);
29006 const newKey = new PrivateKey(oneKeyList);
29007 keys.push(newKey);
29008 }
29009 return keys;
29010 }
29011
29012 // GPG4Browsers - An OpenPGP implementation in javascript
29013
29014 // A Message can contain the following packets
29015 const allowedMessagePackets = /*#__PURE__*/ util.constructAllowedPackets([
29016 LiteralDataPacket,
29017 CompressedDataPacket,
29018 AEADEncryptedDataPacket,
29019 SymEncryptedIntegrityProtectedDataPacket,
29020 SymmetricallyEncryptedDataPacket,
29021 PublicKeyEncryptedSessionKeyPacket,
29022 SymEncryptedSessionKeyPacket,
29023 OnePassSignaturePacket,
29024 SignaturePacket
29025 ]);
29026 // A SKESK packet can contain the following packets
29027 const allowedSymSessionKeyPackets = /*#__PURE__*/ util.constructAllowedPackets([SymEncryptedSessionKeyPacket]);
29028 // A detached signature can contain the following packets
29029 const allowedDetachedSignaturePackets = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
29030
29031 /**
29032 * Class that represents an OpenPGP message.
29033 * Can be an encrypted message, signed message, compressed message or literal message
29034 * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}
29035 */
29036 class Message {
29037 /**
29038 * @param {PacketList} packetlist - The packets that form this message
29039 */
29040 constructor(packetlist) {
29041 this.packets = packetlist || new PacketList();
29042 }
29043
29044 /**
29045 * Returns the key IDs of the keys to which the session key is encrypted
29046 * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
29047 */
29048 getEncryptionKeyIDs() {
29049 const keyIDs = [];
29050 const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
29051 pkESKeyPacketlist.forEach(function(packet) {
29052 keyIDs.push(packet.publicKeyID);
29053 });
29054 return keyIDs;
29055 }
29056
29057 /**
29058 * Returns the key IDs of the keys that signed the message
29059 * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
29060 */
29061 getSigningKeyIDs() {
29062 const msg = this.unwrapCompressed();
29063 // search for one pass signatures
29064 const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature);
29065 if (onePassSigList.length > 0) {
29066 return onePassSigList.map(packet => packet.issuerKeyID);
29067 }
29068 // if nothing found look for signature packets
29069 const signatureList = msg.packets.filterByTag(enums.packet.signature);
29070 return signatureList.map(packet => packet.issuerKeyID);
29071 }
29072
29073 /**
29074 * Decrypt the message. Either a private key, a session key, or a password must be specified.
29075 * @param {Array<PrivateKey>} [decryptionKeys] - Private keys with decrypted secret data
29076 * @param {Array<String>} [passwords] - Passwords used to decrypt
29077 * @param {Array<Object>} [sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
29078 * @param {Date} [date] - Use the given date for key verification instead of the current time
29079 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29080 * @returns {Promise<Message>} New message with decrypted content.
29081 * @async
29082 */
29083 async decrypt(decryptionKeys, passwords, sessionKeys, date = new Date(), config = defaultConfig) {
29084 const keyObjs = sessionKeys || await this.decryptSessionKeys(decryptionKeys, passwords, date, config);
29085
29086 const symEncryptedPacketlist = this.packets.filterByTag(
29087 enums.packet.symmetricallyEncryptedData,
29088 enums.packet.symEncryptedIntegrityProtectedData,
29089 enums.packet.aeadEncryptedData
29090 );
29091
29092 if (symEncryptedPacketlist.length === 0) {
29093 return this;
29094 }
29095
29096 const symEncryptedPacket = symEncryptedPacketlist[0];
29097 let exception = null;
29098 const decryptedPromise = Promise.all(keyObjs.map(async keyObj => {
29099 if (!keyObj || !util.isUint8Array(keyObj.data) || !util.isString(keyObj.algorithm)) {
29100 throw new Error('Invalid session key for decryption.');
29101 }
29102
29103 try {
29104 await symEncryptedPacket.decrypt(keyObj.algorithm, keyObj.data, config);
29105 } catch (e) {
29106 util.printDebugError(e);
29107 exception = e;
29108 }
29109 }));
29110 // We don't await stream.cancel here because it only returns when the other copy is canceled too.
29111 cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.
29112 symEncryptedPacket.encrypted = null;
29113 await decryptedPromise;
29114
29115 if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {
29116 throw exception || new Error('Decryption failed.');
29117 }
29118
29119 const resultMsg = new Message(symEncryptedPacket.packets);
29120 symEncryptedPacket.packets = new PacketList(); // remove packets after decryption
29121
29122 return resultMsg;
29123 }
29124
29125 /**
29126 * Decrypt encrypted session keys either with private keys or passwords.
29127 * @param {Array<PrivateKey>} [decryptionKeys] - Private keys with decrypted secret data
29128 * @param {Array<String>} [passwords] - Passwords used to decrypt
29129 * @param {Date} [date] - Use the given date for key verification, instead of current time
29130 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29131 * @returns {Promise<Array<{
29132 * data: Uint8Array,
29133 * algorithm: String
29134 * }>>} array of object with potential sessionKey, algorithm pairs
29135 * @async
29136 */
29137 async decryptSessionKeys(decryptionKeys, passwords, date = new Date(), config = defaultConfig) {
29138 let keyPackets = [];
29139
29140 let exception;
29141 if (passwords) {
29142 const symESKeyPacketlist = this.packets.filterByTag(enums.packet.symEncryptedSessionKey);
29143 if (symESKeyPacketlist.length === 0) {
29144 throw new Error('No symmetrically encrypted session key packet found.');
29145 }
29146 await Promise.all(passwords.map(async function(password, i) {
29147 let packets;
29148 if (i) {
29149 packets = await PacketList.fromBinary(symESKeyPacketlist.write(), allowedSymSessionKeyPackets, config);
29150 } else {
29151 packets = symESKeyPacketlist;
29152 }
29153 await Promise.all(packets.map(async function(keyPacket) {
29154 try {
29155 await keyPacket.decrypt(password);
29156 keyPackets.push(keyPacket);
29157 } catch (err) {
29158 util.printDebugError(err);
29159 }
29160 }));
29161 }));
29162 } else if (decryptionKeys) {
29163 const pkESKeyPacketlist = this.packets.filterByTag(enums.packet.publicKeyEncryptedSessionKey);
29164 if (pkESKeyPacketlist.length === 0) {
29165 throw new Error('No public key encrypted session key packet found.');
29166 }
29167 await Promise.all(pkESKeyPacketlist.map(async function(keyPacket) {
29168 await Promise.all(decryptionKeys.map(async function(decryptionKey) {
29169 let algos = [
29170 enums.symmetric.aes256, // Old OpenPGP.js default fallback
29171 enums.symmetric.aes128, // RFC4880bis fallback
29172 enums.symmetric.tripledes, // RFC4880 fallback
29173 enums.symmetric.cast5 // Golang OpenPGP fallback
29174 ];
29175 try {
29176 const primaryUser = await decryptionKey.getPrimaryUser(date, undefined, config); // TODO: Pass userID from somewhere.
29177 if (primaryUser.selfCertification.preferredSymmetricAlgorithms) {
29178 algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms);
29179 }
29180 } catch (e) {}
29181
29182 // do not check key expiration to allow decryption of old messages
29183 const decryptionKeyPackets = (await decryptionKey.getDecryptionKeys(keyPacket.publicKeyID, null, undefined, config)).map(key => key.keyPacket);
29184 await Promise.all(decryptionKeyPackets.map(async function(decryptionKeyPacket) {
29185 if (!decryptionKeyPacket || decryptionKeyPacket.isDummy()) {
29186 return;
29187 }
29188 if (!decryptionKeyPacket.isDecrypted()) {
29189 throw new Error('Decryption key is not decrypted.');
29190 }
29191 try {
29192 await keyPacket.decrypt(decryptionKeyPacket);
29193 if (!algos.includes(enums.write(enums.symmetric, keyPacket.sessionKeyAlgorithm))) {
29194 throw new Error('A non-preferred symmetric algorithm was used.');
29195 }
29196 keyPackets.push(keyPacket);
29197 } catch (err) {
29198 util.printDebugError(err);
29199 exception = err;
29200 }
29201 }));
29202 }));
29203 cancel(keyPacket.encrypted); // Don't keep copy of encrypted data in memory.
29204 keyPacket.encrypted = null;
29205 }));
29206 } else {
29207 throw new Error('No key or password specified.');
29208 }
29209
29210 if (keyPackets.length) {
29211 // Return only unique session keys
29212 if (keyPackets.length > 1) {
29213 const seen = new Set();
29214 keyPackets = keyPackets.filter(item => {
29215 const k = item.sessionKeyAlgorithm + util.uint8ArrayToString(item.sessionKey);
29216 if (seen.has(k)) {
29217 return false;
29218 }
29219 seen.add(k);
29220 return true;
29221 });
29222 }
29223
29224 return keyPackets.map(packet => ({ data: packet.sessionKey, algorithm: packet.sessionKeyAlgorithm }));
29225 }
29226 throw exception || new Error('Session key decryption failed.');
29227 }
29228
29229 /**
29230 * Get literal data that is the body of the message
29231 * @returns {(Uint8Array|null)} Literal body of the message as Uint8Array.
29232 */
29233 getLiteralData() {
29234 const msg = this.unwrapCompressed();
29235 const literal = msg.packets.findPacket(enums.packet.literalData);
29236 return (literal && literal.getBytes()) || null;
29237 }
29238
29239 /**
29240 * Get filename from literal data packet
29241 * @returns {(String|null)} Filename of literal data packet as string.
29242 */
29243 getFilename() {
29244 const msg = this.unwrapCompressed();
29245 const literal = msg.packets.findPacket(enums.packet.literalData);
29246 return (literal && literal.getFilename()) || null;
29247 }
29248
29249 /**
29250 * Get literal data as text
29251 * @returns {(String|null)} Literal body of the message interpreted as text.
29252 */
29253 getText() {
29254 const msg = this.unwrapCompressed();
29255 const literal = msg.packets.findPacket(enums.packet.literalData);
29256 if (literal) {
29257 return literal.getText();
29258 }
29259 return null;
29260 }
29261
29262 /**
29263 * Generate a new session key object, taking the algorithm preferences of the passed encryption keys into account, if any.
29264 * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) to select algorithm preferences for
29265 * @param {Date} [date] - Date to select algorithm preferences at
29266 * @param {Array<Object>} [userIDs] - User IDs to select algorithm preferences for
29267 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29268 * @returns {Promise<{ data: Uint8Array, algorithm: String, aeadAlgorithm: undefined|String }>} Object with session key data and algorithms.
29269 * @async
29270 */
29271 static async generateSessionKey(encryptionKeys = [], date = new Date(), userIDs = [], config = defaultConfig) {
29272 const algorithm = enums.read(enums.symmetric, await getPreferredAlgo('symmetric', encryptionKeys, date, userIDs, config));
29273 const aeadAlgorithm = config.aeadProtect && await isAEADSupported(encryptionKeys, date, userIDs, config) ?
29274 enums.read(enums.aead, await getPreferredAlgo('aead', encryptionKeys, date, userIDs, config)) :
29275 undefined;
29276
29277 const sessionKeyData = await mod.generateSessionKey(algorithm);
29278 return { data: sessionKeyData, algorithm, aeadAlgorithm };
29279 }
29280
29281 /**
29282 * Encrypt the message either with public keys, passwords, or both at once.
29283 * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) for message encryption
29284 * @param {Array<String>} [passwords] - Password(s) for message encryption
29285 * @param {Object} [sessionKey] - Session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
29286 * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs
29287 * @param {Array<module:type/keyid~KeyID>} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to keys[i]
29288 * @param {Date} [date] - Override the creation date of the literal package
29289 * @param {Array<Object>} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
29290 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29291 * @returns {Promise<Message>} New message with encrypted content.
29292 * @async
29293 */
29294 async encrypt(encryptionKeys, passwords, sessionKey, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
29295 if (sessionKey) {
29296 if (!util.isUint8Array(sessionKey.data) || !util.isString(sessionKey.algorithm)) {
29297 throw new Error('Invalid session key for encryption.');
29298 }
29299 } else if (encryptionKeys && encryptionKeys.length) {
29300 sessionKey = await Message.generateSessionKey(encryptionKeys, date, userIDs, config);
29301 } else if (passwords && passwords.length) {
29302 sessionKey = await Message.generateSessionKey(undefined, undefined, undefined, config);
29303 } else {
29304 throw new Error('No keys, passwords, or session key provided.');
29305 }
29306
29307 const { data: sessionKeyData, algorithm, aeadAlgorithm } = sessionKey;
29308
29309 const msg = await Message.encryptSessionKey(sessionKeyData, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, userIDs, config);
29310
29311 let symEncryptedPacket;
29312 if (aeadAlgorithm) {
29313 symEncryptedPacket = new AEADEncryptedDataPacket();
29314 symEncryptedPacket.aeadAlgorithm = aeadAlgorithm;
29315 } else {
29316 symEncryptedPacket = new SymEncryptedIntegrityProtectedDataPacket();
29317 }
29318 symEncryptedPacket.packets = this.packets;
29319
29320 await symEncryptedPacket.encrypt(algorithm, sessionKeyData, config);
29321
29322 msg.packets.push(symEncryptedPacket);
29323 symEncryptedPacket.packets = new PacketList(); // remove packets after encryption
29324 return msg;
29325 }
29326
29327 /**
29328 * Encrypt a session key either with public keys, passwords, or both at once.
29329 * @param {Uint8Array} sessionKey - session key for encryption
29330 * @param {String} algorithm - session key algorithm
29331 * @param {String} [aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'
29332 * @param {Array<PublicKey>} [encryptionKeys] - Public key(s) for message encryption
29333 * @param {Array<String>} [passwords] - For message encryption
29334 * @param {Boolean} [wildcard] - Use a key ID of 0 instead of the public key IDs
29335 * @param {Array<module:type/keyid~KeyID>} [encryptionKeyIDs] - Array of key IDs to use for encryption. Each encryptionKeyIDs[i] corresponds to encryptionKeys[i]
29336 * @param {Date} [date] - Override the date
29337 * @param {Array} [userIDs] - User IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
29338 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29339 * @returns {Promise<Message>} New message with encrypted content.
29340 * @async
29341 */
29342 static async encryptSessionKey(sessionKey, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard = false, encryptionKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
29343 const packetlist = new PacketList();
29344
29345 if (encryptionKeys) {
29346 const results = await Promise.all(encryptionKeys.map(async function(primaryKey, i) {
29347 const encryptionKey = await primaryKey.getEncryptionKey(encryptionKeyIDs[i], date, userIDs, config);
29348 const pkESKeyPacket = new PublicKeyEncryptedSessionKeyPacket();
29349 pkESKeyPacket.publicKeyID = wildcard ? KeyID.wildcard() : encryptionKey.getKeyID();
29350 pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm;
29351 pkESKeyPacket.sessionKey = sessionKey;
29352 pkESKeyPacket.sessionKeyAlgorithm = algorithm;
29353 await pkESKeyPacket.encrypt(encryptionKey.keyPacket);
29354 delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption
29355 return pkESKeyPacket;
29356 }));
29357 packetlist.push(...results);
29358 }
29359 if (passwords) {
29360 const testDecrypt = async function(keyPacket, password) {
29361 try {
29362 await keyPacket.decrypt(password);
29363 return 1;
29364 } catch (e) {
29365 return 0;
29366 }
29367 };
29368
29369 const sum = (accumulator, currentValue) => accumulator + currentValue;
29370
29371 const encryptPassword = async function(sessionKey, algorithm, aeadAlgorithm, password) {
29372 const symEncryptedSessionKeyPacket = new SymEncryptedSessionKeyPacket(config);
29373 symEncryptedSessionKeyPacket.sessionKey = sessionKey;
29374 symEncryptedSessionKeyPacket.sessionKeyAlgorithm = algorithm;
29375 if (aeadAlgorithm) {
29376 symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgorithm;
29377 }
29378 await symEncryptedSessionKeyPacket.encrypt(password, config);
29379
29380 if (config.passwordCollisionCheck) {
29381 const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));
29382 if (results.reduce(sum) !== 1) {
29383 return encryptPassword(sessionKey, algorithm, password);
29384 }
29385 }
29386
29387 delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption
29388 return symEncryptedSessionKeyPacket;
29389 };
29390
29391 const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, algorithm, aeadAlgorithm, pwd)));
29392 packetlist.push(...results);
29393 }
29394
29395 return new Message(packetlist);
29396 }
29397
29398 /**
29399 * Sign the message (the literal data packet of the message)
29400 * @param {Array<PrivateKey>} signingKeys - private keys with decrypted secret key data for signing
29401 * @param {Signature} [signature] - Any existing detached signature to add to the message
29402 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
29403 * @param {Date} [date] - Override the creation time of the signature
29404 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
29405 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29406 * @returns {Promise<Message>} New message with signed content.
29407 * @async
29408 */
29409 async sign(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
29410 const packetlist = new PacketList();
29411
29412 const literalDataPacket = this.packets.findPacket(enums.packet.literalData);
29413 if (!literalDataPacket) {
29414 throw new Error('No literal data packet to sign.');
29415 }
29416
29417 let i;
29418 let existingSigPacketlist;
29419 // If data packet was created from Uint8Array, use binary, otherwise use text
29420 const signatureType = literalDataPacket.text === null ?
29421 enums.signature.binary : enums.signature.text;
29422
29423 if (signature) {
29424 existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);
29425 for (i = existingSigPacketlist.length - 1; i >= 0; i--) {
29426 const signaturePacket = existingSigPacketlist[i];
29427 const onePassSig = new OnePassSignaturePacket();
29428 onePassSig.signatureType = signaturePacket.signatureType;
29429 onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;
29430 onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;
29431 onePassSig.issuerKeyID = signaturePacket.issuerKeyID;
29432 if (!signingKeys.length && i === 0) {
29433 onePassSig.flags = 1;
29434 }
29435 packetlist.push(onePassSig);
29436 }
29437 }
29438
29439 await Promise.all(Array.from(signingKeys).reverse().map(async function (primaryKey, i) {
29440 if (!primaryKey.isPrivate()) {
29441 throw new Error('Need private key for signing');
29442 }
29443 const signingKeyID = signingKeyIDs[signingKeys.length - 1 - i];
29444 const signingKey = await primaryKey.getSigningKey(signingKeyID, date, userIDs, config);
29445 const onePassSig = new OnePassSignaturePacket();
29446 onePassSig.signatureType = signatureType;
29447 onePassSig.hashAlgorithm = await getPreferredHashAlgo$1(primaryKey, signingKey.keyPacket, date, userIDs, config);
29448 onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm;
29449 onePassSig.issuerKeyID = signingKey.getKeyID();
29450 if (i === signingKeys.length - 1) {
29451 onePassSig.flags = 1;
29452 }
29453 return onePassSig;
29454 })).then(onePassSignatureList => {
29455 onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig));
29456 });
29457
29458 packetlist.push(literalDataPacket);
29459 packetlist.push(...(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, false, config)));
29460
29461 return new Message(packetlist);
29462 }
29463
29464 /**
29465 * Compresses the message (the literal and -if signed- signature data packets of the message)
29466 * @param {module:enums.compression} algo - compression algorithm
29467 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29468 * @returns {Message} New message with compressed content.
29469 */
29470 compress(algo, config = defaultConfig) {
29471 if (algo === enums.compression.uncompressed) {
29472 return this;
29473 }
29474
29475 const compressed = new CompressedDataPacket(config);
29476 compressed.algorithm = enums.read(enums.compression, algo);
29477 compressed.packets = this.packets;
29478
29479 const packetList = new PacketList();
29480 packetList.push(compressed);
29481
29482 return new Message(packetList);
29483 }
29484
29485 /**
29486 * Create a detached signature for the message (the literal data packet of the message)
29487 * @param {Array<PrivateKey>} signingKeys - private keys with decrypted secret key data for signing
29488 * @param {Signature} [signature] - Any existing detached signature
29489 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
29490 * @param {Date} [date] - Override the creation time of the signature
29491 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
29492 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29493 * @returns {Promise<Signature>} New detached signature of message content.
29494 * @async
29495 */
29496 async signDetached(signingKeys = [], signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
29497 const literalDataPacket = this.packets.findPacket(enums.packet.literalData);
29498 if (!literalDataPacket) {
29499 throw new Error('No literal data packet to sign.');
29500 }
29501 return new Signature(await createSignaturePackets(literalDataPacket, signingKeys, signature, signingKeyIDs, date, userIDs, true, config));
29502 }
29503
29504 /**
29505 * Verify message signatures
29506 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
29507 * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
29508 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29509 * @returns {Promise<Array<{
29510 * keyID: module:type/keyid~KeyID,
29511 * signature: Promise<Signature>,
29512 * verified: Promise<true>
29513 * }>>} List of signer's keyID and validity of signatures.
29514 * @async
29515 */
29516 async verify(verificationKeys, date = new Date(), config = defaultConfig) {
29517 const msg = this.unwrapCompressed();
29518 const literalDataList = msg.packets.filterByTag(enums.packet.literalData);
29519 if (literalDataList.length !== 1) {
29520 throw new Error('Can only verify message with one literal data packet.');
29521 }
29522 if (isArrayStream(msg.packets.stream)) {
29523 msg.packets.push(...await readToEnd(msg.packets.stream, _ => _ || []));
29524 }
29525 const onePassSigList = msg.packets.filterByTag(enums.packet.onePassSignature).reverse();
29526 const signatureList = msg.packets.filterByTag(enums.packet.signature);
29527 if (onePassSigList.length && !signatureList.length && util.isStream(msg.packets.stream) && !isArrayStream(msg.packets.stream)) {
29528 await Promise.all(onePassSigList.map(async onePassSig => {
29529 onePassSig.correspondingSig = new Promise((resolve, reject) => {
29530 onePassSig.correspondingSigResolve = resolve;
29531 onePassSig.correspondingSigReject = reject;
29532 });
29533 onePassSig.signatureData = fromAsync(async () => (await onePassSig.correspondingSig).signatureData);
29534 onePassSig.hashed = readToEnd(await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false));
29535 onePassSig.hashed.catch(() => {});
29536 }));
29537 msg.packets.stream = transformPair(msg.packets.stream, async (readable, writable) => {
29538 const reader = getReader(readable);
29539 const writer = getWriter(writable);
29540 try {
29541 for (let i = 0; i < onePassSigList.length; i++) {
29542 const { value: signature } = await reader.read();
29543 onePassSigList[i].correspondingSigResolve(signature);
29544 }
29545 await reader.readToEnd();
29546 await writer.ready;
29547 await writer.close();
29548 } catch (e) {
29549 onePassSigList.forEach(onePassSig => {
29550 onePassSig.correspondingSigReject(e);
29551 });
29552 await writer.abort(e);
29553 }
29554 });
29555 return createVerificationObjects(onePassSigList, literalDataList, verificationKeys, date, false, config);
29556 }
29557 return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, false, config);
29558 }
29559
29560 /**
29561 * Verify detached message signature
29562 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
29563 * @param {Signature} signature
29564 * @param {Date} date - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
29565 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29566 * @returns {Promise<Array<{
29567 * keyID: module:type/keyid~KeyID,
29568 * signature: Promise<Signature>,
29569 * verified: Promise<true>
29570 * }>>} List of signer's keyID and validity of signature.
29571 * @async
29572 */
29573 verifyDetached(signature, verificationKeys, date = new Date(), config = defaultConfig) {
29574 const msg = this.unwrapCompressed();
29575 const literalDataList = msg.packets.filterByTag(enums.packet.literalData);
29576 if (literalDataList.length !== 1) {
29577 throw new Error('Can only verify message with one literal data packet.');
29578 }
29579 const signatureList = signature.packets;
29580 return createVerificationObjects(signatureList, literalDataList, verificationKeys, date, true, config);
29581 }
29582
29583 /**
29584 * Unwrap compressed message
29585 * @returns {Message} Message Content of compressed message.
29586 */
29587 unwrapCompressed() {
29588 const compressed = this.packets.filterByTag(enums.packet.compressedData);
29589 if (compressed.length) {
29590 return new Message(compressed[0].packets);
29591 }
29592 return this;
29593 }
29594
29595 /**
29596 * Append signature to unencrypted message object
29597 * @param {String|Uint8Array} detachedSignature - The detached ASCII-armored or Uint8Array PGP signature
29598 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29599 */
29600 async appendSignature(detachedSignature, config = defaultConfig) {
29601 await this.packets.read(
29602 util.isUint8Array(detachedSignature) ? detachedSignature : (await unarmor(detachedSignature)).data,
29603 allowedDetachedSignaturePackets,
29604 config
29605 );
29606 }
29607
29608 /**
29609 * Returns binary encoded message
29610 * @returns {ReadableStream<Uint8Array>} Binary message.
29611 */
29612 write() {
29613 return this.packets.write();
29614 }
29615
29616 /**
29617 * Returns ASCII armored text of message
29618 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29619 * @returns {ReadableStream<String>} ASCII armor.
29620 */
29621 armor(config = defaultConfig) {
29622 return armor(enums.armor.message, this.write(), null, null, null, config);
29623 }
29624 }
29625
29626 /**
29627 * Create signature packets for the message
29628 * @param {LiteralDataPacket} literalDataPacket - the literal data packet to sign
29629 * @param {Array<PrivateKey>} [signingKeys] - private keys with decrypted secret key data for signing
29630 * @param {Signature} [signature] - Any existing detached signature to append
29631 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to signingKeys[i]
29632 * @param {Date} [date] - Override the creationtime of the signature
29633 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
29634 * @param {Boolean} [detached] - Whether to create detached signature packets
29635 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29636 * @returns {Promise<PacketList>} List of signature packets.
29637 * @async
29638 * @private
29639 */
29640 async function createSignaturePackets(literalDataPacket, signingKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], detached = false, config = defaultConfig) {
29641 const packetlist = new PacketList();
29642
29643 // If data packet was created from Uint8Array, use binary, otherwise use text
29644 const signatureType = literalDataPacket.text === null ?
29645 enums.signature.binary : enums.signature.text;
29646
29647 await Promise.all(signingKeys.map(async (primaryKey, i) => {
29648 const userID = userIDs[i];
29649 if (!primaryKey.isPrivate()) {
29650 throw new Error('Need private key for signing');
29651 }
29652 const signingKey = await primaryKey.getSigningKey(signingKeyIDs[i], date, userID, config);
29653 return createSignaturePacket(literalDataPacket, primaryKey, signingKey.keyPacket, { signatureType }, date, userID, detached, config);
29654 })).then(signatureList => {
29655 packetlist.push(...signatureList);
29656 });
29657
29658 if (signature) {
29659 const existingSigPacketlist = signature.packets.filterByTag(enums.packet.signature);
29660 packetlist.push(...existingSigPacketlist);
29661 }
29662 return packetlist;
29663 }
29664
29665 /**
29666 * Create object containing signer's keyID and validity of signature
29667 * @param {SignaturePacket} signature - Signature packet
29668 * @param {Array<LiteralDataPacket>} literalDataList - Array of literal data packets
29669 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
29670 * @param {Date} [date] - Check signature validity with respect to the given date
29671 * @param {Boolean} [detached] - Whether to verify detached signature packets
29672 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29673 * @returns {Promise<{
29674 * keyID: module:type/keyid~KeyID,
29675 * signature: Promise<Signature>,
29676 * verified: Promise<true>
29677 * }>} signer's keyID and validity of signature
29678 * @async
29679 * @private
29680 */
29681 async function createVerificationObject(signature, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {
29682 let primaryKey;
29683 let unverifiedSigningKey;
29684
29685 for (const key of verificationKeys) {
29686 const issuerKeys = key.getKeys(signature.issuerKeyID);
29687 if (issuerKeys.length > 0) {
29688 primaryKey = key;
29689 unverifiedSigningKey = issuerKeys[0];
29690 break;
29691 }
29692 }
29693
29694 const isOnePassSignature = signature instanceof OnePassSignaturePacket;
29695 const signaturePacketPromise = isOnePassSignature ? signature.correspondingSig : signature;
29696
29697 const verifiedSig = {
29698 keyID: signature.issuerKeyID,
29699 verified: (async () => {
29700 if (!unverifiedSigningKey) {
29701 throw new Error(`Could not find signing key with key ID ${signature.issuerKeyID.toHex()}`);
29702 }
29703
29704 await signature.verify(unverifiedSigningKey.keyPacket, signature.signatureType, literalDataList[0], date, detached, config);
29705 const signaturePacket = await signaturePacketPromise;
29706 if (unverifiedSigningKey.getCreationTime() > signaturePacket.created) {
29707 throw new Error('Key is newer than the signature');
29708 }
29709 // We pass the signature creation time to check whether the key was expired at the time of signing.
29710 // We check this after signature verification because for streamed one-pass signatures, the creation time is not available before
29711 await primaryKey.getSigningKey(unverifiedSigningKey.getKeyID(), signaturePacket.created, undefined, config);
29712 return true;
29713 })(),
29714 signature: (async () => {
29715 const signaturePacket = await signaturePacketPromise;
29716 const packetlist = new PacketList();
29717 signaturePacket && packetlist.push(signaturePacket);
29718 return new Signature(packetlist);
29719 })()
29720 };
29721
29722 // Mark potential promise rejections as "handled". This is needed because in
29723 // some cases, we reject them before the user has a reasonable chance to
29724 // handle them (e.g. `await readToEnd(result.data); await result.verified` and
29725 // the data stream errors).
29726 verifiedSig.signature.catch(() => {});
29727 verifiedSig.verified.catch(() => {});
29728
29729 return verifiedSig;
29730 }
29731
29732 /**
29733 * Create list of objects containing signer's keyID and validity of signature
29734 * @param {Array<SignaturePacket>} signatureList - Array of signature packets
29735 * @param {Array<LiteralDataPacket>} literalDataList - Array of literal data packets
29736 * @param {Array<PublicKey>} verificationKeys - Array of public keys to verify signatures
29737 * @param {Date} date - Verify the signature against the given date,
29738 * i.e. check signature creation time < date < expiration time
29739 * @param {Boolean} [detached] - Whether to verify detached signature packets
29740 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29741 * @returns {Promise<Array<{
29742 * keyID: module:type/keyid~KeyID,
29743 * signature: Promise<Signature>,
29744 * verified: Promise<true>
29745 * }>>} list of signer's keyID and validity of signatures (one entry per signature packet in input)
29746 * @async
29747 * @private
29748 */
29749 async function createVerificationObjects(signatureList, literalDataList, verificationKeys, date = new Date(), detached = false, config = defaultConfig) {
29750 return Promise.all(signatureList.filter(function(signature) {
29751 return ['text', 'binary'].includes(enums.read(enums.signature, signature.signatureType));
29752 }).map(async function(signature) {
29753 return createVerificationObject(signature, literalDataList, verificationKeys, date, detached, config);
29754 }));
29755 }
29756
29757 /**
29758 * Reads an (optionally armored) OpenPGP message and returns a Message object
29759 * @param {Object} options
29760 * @param {String | ReadableStream<String>} [options.armoredMessage] - Armored message to be parsed
29761 * @param {Uint8Array | ReadableStream<Uint8Array>} [options.binaryMessage] - Binary to be parsed
29762 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29763 * @returns {Promise<Message>} New message object.
29764 * @async
29765 * @static
29766 */
29767 async function readMessage({ armoredMessage, binaryMessage, config, ...rest }) {
29768 config = { ...defaultConfig, ...config };
29769 let input = armoredMessage || binaryMessage;
29770 if (!input) {
29771 throw new Error('readMessage: must pass options object containing `armoredMessage` or `binaryMessage`');
29772 }
29773 if (armoredMessage && !util.isString(armoredMessage) && !util.isStream(armoredMessage)) {
29774 throw new Error('readMessage: options.armoredMessage must be a string or stream');
29775 }
29776 if (binaryMessage && !util.isUint8Array(binaryMessage) && !util.isStream(binaryMessage)) {
29777 throw new Error('readMessage: options.binaryMessage must be a Uint8Array or stream');
29778 }
29779 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
29780
29781 const streamType = util.isStream(input);
29782 if (streamType) {
29783 await loadStreamsPonyfill();
29784 input = toStream(input);
29785 }
29786 if (armoredMessage) {
29787 const { type, data } = await unarmor(input, config);
29788 if (type !== enums.armor.message) {
29789 throw new Error('Armored text not of type message');
29790 }
29791 input = data;
29792 }
29793 const packetlist = await PacketList.fromBinary(input, allowedMessagePackets, config);
29794 const message = new Message(packetlist);
29795 message.fromStream = streamType;
29796 return message;
29797 }
29798
29799 /**
29800 * Creates new message object from text or binary data.
29801 * @param {Object} options
29802 * @param {String | ReadableStream<String>} [options.text] - The text message contents
29803 * @param {Uint8Array | ReadableStream<Uint8Array>} [options.binary] - The binary message contents
29804 * @param {String} [options.filename=""] - Name of the file (if any)
29805 * @param {Date} [options.date=current date] - Date of the message, or modification date of the file
29806 * @param {'utf8'|'binary'|'text'|'mime'} [options.format='utf8' if text is passed, 'binary' otherwise] - Data packet type
29807 * @returns {Promise<Message>} New message object.
29808 * @async
29809 * @static
29810 */
29811 async function createMessage({ text, binary, filename, date = new Date(), format = text !== undefined ? 'utf8' : 'binary', ...rest }) {
29812 let input = text !== undefined ? text : binary;
29813 if (input === undefined) {
29814 throw new Error('createMessage: must pass options object containing `text` or `binary`');
29815 }
29816 if (text && !util.isString(text) && !util.isStream(text)) {
29817 throw new Error('createMessage: options.text must be a string or stream');
29818 }
29819 if (binary && !util.isUint8Array(binary) && !util.isStream(binary)) {
29820 throw new Error('createMessage: options.binary must be a Uint8Array or stream');
29821 }
29822 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
29823
29824 const streamType = util.isStream(input);
29825 if (streamType) {
29826 await loadStreamsPonyfill();
29827 input = toStream(input);
29828 }
29829 const literalDataPacket = new LiteralDataPacket(date);
29830 if (text !== undefined) {
29831 literalDataPacket.setText(input, format);
29832 } else {
29833 literalDataPacket.setBytes(input, format);
29834 }
29835 if (filename !== undefined) {
29836 literalDataPacket.setFilename(filename);
29837 }
29838 const literalDataPacketlist = new PacketList();
29839 literalDataPacketlist.push(literalDataPacket);
29840 const message = new Message(literalDataPacketlist);
29841 message.fromStream = streamType;
29842 return message;
29843 }
29844
29845 // GPG4Browsers - An OpenPGP implementation in javascript
29846
29847 // A Cleartext message can contain the following packets
29848 const allowedPackets$5 = /*#__PURE__*/ util.constructAllowedPackets([SignaturePacket]);
29849
29850 /**
29851 * Class that represents an OpenPGP cleartext signed message.
29852 * See {@link https://tools.ietf.org/html/rfc4880#section-7}
29853 */
29854 class CleartextMessage {
29855 /**
29856 * @param {String} text - The cleartext of the signed message
29857 * @param {Signature} signature - The detached signature or an empty signature for unsigned messages
29858 */
29859 constructor(text, signature) {
29860 // normalize EOL to canonical form <CR><LF>
29861 this.text = util.removeTrailingSpaces(text).replace(/\r?\n/g, '\r\n');
29862 if (signature && !(signature instanceof Signature)) {
29863 throw new Error('Invalid signature input');
29864 }
29865 this.signature = signature || new Signature(new PacketList());
29866 }
29867
29868 /**
29869 * Returns the key IDs of the keys that signed the cleartext message
29870 * @returns {Array<module:type/keyid~KeyID>} Array of keyID objects.
29871 */
29872 getSigningKeyIDs() {
29873 const keyIDs = [];
29874 const signatureList = this.signature.packets;
29875 signatureList.forEach(function(packet) {
29876 keyIDs.push(packet.issuerKeyID);
29877 });
29878 return keyIDs;
29879 }
29880
29881 /**
29882 * Sign the cleartext message
29883 * @param {Array<Key>} privateKeys - private keys with decrypted secret key data for signing
29884 * @param {Signature} [signature] - Any existing detached signature
29885 * @param {Array<module:type/keyid~KeyID>} [signingKeyIDs] - Array of key IDs to use for signing. Each signingKeyIDs[i] corresponds to privateKeys[i]
29886 * @param {Date} [date] - The creation time of the signature that should be created
29887 * @param {Array} [userIDs] - User IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
29888 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29889 * @returns {Promise<CleartextMessage>} New cleartext message with signed content.
29890 * @async
29891 */
29892 async sign(privateKeys, signature = null, signingKeyIDs = [], date = new Date(), userIDs = [], config = defaultConfig) {
29893 const literalDataPacket = new LiteralDataPacket();
29894 literalDataPacket.setText(this.text);
29895 const newSignature = new Signature(await createSignaturePackets(literalDataPacket, privateKeys, signature, signingKeyIDs, date, userIDs, true, config));
29896 return new CleartextMessage(this.text, newSignature);
29897 }
29898
29899 /**
29900 * Verify signatures of cleartext signed message
29901 * @param {Array<Key>} keys - Array of keys to verify signatures
29902 * @param {Date} [date] - Verify the signature against the given date, i.e. check signature creation time < date < expiration time
29903 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29904 * @returns {Promise<Array<{
29905 * keyID: module:type/keyid~KeyID,
29906 * signature: Promise<Signature>,
29907 * verified: Promise<true>
29908 * }>>} List of signer's keyID and validity of signature.
29909 * @async
29910 */
29911 verify(keys, date = new Date(), config = defaultConfig) {
29912 const signatureList = this.signature.packets;
29913 const literalDataPacket = new LiteralDataPacket();
29914 // we assume that cleartext signature is generated based on UTF8 cleartext
29915 literalDataPacket.setText(this.text);
29916 return createVerificationObjects(signatureList, [literalDataPacket], keys, date, true, config);
29917 }
29918
29919 /**
29920 * Get cleartext
29921 * @returns {String} Cleartext of message.
29922 */
29923 getText() {
29924 // normalize end of line to \n
29925 return this.text.replace(/\r\n/g, '\n');
29926 }
29927
29928 /**
29929 * Returns ASCII armored text of cleartext signed message
29930 * @param {Object} [config] - Full configuration, defaults to openpgp.config
29931 * @returns {String | ReadableStream<String>} ASCII armor.
29932 */
29933 armor(config = defaultConfig) {
29934 let hashes = this.signature.packets.map(function(packet) {
29935 return enums.read(enums.hash, packet.hashAlgorithm).toUpperCase();
29936 });
29937 hashes = hashes.filter(function(item, i, ar) { return ar.indexOf(item) === i; });
29938 const body = {
29939 hash: hashes.join(),
29940 text: this.text,
29941 data: this.signature.packets.write()
29942 };
29943 return armor(enums.armor.signed, body, undefined, undefined, undefined, config);
29944 }
29945 }
29946
29947 /**
29948 * Reads an OpenPGP cleartext signed message and returns a CleartextMessage object
29949 * @param {Object} options
29950 * @param {String} options.cleartextMessage - Text to be parsed
29951 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
29952 * @returns {Promise<CleartextMessage>} New cleartext message object.
29953 * @async
29954 * @static
29955 */
29956 async function readCleartextMessage({ cleartextMessage, config, ...rest }) {
29957 config = { ...defaultConfig, ...config };
29958 if (!cleartextMessage) {
29959 throw new Error('readCleartextMessage: must pass options object containing `cleartextMessage`');
29960 }
29961 if (!util.isString(cleartextMessage)) {
29962 throw new Error('readCleartextMessage: options.cleartextMessage must be a string');
29963 }
29964 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
29965
29966 const input = await unarmor(cleartextMessage);
29967 if (input.type !== enums.armor.signed) {
29968 throw new Error('No cleartext signed message.');
29969 }
29970 const packetlist = await PacketList.fromBinary(input.data, allowedPackets$5, config);
29971 verifyHeaders$1(input.headers, packetlist);
29972 const signature = new Signature(packetlist);
29973 return new CleartextMessage(input.text, signature);
29974 }
29975
29976 /**
29977 * Compare hash algorithm specified in the armor header with signatures
29978 * @param {Array<String>} headers - Armor headers
29979 * @param {PacketList} packetlist - The packetlist with signature packets
29980 * @private
29981 */
29982 function verifyHeaders$1(headers, packetlist) {
29983 const checkHashAlgos = function(hashAlgos) {
29984 const check = packet => algo => packet.hashAlgorithm === algo;
29985
29986 for (let i = 0; i < packetlist.length; i++) {
29987 if (packetlist[i].constructor.tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {
29988 return false;
29989 }
29990 }
29991 return true;
29992 };
29993
29994 let oneHeader = null;
29995 let hashAlgos = [];
29996 headers.forEach(function(header) {
29997 oneHeader = header.match(/Hash: (.+)/); // get header value
29998 if (oneHeader) {
29999 oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace
30000 oneHeader = oneHeader.split(',');
30001 oneHeader = oneHeader.map(function(hash) {
30002 hash = hash.toLowerCase();
30003 try {
30004 return enums.write(enums.hash, hash);
30005 } catch (e) {
30006 throw new Error('Unknown hash algorithm in armor header: ' + hash);
30007 }
30008 });
30009 hashAlgos = hashAlgos.concat(oneHeader);
30010 } else {
30011 throw new Error('Only "Hash" header allowed in cleartext signed message');
30012 }
30013 });
30014
30015 if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) {
30016 throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed');
30017 } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {
30018 throw new Error('Hash algorithm mismatch in armor header and signature');
30019 }
30020 }
30021
30022 /**
30023 * Creates a new CleartextMessage object from text
30024 * @param {Object} options
30025 * @param {String} options.text
30026 * @static
30027 * @async
30028 */
30029 async function createCleartextMessage({ text, ...rest }) {
30030 if (!text) {
30031 throw new Error('createCleartextMessage: must pass options object containing `text`');
30032 }
30033 if (!util.isString(text)) {
30034 throw new Error('createCleartextMessage: options.text must be a string');
30035 }
30036 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30037
30038 return new CleartextMessage(text);
30039 }
30040
30041 // OpenPGP.js - An OpenPGP implementation in javascript
30042
30043
30044 //////////////////////
30045 // //
30046 // Key handling //
30047 // //
30048 //////////////////////
30049
30050
30051 /**
30052 * Generates a new OpenPGP key pair. Supports RSA and ECC keys. By default, primary and subkeys will be of same type.
30053 * The generated primary key will have signing capabilities. By default, one subkey with encryption capabilities is also generated.
30054 * @param {Object} options
30055 * @param {Object|Array<Object>} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`
30056 * @param {'ecc'|'rsa'} [options.type='ecc'] - The primary key algorithm type: ECC (default) or RSA
30057 * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the generated private key. If omitted, the key won't be encrypted.
30058 * @param {Number} [options.rsaBits=4096] - Number of bits for RSA keys
30059 * @param {String} [options.curve='curve25519'] - Elliptic curve for ECC keys:
30060 * curve25519 (default), p256, p384, p521, secp256k1,
30061 * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1
30062 * @param {Date} [options.date=current date] - Override the creation date of the key and the key signatures
30063 * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires
30064 * @param {Array<Object>} [options.subkeys=a single encryption subkey] - Options for each subkey e.g. `[{sign: true, passphrase: '123'}]`
30065 * default to main key options, except for `sign` parameter that defaults to false, and indicates whether the subkey should sign rather than encrypt
30066 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys
30067 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30068 * @returns {Promise<Object>} The generated key object in the form:
30069 * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }
30070 * @async
30071 * @static
30072 */
30073 async function generateKey({ userIDs = [], passphrase = '', type = 'ecc', rsaBits = 4096, curve = 'curve25519', keyExpirationTime = 0, date = new Date(), subkeys = [{}], format = 'armored', config, ...rest }) {
30074 config = { ...defaultConfig, ...config }; checkConfig(config);
30075 userIDs = toArray$1(userIDs);
30076 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30077
30078 if (userIDs.length === 0) {
30079 throw new Error('UserIDs are required for key generation');
30080 }
30081 if (type === 'rsa' && rsaBits < config.minRSABits) {
30082 throw new Error(`rsaBits should be at least ${config.minRSABits}, got: ${rsaBits}`);
30083 }
30084
30085 const options = { userIDs, passphrase, type, rsaBits, curve, keyExpirationTime, date, subkeys };
30086
30087 try {
30088 const { key, revocationCertificate } = await generate$2(options, config);
30089 key.getKeys().forEach(({ keyPacket }) => checkKeyRequirements(keyPacket, config));
30090
30091 return {
30092 privateKey: formatObject(key, format, config),
30093 publicKey: formatObject(key.toPublic(), format, config),
30094 revocationCertificate
30095 };
30096 } catch (err) {
30097 throw util.wrapError('Error generating keypair', err);
30098 }
30099 }
30100
30101 /**
30102 * Reformats signature packets for a key and rewraps key object.
30103 * @param {Object} options
30104 * @param {PrivateKey} options.privateKey - Private key to reformat
30105 * @param {Object|Array<Object>} options.userIDs - User IDs as objects: `{ name: 'Jo Doe', email: 'info@jo.com' }`
30106 * @param {String} [options.passphrase=(not protected)] - The passphrase used to encrypt the reformatted private key. If omitted, the key won't be encrypted.
30107 * @param {Number} [options.keyExpirationTime=0 (never expires)] - Number of seconds from the key creation time after which the key expires
30108 * @param {Date} [options.date] - Override the creation date of the key signatures
30109 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output keys
30110 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30111 * @returns {Promise<Object>} The generated key object in the form:
30112 * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String, revocationCertificate:String }
30113 * @async
30114 * @static
30115 */
30116 async function reformatKey({ privateKey, userIDs = [], passphrase = '', keyExpirationTime = 0, date, format = 'armored', config, ...rest }) {
30117 config = { ...defaultConfig, ...config }; checkConfig(config);
30118 userIDs = toArray$1(userIDs);
30119 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30120
30121 if (userIDs.length === 0) {
30122 throw new Error('UserIDs are required for key reformat');
30123 }
30124 const options = { privateKey, userIDs, passphrase, keyExpirationTime, date };
30125
30126 try {
30127 const { key: reformattedKey, revocationCertificate } = await reformat(options, config);
30128
30129 return {
30130 privateKey: formatObject(reformattedKey, format, config),
30131 publicKey: formatObject(reformattedKey.toPublic(), format, config),
30132 revocationCertificate
30133 };
30134 } catch (err) {
30135 throw util.wrapError('Error reformatting keypair', err);
30136 }
30137 }
30138
30139 /**
30140 * Revokes a key. Requires either a private key or a revocation certificate.
30141 * If a revocation certificate is passed, the reasonForRevocation parameter will be ignored.
30142 * @param {Object} options
30143 * @param {Key} options.key - Public or private key to revoke
30144 * @param {String} [options.revocationCertificate] - Revocation certificate to revoke the key with
30145 * @param {Object} [options.reasonForRevocation] - Object indicating the reason for revocation
30146 * @param {module:enums.reasonForRevocation} [options.reasonForRevocation.flag=[noReason]{@link module:enums.reasonForRevocation}] - Flag indicating the reason for revocation
30147 * @param {String} [options.reasonForRevocation.string=""] - String explaining the reason for revocation
30148 * @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
30149 * @param {'armored'|'binary'|'object'} [options.format='armored'] - format of the output key(s)
30150 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30151 * @returns {Promise<Object>} The revoked key in the form:
30152 * { privateKey:PrivateKey|Uint8Array|String, publicKey:PublicKey|Uint8Array|String } if private key is passed, or
30153 * { privateKey: null, publicKey:PublicKey|Uint8Array|String } otherwise
30154 * @async
30155 * @static
30156 */
30157 async function revokeKey({ key, revocationCertificate, reasonForRevocation, date = new Date(), format = 'armored', config, ...rest }) {
30158 config = { ...defaultConfig, ...config }; checkConfig(config);
30159 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30160
30161 try {
30162 const revokedKey = revocationCertificate ?
30163 await key.applyRevocationCertificate(revocationCertificate, date, config) :
30164 await key.revoke(reasonForRevocation, date, config);
30165
30166 return revokedKey.isPrivate() ? {
30167 privateKey: formatObject(revokedKey, format, config),
30168 publicKey: formatObject(revokedKey.toPublic(), format, config)
30169 } : {
30170 privateKey: null,
30171 publicKey: formatObject(revokedKey, format, config)
30172 };
30173 } catch (err) {
30174 throw util.wrapError('Error revoking key', err);
30175 }
30176 }
30177
30178 /**
30179 * Unlock a private key with the given passphrase.
30180 * This method does not change the original key.
30181 * @param {Object} options
30182 * @param {PrivateKey} options.privateKey - The private key to decrypt
30183 * @param {String|Array<String>} options.passphrase - The user's passphrase(s)
30184 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30185 * @returns {Promise<PrivateKey>} The unlocked key object.
30186 * @async
30187 */
30188 async function decryptKey({ privateKey, passphrase, config, ...rest }) {
30189 config = { ...defaultConfig, ...config }; checkConfig(config);
30190 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30191
30192 if (!privateKey.isPrivate()) {
30193 throw new Error('Cannot decrypt a public key');
30194 }
30195 const clonedPrivateKey = privateKey.clone(true);
30196 const passphrases = util.isArray(passphrase) ? passphrase : [passphrase];
30197
30198 try {
30199 await Promise.all(clonedPrivateKey.getKeys().map(key => (
30200 // try to decrypt each key with any of the given passphrases
30201 util.anyPromise(passphrases.map(passphrase => key.keyPacket.decrypt(passphrase)))
30202 )));
30203
30204 await clonedPrivateKey.validate(config);
30205 return clonedPrivateKey;
30206 } catch (err) {
30207 clonedPrivateKey.clearPrivateParams();
30208 throw util.wrapError('Error decrypting private key', err);
30209 }
30210 }
30211
30212 /**
30213 * Lock a private key with the given passphrase.
30214 * This method does not change the original key.
30215 * @param {Object} options
30216 * @param {PrivateKey} options.privateKey - The private key to encrypt
30217 * @param {String|Array<String>} options.passphrase - If multiple passphrases, they should be in the same order as the packets each should encrypt
30218 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30219 * @returns {Promise<PrivateKey>} The locked key object.
30220 * @async
30221 */
30222 async function encryptKey({ privateKey, passphrase, config, ...rest }) {
30223 config = { ...defaultConfig, ...config }; checkConfig(config);
30224 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30225
30226 if (!privateKey.isPrivate()) {
30227 throw new Error('Cannot encrypt a public key');
30228 }
30229 const clonedPrivateKey = privateKey.clone(true);
30230
30231 const keys = clonedPrivateKey.getKeys();
30232 const passphrases = util.isArray(passphrase) ? passphrase : new Array(keys.length).fill(passphrase);
30233 if (passphrases.length !== keys.length) {
30234 throw new Error('Invalid number of passphrases given for key encryption');
30235 }
30236
30237 try {
30238 await Promise.all(keys.map(async (key, i) => {
30239 const { keyPacket } = key;
30240 await keyPacket.encrypt(passphrases[i], config);
30241 keyPacket.clearPrivateParams();
30242 }));
30243 return clonedPrivateKey;
30244 } catch (err) {
30245 clonedPrivateKey.clearPrivateParams();
30246 throw util.wrapError('Error encrypting private key', err);
30247 }
30248 }
30249
30250
30251 ///////////////////////////////////////////
30252 // //
30253 // Message encryption and decryption //
30254 // //
30255 ///////////////////////////////////////////
30256
30257
30258 /**
30259 * Encrypts a message using public keys, passwords or both at once. At least one of `encryptionKeys` or `passwords`
30260 * must be specified. If signing keys are specified, those will be used to sign the message.
30261 * @param {Object} options
30262 * @param {Message} options.message - Message to be encrypted as created by {@link createMessage}
30263 * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of keys or single key, used to encrypt the message
30264 * @param {PrivateKey|PrivateKey[]} [options.signingKeys] - Private keys for signing. If omitted message will not be signed
30265 * @param {String|String[]} [options.passwords] - Array of passwords or a single password to encrypt the message
30266 * @param {Object} [options.sessionKey] - Session key in the form: `{ data:Uint8Array, algorithm:String }`
30267 * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message
30268 * @param {Signature} [options.signature] - A detached signature to add to the encrypted message
30269 * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs
30270 * @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]`
30271 * @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]`
30272 * @param {Date} [options.date=current date] - Override the creation date of the message signature
30273 * @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' }]`
30274 * @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' }]`
30275 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30276 * @returns {Promise<MaybeStream<String>|MaybeStream<Uint8Array>>} Encrypted message (string if `armor` was true, the default; Uint8Array if `armor` was false).
30277 * @async
30278 * @static
30279 */
30280 async function encrypt$4({ message, encryptionKeys, signingKeys, passwords, sessionKey, format = 'armored', signature = null, wildcard = false, signingKeyIDs = [], encryptionKeyIDs = [], date = new Date(), signingUserIDs = [], encryptionUserIDs = [], config, ...rest }) {
30281 config = { ...defaultConfig, ...config }; checkConfig(config);
30282 checkMessage(message); checkOutputMessageFormat(format);
30283 encryptionKeys = toArray$1(encryptionKeys); signingKeys = toArray$1(signingKeys); passwords = toArray$1(passwords);
30284 signingKeyIDs = toArray$1(signingKeyIDs); encryptionKeyIDs = toArray$1(encryptionKeyIDs); signingUserIDs = toArray$1(signingUserIDs); encryptionUserIDs = toArray$1(encryptionUserIDs);
30285 if (rest.detached) {
30286 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.");
30287 }
30288 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encrypt, pass `encryptionKeys` instead');
30289 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.encrypt, pass `signingKeys` instead');
30290 if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.encrypt, pass `format` instead.');
30291 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30292
30293 if (!signingKeys) {
30294 signingKeys = [];
30295 }
30296 const streaming = message.fromStream;
30297 try {
30298 if (signingKeys.length || signature) { // sign the message only if signing keys or signature is specified
30299 message = await message.sign(signingKeys, signature, signingKeyIDs, date, signingUserIDs, config);
30300 }
30301 message = message.compress(
30302 await getPreferredAlgo('compression', encryptionKeys, date, encryptionUserIDs, config),
30303 config
30304 );
30305 message = await message.encrypt(encryptionKeys, passwords, sessionKey, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);
30306 if (format === 'object') return message;
30307 // serialize data
30308 const armor = format === 'armored';
30309 const data = armor ? message.armor(config) : message.write();
30310 return convertStream(data, streaming, armor ? 'utf8' : 'binary');
30311 } catch (err) {
30312 throw util.wrapError('Error encrypting message', err);
30313 }
30314 }
30315
30316 /**
30317 * Decrypts a message with the user's private key, a session key or a password.
30318 * One of `decryptionKeys`, `sessionkeys` or `passwords` must be specified (passing a combination of these options is not supported).
30319 * @param {Object} options
30320 * @param {Message} options.message - The message object with the encrypted data
30321 * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data or session key
30322 * @param {String|String[]} [options.passwords] - Passwords to decrypt the message
30323 * @param {Object|Object[]} [options.sessionKeys] - Session keys in the form: { data:Uint8Array, algorithm:String }
30324 * @param {PublicKey|PublicKey[]} [options.verificationKeys] - Array of public keys or single key, to verify signatures
30325 * @param {Boolean} [options.expectSigned=false] - If true, data decryption fails if the message is not signed with the provided publicKeys
30326 * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.
30327 * @param {Signature} [options.signature] - Detached signature for verification
30328 * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time
30329 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30330 * @returns {Promise<Object>} Object containing decrypted and verified message in the form:
30331 *
30332 * {
30333 * data: MaybeStream<String>, (if format was 'utf8', the default)
30334 * data: MaybeStream<Uint8Array>, (if format was 'binary')
30335 * filename: String,
30336 * signatures: [
30337 * {
30338 * keyID: module:type/keyid~KeyID,
30339 * verified: Promise<true>,
30340 * signature: Promise<Signature>
30341 * }, ...
30342 * ]
30343 * }
30344 *
30345 * where `signatures` contains a separate entry for each signature packet found in the input message.
30346 * @async
30347 * @static
30348 */
30349 async function decrypt$4({ message, decryptionKeys, passwords, sessionKeys, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {
30350 config = { ...defaultConfig, ...config }; checkConfig(config);
30351 checkMessage(message); verificationKeys = toArray$1(verificationKeys); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords); sessionKeys = toArray$1(sessionKeys);
30352 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decrypt, pass `decryptionKeys` instead');
30353 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.decrypt, pass `verificationKeys` instead');
30354 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30355
30356 try {
30357 const decrypted = await message.decrypt(decryptionKeys, passwords, sessionKeys, date, config);
30358 if (!verificationKeys) {
30359 verificationKeys = [];
30360 }
30361
30362 const result = {};
30363 result.signatures = signature ? await decrypted.verifyDetached(signature, verificationKeys, date, config) : await decrypted.verify(verificationKeys, date, config);
30364 result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();
30365 result.filename = decrypted.getFilename();
30366 linkStreams(result, message);
30367 if (expectSigned) {
30368 if (verificationKeys.length === 0) {
30369 throw new Error('Verification keys are required to verify message signatures');
30370 }
30371 if (result.signatures.length === 0) {
30372 throw new Error('Message is not signed');
30373 }
30374 result.data = concat([
30375 result.data,
30376 fromAsync(async () => {
30377 await util.anyPromise(result.signatures.map(sig => sig.verified));
30378 })
30379 ]);
30380 }
30381 result.data = await convertStream(result.data, message.fromStream, format);
30382 return result;
30383 } catch (err) {
30384 throw util.wrapError('Error decrypting message', err);
30385 }
30386 }
30387
30388
30389 //////////////////////////////////////////
30390 // //
30391 // Message signing and verification //
30392 // //
30393 //////////////////////////////////////////
30394
30395
30396 /**
30397 * Signs a message.
30398 * @param {Object} options
30399 * @param {CleartextMessage|Message} options.message - (cleartext) message to be signed
30400 * @param {PrivateKey|PrivateKey[]} options.signingKeys - Array of keys or single key with decrypted secret key data to sign cleartext
30401 * @param {'armored'|'binary'|'object'} [options.format='armored'] - Format of the returned message
30402 * @param {Boolean} [options.detached=false] - If the return value should contain a detached signature
30403 * @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]
30404 * @param {Date} [options.date=current date] - Override the creation date of the signature
30405 * @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' }]`
30406 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30407 * @returns {Promise<MaybeStream<String|Uint8Array>>} Signed message (string if `armor` was true, the default; Uint8Array if `armor` was false).
30408 * @async
30409 * @static
30410 */
30411 async function sign$5({ message, signingKeys, format = 'armored', detached = false, signingKeyIDs = [], date = new Date(), signingUserIDs = [], config, ...rest }) {
30412 config = { ...defaultConfig, ...config }; checkConfig(config);
30413 checkCleartextOrMessage(message); checkOutputMessageFormat(format);
30414 signingKeys = toArray$1(signingKeys); signingKeyIDs = toArray$1(signingKeyIDs); signingUserIDs = toArray$1(signingUserIDs);
30415
30416 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.sign, pass `signingKeys` instead');
30417 if (rest.armor !== undefined) throw new Error('The `armor` option has been removed from openpgp.sign, pass `format` instead.');
30418 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30419
30420 if (message instanceof CleartextMessage && format === 'binary') throw new Error('Cannot return signed cleartext message in binary format');
30421 if (message instanceof CleartextMessage && detached) throw new Error('Cannot detach-sign a cleartext message');
30422
30423 if (!signingKeys || signingKeys.length === 0) {
30424 throw new Error('No signing keys provided');
30425 }
30426
30427 try {
30428 let signature;
30429 if (detached) {
30430 signature = await message.signDetached(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, config);
30431 } else {
30432 signature = await message.sign(signingKeys, undefined, signingKeyIDs, date, signingUserIDs, config);
30433 }
30434 if (format === 'object') return signature;
30435
30436 const armor = format === 'armored';
30437 signature = armor ? signature.armor(config) : signature.write();
30438 if (detached) {
30439 signature = transformPair(message.packets.write(), async (readable, writable) => {
30440 await Promise.all([
30441 pipe(signature, writable),
30442 readToEnd(readable).catch(() => {})
30443 ]);
30444 });
30445 }
30446 return convertStream(signature, message.fromStream, armor ? 'utf8' : 'binary');
30447 } catch (err) {
30448 throw util.wrapError('Error signing message', err);
30449 }
30450 }
30451
30452 /**
30453 * Verifies signatures of cleartext signed message
30454 * @param {Object} options
30455 * @param {CleartextMessage|Message} options.message - (cleartext) message object with signatures
30456 * @param {PublicKey|PublicKey[]} options.verificationKeys - Array of publicKeys or single key, to verify signatures
30457 * @param {Boolean} [options.expectSigned=false] - If true, verification throws if the message is not signed with the provided publicKeys
30458 * @param {'utf8'|'binary'} [options.format='utf8'] - Whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.
30459 * @param {Signature} [options.signature] - Detached signature for verification
30460 * @param {Date} [options.date=current date] - Use the given date for verification instead of the current time
30461 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30462 * @returns {Promise<Object>} Object containing verified message in the form:
30463 *
30464 * {
30465 * data: MaybeStream<String>, (if `message` was a CleartextMessage)
30466 * data: MaybeStream<Uint8Array>, (if `message` was a Message)
30467 * signatures: [
30468 * {
30469 * keyID: module:type/keyid~KeyID,
30470 * verified: Promise<true>,
30471 * signature: Promise<Signature>
30472 * }, ...
30473 * ]
30474 * }
30475 *
30476 * where `signatures` contains a separate entry for each signature packet found in the input message.
30477 * @async
30478 * @static
30479 */
30480 async function verify$5({ message, verificationKeys, expectSigned = false, format = 'utf8', signature = null, date = new Date(), config, ...rest }) {
30481 config = { ...defaultConfig, ...config }; checkConfig(config);
30482 checkCleartextOrMessage(message); verificationKeys = toArray$1(verificationKeys);
30483 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead');
30484 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30485
30486 if (message instanceof CleartextMessage && format === 'binary') throw new Error("Can't return cleartext message data as binary");
30487 if (message instanceof CleartextMessage && signature) throw new Error("Can't verify detached cleartext signature");
30488
30489 try {
30490 const result = {};
30491 if (signature) {
30492 result.signatures = await message.verifyDetached(signature, verificationKeys, date, config);
30493 } else {
30494 result.signatures = await message.verify(verificationKeys, date, config);
30495 }
30496 result.data = format === 'binary' ? message.getLiteralData() : message.getText();
30497 if (message.fromStream) linkStreams(result, message);
30498 if (expectSigned) {
30499 if (result.signatures.length === 0) {
30500 throw new Error('Message is not signed');
30501 }
30502 result.data = concat([
30503 result.data,
30504 fromAsync(async () => {
30505 await util.anyPromise(result.signatures.map(sig => sig.verified));
30506 })
30507 ]);
30508 }
30509 result.data = await convertStream(result.data, message.fromStream, format);
30510 return result;
30511 } catch (err) {
30512 throw util.wrapError('Error verifying signed message', err);
30513 }
30514 }
30515
30516
30517 ///////////////////////////////////////////////
30518 // //
30519 // Session key encryption and decryption //
30520 // //
30521 ///////////////////////////////////////////////
30522
30523 /**
30524 * Generate a new session key object, taking the algorithm preferences of the passed public keys into account.
30525 * @param {Object} options
30526 * @param {PublicKey|PublicKey[]} options.encryptionKeys - Array of public keys or single key used to select algorithm preferences for
30527 * @param {Date} [options.date=current date] - Date to select algorithm preferences at
30528 * @param {Object|Object[]} [options.encryptionUserIDs=primary user IDs] - User IDs to select algorithm preferences for
30529 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30530 * @returns {Promise<{ data: Uint8Array, algorithm: String }>} Object with session key data and algorithm.
30531 * @async
30532 * @static
30533 */
30534 async function generateSessionKey$1({ encryptionKeys, date = new Date(), encryptionUserIDs = [], config, ...rest }) {
30535 config = { ...defaultConfig, ...config }; checkConfig(config);
30536 encryptionKeys = toArray$1(encryptionKeys); encryptionUserIDs = toArray$1(encryptionUserIDs);
30537 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.generateSessionKey, pass `encryptionKeys` instead');
30538 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30539
30540 try {
30541 const sessionKeys = await Message.generateSessionKey(encryptionKeys, date, encryptionUserIDs, config);
30542 return sessionKeys;
30543 } catch (err) {
30544 throw util.wrapError('Error generating session key', err);
30545 }
30546 }
30547
30548 /**
30549 * Encrypt a symmetric session key with public keys, passwords, or both at once.
30550 * At least one of `encryptionKeys` or `passwords` must be specified.
30551 * @param {Object} options
30552 * @param {Uint8Array} options.data - The session key to be encrypted e.g. 16 random bytes (for aes128)
30553 * @param {String} options.algorithm - Algorithm of the symmetric session key e.g. 'aes128' or 'aes256'
30554 * @param {String} [options.aeadAlgorithm] - AEAD algorithm, e.g. 'eax' or 'ocb'
30555 * @param {PublicKey|PublicKey[]} [options.encryptionKeys] - Array of public keys or single key, used to encrypt the key
30556 * @param {String|String[]} [options.passwords] - Passwords for the message
30557 * @param {'armored'|'binary'} [options.format='armored'] - Format of the returned value
30558 * @param {Boolean} [options.wildcard=false] - Use a key ID of 0 instead of the public key IDs
30559 * @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]
30560 * @param {Date} [options.date=current date] - Override the date
30561 * @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' }]`
30562 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30563 * @returns {Promise<String|Uint8Array>} Encrypted session keys (string if `armor` was true, the default; Uint8Array if `armor` was false).
30564 * @async
30565 * @static
30566 */
30567 async function encryptSessionKey({ data, algorithm, aeadAlgorithm, encryptionKeys, passwords, format = 'armored', wildcard = false, encryptionKeyIDs = [], date = new Date(), encryptionUserIDs = [], config, ...rest }) {
30568 config = { ...defaultConfig, ...config }; checkConfig(config);
30569 checkBinary(data); checkString(algorithm, 'algorithm'); checkOutputMessageFormat(format);
30570 encryptionKeys = toArray$1(encryptionKeys); passwords = toArray$1(passwords); encryptionKeyIDs = toArray$1(encryptionKeyIDs); encryptionUserIDs = toArray$1(encryptionUserIDs);
30571 if (rest.publicKeys) throw new Error('The `publicKeys` option has been removed from openpgp.encryptSessionKey, pass `encryptionKeys` instead');
30572 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30573
30574 try {
30575 const message = await Message.encryptSessionKey(data, algorithm, aeadAlgorithm, encryptionKeys, passwords, wildcard, encryptionKeyIDs, date, encryptionUserIDs, config);
30576 return formatObject(message, format, config);
30577 } catch (err) {
30578 throw util.wrapError('Error encrypting session key', err);
30579 }
30580 }
30581
30582 /**
30583 * Decrypt symmetric session keys using private keys or passwords (not both).
30584 * One of `decryptionKeys` or `passwords` must be specified.
30585 * @param {Object} options
30586 * @param {Message} options.message - A message object containing the encrypted session key packets
30587 * @param {PrivateKey|PrivateKey[]} [options.decryptionKeys] - Private keys with decrypted secret key data
30588 * @param {String|String[]} [options.passwords] - Passwords to decrypt the session key
30589 * @param {Date} [options.date] - Date to use for key verification instead of the current time
30590 * @param {Object} [options.config] - Custom configuration settings to overwrite those in [config]{@link module:config}
30591 * @returns {Promise<Object[]>} Array of decrypted session key, algorithm pairs in the form:
30592 * { data:Uint8Array, algorithm:String }
30593 * @throws if no session key could be found or decrypted
30594 * @async
30595 * @static
30596 */
30597 async function decryptSessionKeys({ message, decryptionKeys, passwords, date = new Date(), config, ...rest }) {
30598 config = { ...defaultConfig, ...config }; checkConfig(config);
30599 checkMessage(message); decryptionKeys = toArray$1(decryptionKeys); passwords = toArray$1(passwords);
30600 if (rest.privateKeys) throw new Error('The `privateKeys` option has been removed from openpgp.decryptSessionKeys, pass `decryptionKeys` instead');
30601 const unknownOptions = Object.keys(rest); if (unknownOptions.length > 0) throw new Error(`Unknown option: ${unknownOptions.join(', ')}`);
30602
30603 try {
30604 const sessionKeys = await message.decryptSessionKeys(decryptionKeys, passwords, date, config);
30605 return sessionKeys;
30606 } catch (err) {
30607 throw util.wrapError('Error decrypting session keys', err);
30608 }
30609 }
30610
30611
30612 //////////////////////////
30613 // //
30614 // Helper functions //
30615 // //
30616 //////////////////////////
30617
30618
30619 /**
30620 * Input validation
30621 * @private
30622 */
30623 function checkString(data, name) {
30624 if (!util.isString(data)) {
30625 throw new Error('Parameter [' + (name || 'data') + '] must be of type String');
30626 }
30627 }
30628 function checkBinary(data, name) {
30629 if (!util.isUint8Array(data)) {
30630 throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');
30631 }
30632 }
30633 function checkMessage(message) {
30634 if (!(message instanceof Message)) {
30635 throw new Error('Parameter [message] needs to be of type Message');
30636 }
30637 }
30638 function checkCleartextOrMessage(message) {
30639 if (!(message instanceof CleartextMessage) && !(message instanceof Message)) {
30640 throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');
30641 }
30642 }
30643 function checkOutputMessageFormat(format) {
30644 if (format !== 'armored' && format !== 'binary' && format !== 'object') {
30645 throw new Error(`Unsupported format ${format}`);
30646 }
30647 }
30648 const defaultConfigPropsCount = Object.keys(defaultConfig).length;
30649 function checkConfig(config) {
30650 const inputConfigProps = Object.keys(config);
30651 if (inputConfigProps.length !== defaultConfigPropsCount) {
30652 for (const inputProp of inputConfigProps) {
30653 if (defaultConfig[inputProp] === undefined) {
30654 throw new Error(`Unknown config property: ${inputProp}`);
30655 }
30656 }
30657 }
30658 }
30659
30660 /**
30661 * Normalize parameter to an array if it is not undefined.
30662 * @param {Object} param - the parameter to be normalized
30663 * @returns {Array<Object>|undefined} The resulting array or undefined.
30664 * @private
30665 */
30666 function toArray$1(param) {
30667 if (param && !util.isArray(param)) {
30668 param = [param];
30669 }
30670 return param;
30671 }
30672
30673 /**
30674 * Convert data to or from Stream
30675 * @param {Object} data - the data to convert
30676 * @param {'web'|'ponyfill'|'node'|false} streaming - Whether to return a ReadableStream, and of what type
30677 * @param {'utf8'|'binary'} [encoding] - How to return data in Node Readable streams
30678 * @returns {Promise<Object>} The data in the respective format.
30679 * @async
30680 * @private
30681 */
30682 async function convertStream(data, streaming, encoding = 'utf8') {
30683 const streamType = util.isStream(data);
30684 if (streamType === 'array') {
30685 return readToEnd(data);
30686 }
30687 if (streaming === 'node') {
30688 data = webToNode(data);
30689 if (encoding !== 'binary') data.setEncoding(encoding);
30690 return data;
30691 }
30692 if (streaming === 'web' && streamType === 'ponyfill') {
30693 return toNativeReadable(data);
30694 }
30695 return data;
30696 }
30697
30698 /**
30699 * Link result.data to the message stream for cancellation.
30700 * Also, forward errors in the message to result.data.
30701 * @param {Object} result - the data to convert
30702 * @param {Message} message - message object
30703 * @returns {Object}
30704 * @private
30705 */
30706 function linkStreams(result, message) {
30707 result.data = transformPair(message.packets.stream, async (readable, writable) => {
30708 await pipe(result.data, writable, {
30709 preventClose: true
30710 });
30711 const writer = getWriter(writable);
30712 try {
30713 // Forward errors in the message stream to result.data.
30714 await readToEnd(readable, _ => _);
30715 await writer.close();
30716 } catch (e) {
30717 await writer.abort(e);
30718 }
30719 });
30720 }
30721
30722 /**
30723 * Convert the object to the given format
30724 * @param {Key|Message} object
30725 * @param {'armored'|'binary'|'object'} format
30726 * @param {Object} config - Full configuration
30727 * @returns {String|Uint8Array|Object}
30728 */
30729 function formatObject(object, format, config) {
30730 switch (format) {
30731 case 'object':
30732 return object;
30733 case 'armored':
30734 return object.armor(config);
30735 case 'binary':
30736 return object.write();
30737 default:
30738 throw new Error(`Unsupported format ${format}`);
30739 }
30740 }
30741
30742 /**
30743 * web-streams-polyfill v3.0.3
30744 */
30745 /// <reference lib="es2015.symbol" />
30746 const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
30747 Symbol :
30748 description => `Symbol(${description})`;
30749
30750 /// <reference lib="dom" />
30751 function noop() {
30752 return undefined;
30753 }
30754 function getGlobals() {
30755 if (typeof self !== 'undefined') {
30756 return self;
30757 }
30758 else if (typeof window !== 'undefined') {
30759 return window;
30760 }
30761 else if (typeof global !== 'undefined') {
30762 return global;
30763 }
30764 return undefined;
30765 }
30766 const globals = getGlobals();
30767
30768 function typeIsObject(x) {
30769 return (typeof x === 'object' && x !== null) || typeof x === 'function';
30770 }
30771 const rethrowAssertionErrorRejection = noop;
30772
30773 const originalPromise = Promise;
30774 const originalPromiseThen = Promise.prototype.then;
30775 const originalPromiseResolve = Promise.resolve.bind(originalPromise);
30776 const originalPromiseReject = Promise.reject.bind(originalPromise);
30777 function newPromise(executor) {
30778 return new originalPromise(executor);
30779 }
30780 function promiseResolvedWith(value) {
30781 return originalPromiseResolve(value);
30782 }
30783 function promiseRejectedWith(reason) {
30784 return originalPromiseReject(reason);
30785 }
30786 function PerformPromiseThen(promise, onFulfilled, onRejected) {
30787 // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an
30788 // approximation.
30789 return originalPromiseThen.call(promise, onFulfilled, onRejected);
30790 }
30791 function uponPromise(promise, onFulfilled, onRejected) {
30792 PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);
30793 }
30794 function uponFulfillment(promise, onFulfilled) {
30795 uponPromise(promise, onFulfilled);
30796 }
30797 function uponRejection(promise, onRejected) {
30798 uponPromise(promise, undefined, onRejected);
30799 }
30800 function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
30801 return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
30802 }
30803 function setPromiseIsHandledToTrue(promise) {
30804 PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);
30805 }
30806 const queueMicrotask = (() => {
30807 const globalQueueMicrotask = globals && globals.queueMicrotask;
30808 if (typeof globalQueueMicrotask === 'function') {
30809 return globalQueueMicrotask;
30810 }
30811 const resolvedPromise = promiseResolvedWith(undefined);
30812 return (fn) => PerformPromiseThen(resolvedPromise, fn);
30813 })();
30814 function reflectCall(F, V, args) {
30815 if (typeof F !== 'function') {
30816 throw new TypeError('Argument is not a function');
30817 }
30818 return Function.prototype.apply.call(F, V, args);
30819 }
30820 function promiseCall(F, V, args) {
30821 try {
30822 return promiseResolvedWith(reflectCall(F, V, args));
30823 }
30824 catch (value) {
30825 return promiseRejectedWith(value);
30826 }
30827 }
30828
30829 // Original from Chromium
30830 // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js
30831 const QUEUE_MAX_ARRAY_SIZE = 16384;
30832 /**
30833 * Simple queue structure.
30834 *
30835 * Avoids scalability issues with using a packed array directly by using
30836 * multiple arrays in a linked list and keeping the array size bounded.
30837 */
30838 class SimpleQueue {
30839 constructor() {
30840 this._cursor = 0;
30841 this._size = 0;
30842 // _front and _back are always defined.
30843 this._front = {
30844 _elements: [],
30845 _next: undefined
30846 };
30847 this._back = this._front;
30848 // The cursor is used to avoid calling Array.shift().
30849 // It contains the index of the front element of the array inside the
30850 // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).
30851 this._cursor = 0;
30852 // When there is only one node, size === elements.length - cursor.
30853 this._size = 0;
30854 }
30855 get length() {
30856 return this._size;
30857 }
30858 // For exception safety, this method is structured in order:
30859 // 1. Read state
30860 // 2. Calculate required state mutations
30861 // 3. Perform state mutations
30862 push(element) {
30863 const oldBack = this._back;
30864 let newBack = oldBack;
30865 if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
30866 newBack = {
30867 _elements: [],
30868 _next: undefined
30869 };
30870 }
30871 // push() is the mutation most likely to throw an exception, so it
30872 // goes first.
30873 oldBack._elements.push(element);
30874 if (newBack !== oldBack) {
30875 this._back = newBack;
30876 oldBack._next = newBack;
30877 }
30878 ++this._size;
30879 }
30880 // Like push(), shift() follows the read -> calculate -> mutate pattern for
30881 // exception safety.
30882 shift() { // must not be called on an empty queue
30883 const oldFront = this._front;
30884 let newFront = oldFront;
30885 const oldCursor = this._cursor;
30886 let newCursor = oldCursor + 1;
30887 const elements = oldFront._elements;
30888 const element = elements[oldCursor];
30889 if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
30890 newFront = oldFront._next;
30891 newCursor = 0;
30892 }
30893 // No mutations before this point.
30894 --this._size;
30895 this._cursor = newCursor;
30896 if (oldFront !== newFront) {
30897 this._front = newFront;
30898 }
30899 // Permit shifted element to be garbage collected.
30900 elements[oldCursor] = undefined;
30901 return element;
30902 }
30903 // The tricky thing about forEach() is that it can be called
30904 // re-entrantly. The queue may be mutated inside the callback. It is easy to
30905 // see that push() within the callback has no negative effects since the end
30906 // of the queue is checked for on every iteration. If shift() is called
30907 // repeatedly within the callback then the next iteration may return an
30908 // element that has been removed. In this case the callback will be called
30909 // with undefined values until we either "catch up" with elements that still
30910 // exist or reach the back of the queue.
30911 forEach(callback) {
30912 let i = this._cursor;
30913 let node = this._front;
30914 let elements = node._elements;
30915 while (i !== elements.length || node._next !== undefined) {
30916 if (i === elements.length) {
30917 node = node._next;
30918 elements = node._elements;
30919 i = 0;
30920 if (elements.length === 0) {
30921 break;
30922 }
30923 }
30924 callback(elements[i]);
30925 ++i;
30926 }
30927 }
30928 // Return the element that would be returned if shift() was called now,
30929 // without modifying the queue.
30930 peek() { // must not be called on an empty queue
30931 const front = this._front;
30932 const cursor = this._cursor;
30933 return front._elements[cursor];
30934 }
30935 }
30936
30937 function ReadableStreamReaderGenericInitialize(reader, stream) {
30938 reader._ownerReadableStream = stream;
30939 stream._reader = reader;
30940 if (stream._state === 'readable') {
30941 defaultReaderClosedPromiseInitialize(reader);
30942 }
30943 else if (stream._state === 'closed') {
30944 defaultReaderClosedPromiseInitializeAsResolved(reader);
30945 }
30946 else {
30947 defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
30948 }
30949 }
30950 // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state
30951 // check.
30952 function ReadableStreamReaderGenericCancel(reader, reason) {
30953 const stream = reader._ownerReadableStream;
30954 return ReadableStreamCancel(stream, reason);
30955 }
30956 function ReadableStreamReaderGenericRelease(reader) {
30957 if (reader._ownerReadableStream._state === 'readable') {
30958 defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
30959 }
30960 else {
30961 defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
30962 }
30963 reader._ownerReadableStream._reader = undefined;
30964 reader._ownerReadableStream = undefined;
30965 }
30966 // Helper functions for the readers.
30967 function readerLockException(name) {
30968 return new TypeError('Cannot ' + name + ' a stream using a released reader');
30969 }
30970 // Helper functions for the ReadableStreamDefaultReader.
30971 function defaultReaderClosedPromiseInitialize(reader) {
30972 reader._closedPromise = newPromise((resolve, reject) => {
30973 reader._closedPromise_resolve = resolve;
30974 reader._closedPromise_reject = reject;
30975 });
30976 }
30977 function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
30978 defaultReaderClosedPromiseInitialize(reader);
30979 defaultReaderClosedPromiseReject(reader, reason);
30980 }
30981 function defaultReaderClosedPromiseInitializeAsResolved(reader) {
30982 defaultReaderClosedPromiseInitialize(reader);
30983 defaultReaderClosedPromiseResolve(reader);
30984 }
30985 function defaultReaderClosedPromiseReject(reader, reason) {
30986 if (reader._closedPromise_reject === undefined) {
30987 return;
30988 }
30989 setPromiseIsHandledToTrue(reader._closedPromise);
30990 reader._closedPromise_reject(reason);
30991 reader._closedPromise_resolve = undefined;
30992 reader._closedPromise_reject = undefined;
30993 }
30994 function defaultReaderClosedPromiseResetToRejected(reader, reason) {
30995 defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
30996 }
30997 function defaultReaderClosedPromiseResolve(reader) {
30998 if (reader._closedPromise_resolve === undefined) {
30999 return;
31000 }
31001 reader._closedPromise_resolve(undefined);
31002 reader._closedPromise_resolve = undefined;
31003 reader._closedPromise_reject = undefined;
31004 }
31005
31006 const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
31007 const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
31008 const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
31009 const PullSteps = SymbolPolyfill('[[PullSteps]]');
31010
31011 /// <reference lib="es2015.core" />
31012 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
31013 const NumberIsFinite = Number.isFinite || function (x) {
31014 return typeof x === 'number' && isFinite(x);
31015 };
31016
31017 /// <reference lib="es2015.core" />
31018 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill
31019 const MathTrunc = Math.trunc || function (v) {
31020 return v < 0 ? Math.ceil(v) : Math.floor(v);
31021 };
31022
31023 // https://heycam.github.io/webidl/#idl-dictionaries
31024 function isDictionary(x) {
31025 return typeof x === 'object' || typeof x === 'function';
31026 }
31027 function assertDictionary(obj, context) {
31028 if (obj !== undefined && !isDictionary(obj)) {
31029 throw new TypeError(`${context} is not an object.`);
31030 }
31031 }
31032 // https://heycam.github.io/webidl/#idl-callback-functions
31033 function assertFunction(x, context) {
31034 if (typeof x !== 'function') {
31035 throw new TypeError(`${context} is not a function.`);
31036 }
31037 }
31038 // https://heycam.github.io/webidl/#idl-object
31039 function isObject(x) {
31040 return (typeof x === 'object' && x !== null) || typeof x === 'function';
31041 }
31042 function assertObject(x, context) {
31043 if (!isObject(x)) {
31044 throw new TypeError(`${context} is not an object.`);
31045 }
31046 }
31047 function assertRequiredArgument(x, position, context) {
31048 if (x === undefined) {
31049 throw new TypeError(`Parameter ${position} is required in '${context}'.`);
31050 }
31051 }
31052 function assertRequiredField(x, field, context) {
31053 if (x === undefined) {
31054 throw new TypeError(`${field} is required in '${context}'.`);
31055 }
31056 }
31057 // https://heycam.github.io/webidl/#idl-unrestricted-double
31058 function convertUnrestrictedDouble(value) {
31059 return Number(value);
31060 }
31061 function censorNegativeZero(x) {
31062 return x === 0 ? 0 : x;
31063 }
31064 function integerPart(x) {
31065 return censorNegativeZero(MathTrunc(x));
31066 }
31067 // https://heycam.github.io/webidl/#idl-unsigned-long-long
31068 function convertUnsignedLongLongWithEnforceRange(value, context) {
31069 const lowerBound = 0;
31070 const upperBound = Number.MAX_SAFE_INTEGER;
31071 let x = Number(value);
31072 x = censorNegativeZero(x);
31073 if (!NumberIsFinite(x)) {
31074 throw new TypeError(`${context} is not a finite number`);
31075 }
31076 x = integerPart(x);
31077 if (x < lowerBound || x > upperBound) {
31078 throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
31079 }
31080 if (!NumberIsFinite(x) || x === 0) {
31081 return 0;
31082 }
31083 // TODO Use BigInt if supported?
31084 // let xBigInt = BigInt(integerPart(x));
31085 // xBigInt = BigInt.asUintN(64, xBigInt);
31086 // return Number(xBigInt);
31087 return x;
31088 }
31089
31090 function assertReadableStream(x, context) {
31091 if (!IsReadableStream(x)) {
31092 throw new TypeError(`${context} is not a ReadableStream.`);
31093 }
31094 }
31095
31096 // Abstract operations for the ReadableStream.
31097 function AcquireReadableStreamDefaultReader(stream) {
31098 return new ReadableStreamDefaultReader(stream);
31099 }
31100 // ReadableStream API exposed for controllers.
31101 function ReadableStreamAddReadRequest(stream, readRequest) {
31102 stream._reader._readRequests.push(readRequest);
31103 }
31104 function ReadableStreamFulfillReadRequest(stream, chunk, done) {
31105 const reader = stream._reader;
31106 const readRequest = reader._readRequests.shift();
31107 if (done) {
31108 readRequest._closeSteps();
31109 }
31110 else {
31111 readRequest._chunkSteps(chunk);
31112 }
31113 }
31114 function ReadableStreamGetNumReadRequests(stream) {
31115 return stream._reader._readRequests.length;
31116 }
31117 function ReadableStreamHasDefaultReader(stream) {
31118 const reader = stream._reader;
31119 if (reader === undefined) {
31120 return false;
31121 }
31122 if (!IsReadableStreamDefaultReader(reader)) {
31123 return false;
31124 }
31125 return true;
31126 }
31127 /**
31128 * A default reader vended by a {@link ReadableStream}.
31129 *
31130 * @public
31131 */
31132 class ReadableStreamDefaultReader {
31133 constructor(stream) {
31134 assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');
31135 assertReadableStream(stream, 'First parameter');
31136 if (IsReadableStreamLocked(stream)) {
31137 throw new TypeError('This stream has already been locked for exclusive reading by another reader');
31138 }
31139 ReadableStreamReaderGenericInitialize(this, stream);
31140 this._readRequests = new SimpleQueue();
31141 }
31142 /**
31143 * Returns a promise that will be fulfilled when the stream becomes closed,
31144 * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
31145 */
31146 get closed() {
31147 if (!IsReadableStreamDefaultReader(this)) {
31148 return promiseRejectedWith(defaultReaderBrandCheckException('closed'));
31149 }
31150 return this._closedPromise;
31151 }
31152 /**
31153 * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
31154 */
31155 cancel(reason = undefined) {
31156 if (!IsReadableStreamDefaultReader(this)) {
31157 return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));
31158 }
31159 if (this._ownerReadableStream === undefined) {
31160 return promiseRejectedWith(readerLockException('cancel'));
31161 }
31162 return ReadableStreamReaderGenericCancel(this, reason);
31163 }
31164 /**
31165 * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
31166 *
31167 * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
31168 */
31169 read() {
31170 if (!IsReadableStreamDefaultReader(this)) {
31171 return promiseRejectedWith(defaultReaderBrandCheckException('read'));
31172 }
31173 if (this._ownerReadableStream === undefined) {
31174 return promiseRejectedWith(readerLockException('read from'));
31175 }
31176 let resolvePromise;
31177 let rejectPromise;
31178 const promise = newPromise((resolve, reject) => {
31179 resolvePromise = resolve;
31180 rejectPromise = reject;
31181 });
31182 const readRequest = {
31183 _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
31184 _closeSteps: () => resolvePromise({ value: undefined, done: true }),
31185 _errorSteps: e => rejectPromise(e)
31186 };
31187 ReadableStreamDefaultReaderRead(this, readRequest);
31188 return promise;
31189 }
31190 /**
31191 * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
31192 * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
31193 * from now on; otherwise, the reader will appear closed.
31194 *
31195 * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
31196 * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
31197 * do so will throw a `TypeError` and leave the reader locked to the stream.
31198 */
31199 releaseLock() {
31200 if (!IsReadableStreamDefaultReader(this)) {
31201 throw defaultReaderBrandCheckException('releaseLock');
31202 }
31203 if (this._ownerReadableStream === undefined) {
31204 return;
31205 }
31206 if (this._readRequests.length > 0) {
31207 throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
31208 }
31209 ReadableStreamReaderGenericRelease(this);
31210 }
31211 }
31212 Object.defineProperties(ReadableStreamDefaultReader.prototype, {
31213 cancel: { enumerable: true },
31214 read: { enumerable: true },
31215 releaseLock: { enumerable: true },
31216 closed: { enumerable: true }
31217 });
31218 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
31219 Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
31220 value: 'ReadableStreamDefaultReader',
31221 configurable: true
31222 });
31223 }
31224 // Abstract operations for the readers.
31225 function IsReadableStreamDefaultReader(x) {
31226 if (!typeIsObject(x)) {
31227 return false;
31228 }
31229 if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {
31230 return false;
31231 }
31232 return true;
31233 }
31234 function ReadableStreamDefaultReaderRead(reader, readRequest) {
31235 const stream = reader._ownerReadableStream;
31236 stream._disturbed = true;
31237 if (stream._state === 'closed') {
31238 readRequest._closeSteps();
31239 }
31240 else if (stream._state === 'errored') {
31241 readRequest._errorSteps(stream._storedError);
31242 }
31243 else {
31244 stream._readableStreamController[PullSteps](readRequest);
31245 }
31246 }
31247 // Helper functions for the ReadableStreamDefaultReader.
31248 function defaultReaderBrandCheckException(name) {
31249 return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
31250 }
31251
31252 /// <reference lib="es2018.asynciterable" />
31253 let AsyncIteratorPrototype;
31254 if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
31255 // We're running inside a ES2018+ environment, but we're compiling to an older syntax.
31256 // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.
31257 AsyncIteratorPrototype = {
31258 // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )
31259 // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator
31260 [SymbolPolyfill.asyncIterator]() {
31261 return this;
31262 }
31263 };
31264 Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false });
31265 }
31266
31267 /// <reference lib="es2018.asynciterable" />
31268 class ReadableStreamAsyncIteratorImpl {
31269 constructor(reader, preventCancel) {
31270 this._ongoingPromise = undefined;
31271 this._isFinished = false;
31272 this._reader = reader;
31273 this._preventCancel = preventCancel;
31274 }
31275 next() {
31276 const nextSteps = () => this._nextSteps();
31277 this._ongoingPromise = this._ongoingPromise ?
31278 transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :
31279 nextSteps();
31280 return this._ongoingPromise;
31281 }
31282 return(value) {
31283 const returnSteps = () => this._returnSteps(value);
31284 return this._ongoingPromise ?
31285 transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :
31286 returnSteps();
31287 }
31288 _nextSteps() {
31289 if (this._isFinished) {
31290 return Promise.resolve({ value: undefined, done: true });
31291 }
31292 const reader = this._reader;
31293 if (reader._ownerReadableStream === undefined) {
31294 return promiseRejectedWith(readerLockException('iterate'));
31295 }
31296 let resolvePromise;
31297 let rejectPromise;
31298 const promise = newPromise((resolve, reject) => {
31299 resolvePromise = resolve;
31300 rejectPromise = reject;
31301 });
31302 const readRequest = {
31303 _chunkSteps: chunk => {
31304 this._ongoingPromise = undefined;
31305 // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.
31306 // FIXME Is this a bug in the specification, or in the test?
31307 queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
31308 },
31309 _closeSteps: () => {
31310 this._ongoingPromise = undefined;
31311 this._isFinished = true;
31312 ReadableStreamReaderGenericRelease(reader);
31313 resolvePromise({ value: undefined, done: true });
31314 },
31315 _errorSteps: reason => {
31316 this._ongoingPromise = undefined;
31317 this._isFinished = true;
31318 ReadableStreamReaderGenericRelease(reader);
31319 rejectPromise(reason);
31320 }
31321 };
31322 ReadableStreamDefaultReaderRead(reader, readRequest);
31323 return promise;
31324 }
31325 _returnSteps(value) {
31326 if (this._isFinished) {
31327 return Promise.resolve({ value, done: true });
31328 }
31329 this._isFinished = true;
31330 const reader = this._reader;
31331 if (reader._ownerReadableStream === undefined) {
31332 return promiseRejectedWith(readerLockException('finish iterating'));
31333 }
31334 if (!this._preventCancel) {
31335 const result = ReadableStreamReaderGenericCancel(reader, value);
31336 ReadableStreamReaderGenericRelease(reader);
31337 return transformPromiseWith(result, () => ({ value, done: true }));
31338 }
31339 ReadableStreamReaderGenericRelease(reader);
31340 return promiseResolvedWith({ value, done: true });
31341 }
31342 }
31343 const ReadableStreamAsyncIteratorPrototype = {
31344 next() {
31345 if (!IsReadableStreamAsyncIterator(this)) {
31346 return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));
31347 }
31348 return this._asyncIteratorImpl.next();
31349 },
31350 return(value) {
31351 if (!IsReadableStreamAsyncIterator(this)) {
31352 return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));
31353 }
31354 return this._asyncIteratorImpl.return(value);
31355 }
31356 };
31357 if (AsyncIteratorPrototype !== undefined) {
31358 Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
31359 }
31360 // Abstract operations for the ReadableStream.
31361 function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
31362 const reader = AcquireReadableStreamDefaultReader(stream);
31363 const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
31364 const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
31365 iterator._asyncIteratorImpl = impl;
31366 return iterator;
31367 }
31368 function IsReadableStreamAsyncIterator(x) {
31369 if (!typeIsObject(x)) {
31370 return false;
31371 }
31372 if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {
31373 return false;
31374 }
31375 return true;
31376 }
31377 // Helper functions for the ReadableStream.
31378 function streamAsyncIteratorBrandCheckException(name) {
31379 return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
31380 }
31381
31382 /// <reference lib="es2015.core" />
31383 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill
31384 const NumberIsNaN = Number.isNaN || function (x) {
31385 // eslint-disable-next-line no-self-compare
31386 return x !== x;
31387 };
31388
31389 function IsFiniteNonNegativeNumber(v) {
31390 if (!IsNonNegativeNumber(v)) {
31391 return false;
31392 }
31393 if (v === Infinity) {
31394 return false;
31395 }
31396 return true;
31397 }
31398 function IsNonNegativeNumber(v) {
31399 if (typeof v !== 'number') {
31400 return false;
31401 }
31402 if (NumberIsNaN(v)) {
31403 return false;
31404 }
31405 if (v < 0) {
31406 return false;
31407 }
31408 return true;
31409 }
31410
31411 function DequeueValue(container) {
31412 const pair = container._queue.shift();
31413 container._queueTotalSize -= pair.size;
31414 if (container._queueTotalSize < 0) {
31415 container._queueTotalSize = 0;
31416 }
31417 return pair.value;
31418 }
31419 function EnqueueValueWithSize(container, value, size) {
31420 size = Number(size);
31421 if (!IsFiniteNonNegativeNumber(size)) {
31422 throw new RangeError('Size must be a finite, non-NaN, non-negative number.');
31423 }
31424 container._queue.push({ value, size });
31425 container._queueTotalSize += size;
31426 }
31427 function PeekQueueValue(container) {
31428 const pair = container._queue.peek();
31429 return pair.value;
31430 }
31431 function ResetQueue(container) {
31432 container._queue = new SimpleQueue();
31433 container._queueTotalSize = 0;
31434 }
31435
31436 function CreateArrayFromList(elements) {
31437 // We use arrays to represent lists, so this is basically a no-op.
31438 // Do a slice though just in case we happen to depend on the unique-ness.
31439 return elements.slice();
31440 }
31441 function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
31442 new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
31443 }
31444 // Not implemented correctly
31445 function TransferArrayBuffer(O) {
31446 return O;
31447 }
31448 // Not implemented correctly
31449 function IsDetachedBuffer(O) {
31450 return false;
31451 }
31452
31453 /**
31454 * A pull-into request in a {@link ReadableByteStreamController}.
31455 *
31456 * @public
31457 */
31458 class ReadableStreamBYOBRequest {
31459 constructor() {
31460 throw new TypeError('Illegal constructor');
31461 }
31462 /**
31463 * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
31464 */
31465 get view() {
31466 if (!IsReadableStreamBYOBRequest(this)) {
31467 throw byobRequestBrandCheckException('view');
31468 }
31469 return this._view;
31470 }
31471 respond(bytesWritten) {
31472 if (!IsReadableStreamBYOBRequest(this)) {
31473 throw byobRequestBrandCheckException('respond');
31474 }
31475 assertRequiredArgument(bytesWritten, 1, 'respond');
31476 bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');
31477 if (this._associatedReadableByteStreamController === undefined) {
31478 throw new TypeError('This BYOB request has been invalidated');
31479 }
31480 if (IsDetachedBuffer(this._view.buffer)) ;
31481 ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
31482 }
31483 respondWithNewView(view) {
31484 if (!IsReadableStreamBYOBRequest(this)) {
31485 throw byobRequestBrandCheckException('respondWithNewView');
31486 }
31487 assertRequiredArgument(view, 1, 'respondWithNewView');
31488 if (!ArrayBuffer.isView(view)) {
31489 throw new TypeError('You can only respond with array buffer views');
31490 }
31491 if (view.byteLength === 0) {
31492 throw new TypeError('chunk must have non-zero byteLength');
31493 }
31494 if (view.buffer.byteLength === 0) {
31495 throw new TypeError(`chunk's buffer must have non-zero byteLength`);
31496 }
31497 if (this._associatedReadableByteStreamController === undefined) {
31498 throw new TypeError('This BYOB request has been invalidated');
31499 }
31500 ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
31501 }
31502 }
31503 Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
31504 respond: { enumerable: true },
31505 respondWithNewView: { enumerable: true },
31506 view: { enumerable: true }
31507 });
31508 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
31509 Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
31510 value: 'ReadableStreamBYOBRequest',
31511 configurable: true
31512 });
31513 }
31514 /**
31515 * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
31516 *
31517 * @public
31518 */
31519 class ReadableByteStreamController {
31520 constructor() {
31521 throw new TypeError('Illegal constructor');
31522 }
31523 /**
31524 * Returns the current BYOB pull request, or `null` if there isn't one.
31525 */
31526 get byobRequest() {
31527 if (!IsReadableByteStreamController(this)) {
31528 throw byteStreamControllerBrandCheckException('byobRequest');
31529 }
31530 if (this._byobRequest === null && this._pendingPullIntos.length > 0) {
31531 const firstDescriptor = this._pendingPullIntos.peek();
31532 const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
31533 const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
31534 SetUpReadableStreamBYOBRequest(byobRequest, this, view);
31535 this._byobRequest = byobRequest;
31536 }
31537 return this._byobRequest;
31538 }
31539 /**
31540 * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
31541 * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
31542 */
31543 get desiredSize() {
31544 if (!IsReadableByteStreamController(this)) {
31545 throw byteStreamControllerBrandCheckException('desiredSize');
31546 }
31547 return ReadableByteStreamControllerGetDesiredSize(this);
31548 }
31549 /**
31550 * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
31551 * the stream, but once those are read, the stream will become closed.
31552 */
31553 close() {
31554 if (!IsReadableByteStreamController(this)) {
31555 throw byteStreamControllerBrandCheckException('close');
31556 }
31557 if (this._closeRequested) {
31558 throw new TypeError('The stream has already been closed; do not close it again!');
31559 }
31560 const state = this._controlledReadableByteStream._state;
31561 if (state !== 'readable') {
31562 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
31563 }
31564 ReadableByteStreamControllerClose(this);
31565 }
31566 enqueue(chunk) {
31567 if (!IsReadableByteStreamController(this)) {
31568 throw byteStreamControllerBrandCheckException('enqueue');
31569 }
31570 assertRequiredArgument(chunk, 1, 'enqueue');
31571 if (!ArrayBuffer.isView(chunk)) {
31572 throw new TypeError('chunk must be an array buffer view');
31573 }
31574 if (chunk.byteLength === 0) {
31575 throw new TypeError('chunk must have non-zero byteLength');
31576 }
31577 if (chunk.buffer.byteLength === 0) {
31578 throw new TypeError(`chunk's buffer must have non-zero byteLength`);
31579 }
31580 if (this._closeRequested) {
31581 throw new TypeError('stream is closed or draining');
31582 }
31583 const state = this._controlledReadableByteStream._state;
31584 if (state !== 'readable') {
31585 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
31586 }
31587 ReadableByteStreamControllerEnqueue(this, chunk);
31588 }
31589 /**
31590 * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
31591 */
31592 error(e = undefined) {
31593 if (!IsReadableByteStreamController(this)) {
31594 throw byteStreamControllerBrandCheckException('error');
31595 }
31596 ReadableByteStreamControllerError(this, e);
31597 }
31598 /** @internal */
31599 [CancelSteps](reason) {
31600 if (this._pendingPullIntos.length > 0) {
31601 const firstDescriptor = this._pendingPullIntos.peek();
31602 firstDescriptor.bytesFilled = 0;
31603 }
31604 ResetQueue(this);
31605 const result = this._cancelAlgorithm(reason);
31606 ReadableByteStreamControllerClearAlgorithms(this);
31607 return result;
31608 }
31609 /** @internal */
31610 [PullSteps](readRequest) {
31611 const stream = this._controlledReadableByteStream;
31612 if (this._queueTotalSize > 0) {
31613 const entry = this._queue.shift();
31614 this._queueTotalSize -= entry.byteLength;
31615 ReadableByteStreamControllerHandleQueueDrain(this);
31616 const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
31617 readRequest._chunkSteps(view);
31618 return;
31619 }
31620 const autoAllocateChunkSize = this._autoAllocateChunkSize;
31621 if (autoAllocateChunkSize !== undefined) {
31622 let buffer;
31623 try {
31624 buffer = new ArrayBuffer(autoAllocateChunkSize);
31625 }
31626 catch (bufferE) {
31627 readRequest._errorSteps(bufferE);
31628 return;
31629 }
31630 const pullIntoDescriptor = {
31631 buffer,
31632 byteOffset: 0,
31633 byteLength: autoAllocateChunkSize,
31634 bytesFilled: 0,
31635 elementSize: 1,
31636 viewConstructor: Uint8Array,
31637 readerType: 'default'
31638 };
31639 this._pendingPullIntos.push(pullIntoDescriptor);
31640 }
31641 ReadableStreamAddReadRequest(stream, readRequest);
31642 ReadableByteStreamControllerCallPullIfNeeded(this);
31643 }
31644 }
31645 Object.defineProperties(ReadableByteStreamController.prototype, {
31646 close: { enumerable: true },
31647 enqueue: { enumerable: true },
31648 error: { enumerable: true },
31649 byobRequest: { enumerable: true },
31650 desiredSize: { enumerable: true }
31651 });
31652 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
31653 Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
31654 value: 'ReadableByteStreamController',
31655 configurable: true
31656 });
31657 }
31658 // Abstract operations for the ReadableByteStreamController.
31659 function IsReadableByteStreamController(x) {
31660 if (!typeIsObject(x)) {
31661 return false;
31662 }
31663 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {
31664 return false;
31665 }
31666 return true;
31667 }
31668 function IsReadableStreamBYOBRequest(x) {
31669 if (!typeIsObject(x)) {
31670 return false;
31671 }
31672 if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {
31673 return false;
31674 }
31675 return true;
31676 }
31677 function ReadableByteStreamControllerCallPullIfNeeded(controller) {
31678 const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
31679 if (!shouldPull) {
31680 return;
31681 }
31682 if (controller._pulling) {
31683 controller._pullAgain = true;
31684 return;
31685 }
31686 controller._pulling = true;
31687 // TODO: Test controller argument
31688 const pullPromise = controller._pullAlgorithm();
31689 uponPromise(pullPromise, () => {
31690 controller._pulling = false;
31691 if (controller._pullAgain) {
31692 controller._pullAgain = false;
31693 ReadableByteStreamControllerCallPullIfNeeded(controller);
31694 }
31695 }, e => {
31696 ReadableByteStreamControllerError(controller, e);
31697 });
31698 }
31699 function ReadableByteStreamControllerClearPendingPullIntos(controller) {
31700 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
31701 controller._pendingPullIntos = new SimpleQueue();
31702 }
31703 function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
31704 let done = false;
31705 if (stream._state === 'closed') {
31706 done = true;
31707 }
31708 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
31709 if (pullIntoDescriptor.readerType === 'default') {
31710 ReadableStreamFulfillReadRequest(stream, filledView, done);
31711 }
31712 else {
31713 ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
31714 }
31715 }
31716 function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
31717 const bytesFilled = pullIntoDescriptor.bytesFilled;
31718 const elementSize = pullIntoDescriptor.elementSize;
31719 return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
31720 }
31721 function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
31722 controller._queue.push({ buffer, byteOffset, byteLength });
31723 controller._queueTotalSize += byteLength;
31724 }
31725 function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
31726 const elementSize = pullIntoDescriptor.elementSize;
31727 const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
31728 const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
31729 const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
31730 const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
31731 let totalBytesToCopyRemaining = maxBytesToCopy;
31732 let ready = false;
31733 if (maxAlignedBytes > currentAlignedBytes) {
31734 totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
31735 ready = true;
31736 }
31737 const queue = controller._queue;
31738 while (totalBytesToCopyRemaining > 0) {
31739 const headOfQueue = queue.peek();
31740 const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
31741 const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
31742 CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
31743 if (headOfQueue.byteLength === bytesToCopy) {
31744 queue.shift();
31745 }
31746 else {
31747 headOfQueue.byteOffset += bytesToCopy;
31748 headOfQueue.byteLength -= bytesToCopy;
31749 }
31750 controller._queueTotalSize -= bytesToCopy;
31751 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
31752 totalBytesToCopyRemaining -= bytesToCopy;
31753 }
31754 return ready;
31755 }
31756 function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
31757 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
31758 pullIntoDescriptor.bytesFilled += size;
31759 }
31760 function ReadableByteStreamControllerHandleQueueDrain(controller) {
31761 if (controller._queueTotalSize === 0 && controller._closeRequested) {
31762 ReadableByteStreamControllerClearAlgorithms(controller);
31763 ReadableStreamClose(controller._controlledReadableByteStream);
31764 }
31765 else {
31766 ReadableByteStreamControllerCallPullIfNeeded(controller);
31767 }
31768 }
31769 function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
31770 if (controller._byobRequest === null) {
31771 return;
31772 }
31773 controller._byobRequest._associatedReadableByteStreamController = undefined;
31774 controller._byobRequest._view = null;
31775 controller._byobRequest = null;
31776 }
31777 function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
31778 while (controller._pendingPullIntos.length > 0) {
31779 if (controller._queueTotalSize === 0) {
31780 return;
31781 }
31782 const pullIntoDescriptor = controller._pendingPullIntos.peek();
31783 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
31784 ReadableByteStreamControllerShiftPendingPullInto(controller);
31785 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
31786 }
31787 }
31788 }
31789 function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
31790 const stream = controller._controlledReadableByteStream;
31791 let elementSize = 1;
31792 if (view.constructor !== DataView) {
31793 elementSize = view.constructor.BYTES_PER_ELEMENT;
31794 }
31795 const ctor = view.constructor;
31796 const buffer = TransferArrayBuffer(view.buffer);
31797 const pullIntoDescriptor = {
31798 buffer,
31799 byteOffset: view.byteOffset,
31800 byteLength: view.byteLength,
31801 bytesFilled: 0,
31802 elementSize,
31803 viewConstructor: ctor,
31804 readerType: 'byob'
31805 };
31806 if (controller._pendingPullIntos.length > 0) {
31807 controller._pendingPullIntos.push(pullIntoDescriptor);
31808 // No ReadableByteStreamControllerCallPullIfNeeded() call since:
31809 // - No change happens on desiredSize
31810 // - The source has already been notified of that there's at least 1 pending read(view)
31811 ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
31812 return;
31813 }
31814 if (stream._state === 'closed') {
31815 const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
31816 readIntoRequest._closeSteps(emptyView);
31817 return;
31818 }
31819 if (controller._queueTotalSize > 0) {
31820 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
31821 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
31822 ReadableByteStreamControllerHandleQueueDrain(controller);
31823 readIntoRequest._chunkSteps(filledView);
31824 return;
31825 }
31826 if (controller._closeRequested) {
31827 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
31828 ReadableByteStreamControllerError(controller, e);
31829 readIntoRequest._errorSteps(e);
31830 return;
31831 }
31832 }
31833 controller._pendingPullIntos.push(pullIntoDescriptor);
31834 ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
31835 ReadableByteStreamControllerCallPullIfNeeded(controller);
31836 }
31837 function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
31838 firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
31839 const stream = controller._controlledReadableByteStream;
31840 if (ReadableStreamHasBYOBReader(stream)) {
31841 while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
31842 const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
31843 ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
31844 }
31845 }
31846 }
31847 function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
31848 if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {
31849 throw new RangeError('bytesWritten out of range');
31850 }
31851 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
31852 if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {
31853 // TODO: Figure out whether we should detach the buffer or not here.
31854 return;
31855 }
31856 ReadableByteStreamControllerShiftPendingPullInto(controller);
31857 const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
31858 if (remainderSize > 0) {
31859 const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
31860 const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);
31861 ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
31862 }
31863 pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);
31864 pullIntoDescriptor.bytesFilled -= remainderSize;
31865 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
31866 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
31867 }
31868 function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
31869 const firstDescriptor = controller._pendingPullIntos.peek();
31870 const state = controller._controlledReadableByteStream._state;
31871 if (state === 'closed') {
31872 if (bytesWritten !== 0) {
31873 throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');
31874 }
31875 ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
31876 }
31877 else {
31878 ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
31879 }
31880 ReadableByteStreamControllerCallPullIfNeeded(controller);
31881 }
31882 function ReadableByteStreamControllerShiftPendingPullInto(controller) {
31883 const descriptor = controller._pendingPullIntos.shift();
31884 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
31885 return descriptor;
31886 }
31887 function ReadableByteStreamControllerShouldCallPull(controller) {
31888 const stream = controller._controlledReadableByteStream;
31889 if (stream._state !== 'readable') {
31890 return false;
31891 }
31892 if (controller._closeRequested) {
31893 return false;
31894 }
31895 if (!controller._started) {
31896 return false;
31897 }
31898 if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
31899 return true;
31900 }
31901 if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
31902 return true;
31903 }
31904 const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
31905 if (desiredSize > 0) {
31906 return true;
31907 }
31908 return false;
31909 }
31910 function ReadableByteStreamControllerClearAlgorithms(controller) {
31911 controller._pullAlgorithm = undefined;
31912 controller._cancelAlgorithm = undefined;
31913 }
31914 // A client of ReadableByteStreamController may use these functions directly to bypass state check.
31915 function ReadableByteStreamControllerClose(controller) {
31916 const stream = controller._controlledReadableByteStream;
31917 if (controller._closeRequested || stream._state !== 'readable') {
31918 return;
31919 }
31920 if (controller._queueTotalSize > 0) {
31921 controller._closeRequested = true;
31922 return;
31923 }
31924 if (controller._pendingPullIntos.length > 0) {
31925 const firstPendingPullInto = controller._pendingPullIntos.peek();
31926 if (firstPendingPullInto.bytesFilled > 0) {
31927 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
31928 ReadableByteStreamControllerError(controller, e);
31929 throw e;
31930 }
31931 }
31932 ReadableByteStreamControllerClearAlgorithms(controller);
31933 ReadableStreamClose(stream);
31934 }
31935 function ReadableByteStreamControllerEnqueue(controller, chunk) {
31936 const stream = controller._controlledReadableByteStream;
31937 if (controller._closeRequested || stream._state !== 'readable') {
31938 return;
31939 }
31940 const buffer = chunk.buffer;
31941 const byteOffset = chunk.byteOffset;
31942 const byteLength = chunk.byteLength;
31943 const transferredBuffer = TransferArrayBuffer(buffer);
31944 if (ReadableStreamHasDefaultReader(stream)) {
31945 if (ReadableStreamGetNumReadRequests(stream) === 0) {
31946 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
31947 }
31948 else {
31949 const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
31950 ReadableStreamFulfillReadRequest(stream, transferredView, false);
31951 }
31952 }
31953 else if (ReadableStreamHasBYOBReader(stream)) {
31954 // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.
31955 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
31956 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
31957 }
31958 else {
31959 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
31960 }
31961 ReadableByteStreamControllerCallPullIfNeeded(controller);
31962 }
31963 function ReadableByteStreamControllerError(controller, e) {
31964 const stream = controller._controlledReadableByteStream;
31965 if (stream._state !== 'readable') {
31966 return;
31967 }
31968 ReadableByteStreamControllerClearPendingPullIntos(controller);
31969 ResetQueue(controller);
31970 ReadableByteStreamControllerClearAlgorithms(controller);
31971 ReadableStreamError(stream, e);
31972 }
31973 function ReadableByteStreamControllerGetDesiredSize(controller) {
31974 const state = controller._controlledReadableByteStream._state;
31975 if (state === 'errored') {
31976 return null;
31977 }
31978 if (state === 'closed') {
31979 return 0;
31980 }
31981 return controller._strategyHWM - controller._queueTotalSize;
31982 }
31983 function ReadableByteStreamControllerRespond(controller, bytesWritten) {
31984 bytesWritten = Number(bytesWritten);
31985 if (!IsFiniteNonNegativeNumber(bytesWritten)) {
31986 throw new RangeError('bytesWritten must be a finite');
31987 }
31988 ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
31989 }
31990 function ReadableByteStreamControllerRespondWithNewView(controller, view) {
31991 const firstDescriptor = controller._pendingPullIntos.peek();
31992 if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
31993 throw new RangeError('The region specified by view does not match byobRequest');
31994 }
31995 if (firstDescriptor.byteLength !== view.byteLength) {
31996 throw new RangeError('The buffer of view has different capacity than byobRequest');
31997 }
31998 firstDescriptor.buffer = view.buffer;
31999 ReadableByteStreamControllerRespondInternal(controller, view.byteLength);
32000 }
32001 function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
32002 controller._controlledReadableByteStream = stream;
32003 controller._pullAgain = false;
32004 controller._pulling = false;
32005 controller._byobRequest = null;
32006 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
32007 controller._queue = controller._queueTotalSize = undefined;
32008 ResetQueue(controller);
32009 controller._closeRequested = false;
32010 controller._started = false;
32011 controller._strategyHWM = highWaterMark;
32012 controller._pullAlgorithm = pullAlgorithm;
32013 controller._cancelAlgorithm = cancelAlgorithm;
32014 controller._autoAllocateChunkSize = autoAllocateChunkSize;
32015 controller._pendingPullIntos = new SimpleQueue();
32016 stream._readableStreamController = controller;
32017 const startResult = startAlgorithm();
32018 uponPromise(promiseResolvedWith(startResult), () => {
32019 controller._started = true;
32020 ReadableByteStreamControllerCallPullIfNeeded(controller);
32021 }, r => {
32022 ReadableByteStreamControllerError(controller, r);
32023 });
32024 }
32025 function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
32026 const controller = Object.create(ReadableByteStreamController.prototype);
32027 let startAlgorithm = () => undefined;
32028 let pullAlgorithm = () => promiseResolvedWith(undefined);
32029 let cancelAlgorithm = () => promiseResolvedWith(undefined);
32030 if (underlyingByteSource.start !== undefined) {
32031 startAlgorithm = () => underlyingByteSource.start(controller);
32032 }
32033 if (underlyingByteSource.pull !== undefined) {
32034 pullAlgorithm = () => underlyingByteSource.pull(controller);
32035 }
32036 if (underlyingByteSource.cancel !== undefined) {
32037 cancelAlgorithm = reason => underlyingByteSource.cancel(reason);
32038 }
32039 const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
32040 if (autoAllocateChunkSize === 0) {
32041 throw new TypeError('autoAllocateChunkSize must be greater than 0');
32042 }
32043 SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
32044 }
32045 function SetUpReadableStreamBYOBRequest(request, controller, view) {
32046 request._associatedReadableByteStreamController = controller;
32047 request._view = view;
32048 }
32049 // Helper functions for the ReadableStreamBYOBRequest.
32050 function byobRequestBrandCheckException(name) {
32051 return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
32052 }
32053 // Helper functions for the ReadableByteStreamController.
32054 function byteStreamControllerBrandCheckException(name) {
32055 return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
32056 }
32057
32058 // Abstract operations for the ReadableStream.
32059 function AcquireReadableStreamBYOBReader(stream) {
32060 return new ReadableStreamBYOBReader(stream);
32061 }
32062 // ReadableStream API exposed for controllers.
32063 function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {
32064 stream._reader._readIntoRequests.push(readIntoRequest);
32065 }
32066 function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
32067 const reader = stream._reader;
32068 const readIntoRequest = reader._readIntoRequests.shift();
32069 if (done) {
32070 readIntoRequest._closeSteps(chunk);
32071 }
32072 else {
32073 readIntoRequest._chunkSteps(chunk);
32074 }
32075 }
32076 function ReadableStreamGetNumReadIntoRequests(stream) {
32077 return stream._reader._readIntoRequests.length;
32078 }
32079 function ReadableStreamHasBYOBReader(stream) {
32080 const reader = stream._reader;
32081 if (reader === undefined) {
32082 return false;
32083 }
32084 if (!IsReadableStreamBYOBReader(reader)) {
32085 return false;
32086 }
32087 return true;
32088 }
32089 /**
32090 * A BYOB reader vended by a {@link ReadableStream}.
32091 *
32092 * @public
32093 */
32094 class ReadableStreamBYOBReader {
32095 constructor(stream) {
32096 assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');
32097 assertReadableStream(stream, 'First parameter');
32098 if (IsReadableStreamLocked(stream)) {
32099 throw new TypeError('This stream has already been locked for exclusive reading by another reader');
32100 }
32101 if (!IsReadableByteStreamController(stream._readableStreamController)) {
32102 throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +
32103 'source');
32104 }
32105 ReadableStreamReaderGenericInitialize(this, stream);
32106 this._readIntoRequests = new SimpleQueue();
32107 }
32108 /**
32109 * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
32110 * the reader's lock is released before the stream finishes closing.
32111 */
32112 get closed() {
32113 if (!IsReadableStreamBYOBReader(this)) {
32114 return promiseRejectedWith(byobReaderBrandCheckException('closed'));
32115 }
32116 return this._closedPromise;
32117 }
32118 /**
32119 * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
32120 */
32121 cancel(reason = undefined) {
32122 if (!IsReadableStreamBYOBReader(this)) {
32123 return promiseRejectedWith(byobReaderBrandCheckException('cancel'));
32124 }
32125 if (this._ownerReadableStream === undefined) {
32126 return promiseRejectedWith(readerLockException('cancel'));
32127 }
32128 return ReadableStreamReaderGenericCancel(this, reason);
32129 }
32130 /**
32131 * Attempts to reads bytes into view, and returns a promise resolved with the result.
32132 *
32133 * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
32134 */
32135 read(view) {
32136 if (!IsReadableStreamBYOBReader(this)) {
32137 return promiseRejectedWith(byobReaderBrandCheckException('read'));
32138 }
32139 if (!ArrayBuffer.isView(view)) {
32140 return promiseRejectedWith(new TypeError('view must be an array buffer view'));
32141 }
32142 if (view.byteLength === 0) {
32143 return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));
32144 }
32145 if (view.buffer.byteLength === 0) {
32146 return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
32147 }
32148 if (this._ownerReadableStream === undefined) {
32149 return promiseRejectedWith(readerLockException('read from'));
32150 }
32151 let resolvePromise;
32152 let rejectPromise;
32153 const promise = newPromise((resolve, reject) => {
32154 resolvePromise = resolve;
32155 rejectPromise = reject;
32156 });
32157 const readIntoRequest = {
32158 _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
32159 _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),
32160 _errorSteps: e => rejectPromise(e)
32161 };
32162 ReadableStreamBYOBReaderRead(this, view, readIntoRequest);
32163 return promise;
32164 }
32165 /**
32166 * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
32167 * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
32168 * from now on; otherwise, the reader will appear closed.
32169 *
32170 * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
32171 * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
32172 * do so will throw a `TypeError` and leave the reader locked to the stream.
32173 */
32174 releaseLock() {
32175 if (!IsReadableStreamBYOBReader(this)) {
32176 throw byobReaderBrandCheckException('releaseLock');
32177 }
32178 if (this._ownerReadableStream === undefined) {
32179 return;
32180 }
32181 if (this._readIntoRequests.length > 0) {
32182 throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
32183 }
32184 ReadableStreamReaderGenericRelease(this);
32185 }
32186 }
32187 Object.defineProperties(ReadableStreamBYOBReader.prototype, {
32188 cancel: { enumerable: true },
32189 read: { enumerable: true },
32190 releaseLock: { enumerable: true },
32191 closed: { enumerable: true }
32192 });
32193 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
32194 Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
32195 value: 'ReadableStreamBYOBReader',
32196 configurable: true
32197 });
32198 }
32199 // Abstract operations for the readers.
32200 function IsReadableStreamBYOBReader(x) {
32201 if (!typeIsObject(x)) {
32202 return false;
32203 }
32204 if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {
32205 return false;
32206 }
32207 return true;
32208 }
32209 function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
32210 const stream = reader._ownerReadableStream;
32211 stream._disturbed = true;
32212 if (stream._state === 'errored') {
32213 readIntoRequest._errorSteps(stream._storedError);
32214 }
32215 else {
32216 ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
32217 }
32218 }
32219 // Helper functions for the ReadableStreamBYOBReader.
32220 function byobReaderBrandCheckException(name) {
32221 return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
32222 }
32223
32224 function ExtractHighWaterMark(strategy, defaultHWM) {
32225 const { highWaterMark } = strategy;
32226 if (highWaterMark === undefined) {
32227 return defaultHWM;
32228 }
32229 if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
32230 throw new RangeError('Invalid highWaterMark');
32231 }
32232 return highWaterMark;
32233 }
32234 function ExtractSizeAlgorithm(strategy) {
32235 const { size } = strategy;
32236 if (!size) {
32237 return () => 1;
32238 }
32239 return size;
32240 }
32241
32242 function convertQueuingStrategy(init, context) {
32243 assertDictionary(init, context);
32244 const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
32245 const size = init === null || init === void 0 ? void 0 : init.size;
32246 return {
32247 highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),
32248 size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)
32249 };
32250 }
32251 function convertQueuingStrategySize(fn, context) {
32252 assertFunction(fn, context);
32253 return chunk => convertUnrestrictedDouble(fn(chunk));
32254 }
32255
32256 function convertUnderlyingSink(original, context) {
32257 assertDictionary(original, context);
32258 const abort = original === null || original === void 0 ? void 0 : original.abort;
32259 const close = original === null || original === void 0 ? void 0 : original.close;
32260 const start = original === null || original === void 0 ? void 0 : original.start;
32261 const type = original === null || original === void 0 ? void 0 : original.type;
32262 const write = original === null || original === void 0 ? void 0 : original.write;
32263 return {
32264 abort: abort === undefined ?
32265 undefined :
32266 convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),
32267 close: close === undefined ?
32268 undefined :
32269 convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),
32270 start: start === undefined ?
32271 undefined :
32272 convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),
32273 write: write === undefined ?
32274 undefined :
32275 convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),
32276 type
32277 };
32278 }
32279 function convertUnderlyingSinkAbortCallback(fn, original, context) {
32280 assertFunction(fn, context);
32281 return (reason) => promiseCall(fn, original, [reason]);
32282 }
32283 function convertUnderlyingSinkCloseCallback(fn, original, context) {
32284 assertFunction(fn, context);
32285 return () => promiseCall(fn, original, []);
32286 }
32287 function convertUnderlyingSinkStartCallback(fn, original, context) {
32288 assertFunction(fn, context);
32289 return (controller) => reflectCall(fn, original, [controller]);
32290 }
32291 function convertUnderlyingSinkWriteCallback(fn, original, context) {
32292 assertFunction(fn, context);
32293 return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
32294 }
32295
32296 function assertWritableStream(x, context) {
32297 if (!IsWritableStream(x)) {
32298 throw new TypeError(`${context} is not a WritableStream.`);
32299 }
32300 }
32301
32302 /**
32303 * A writable stream represents a destination for data, into which you can write.
32304 *
32305 * @public
32306 */
32307 class WritableStream$1 {
32308 constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
32309 if (rawUnderlyingSink === undefined) {
32310 rawUnderlyingSink = null;
32311 }
32312 else {
32313 assertObject(rawUnderlyingSink, 'First parameter');
32314 }
32315 const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
32316 const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');
32317 InitializeWritableStream(this);
32318 const type = underlyingSink.type;
32319 if (type !== undefined) {
32320 throw new RangeError('Invalid type is specified');
32321 }
32322 const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
32323 const highWaterMark = ExtractHighWaterMark(strategy, 1);
32324 SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
32325 }
32326 /**
32327 * Returns whether or not the writable stream is locked to a writer.
32328 */
32329 get locked() {
32330 if (!IsWritableStream(this)) {
32331 throw streamBrandCheckException$2('locked');
32332 }
32333 return IsWritableStreamLocked(this);
32334 }
32335 /**
32336 * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
32337 * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
32338 * mechanism of the underlying sink.
32339 *
32340 * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
32341 * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
32342 * the stream) if the stream is currently locked.
32343 */
32344 abort(reason = undefined) {
32345 if (!IsWritableStream(this)) {
32346 return promiseRejectedWith(streamBrandCheckException$2('abort'));
32347 }
32348 if (IsWritableStreamLocked(this)) {
32349 return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));
32350 }
32351 return WritableStreamAbort(this, reason);
32352 }
32353 /**
32354 * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
32355 * close behavior. During this time any further attempts to write will fail (without erroring the stream).
32356 *
32357 * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
32358 * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
32359 * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
32360 */
32361 close() {
32362 if (!IsWritableStream(this)) {
32363 return promiseRejectedWith(streamBrandCheckException$2('close'));
32364 }
32365 if (IsWritableStreamLocked(this)) {
32366 return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));
32367 }
32368 if (WritableStreamCloseQueuedOrInFlight(this)) {
32369 return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
32370 }
32371 return WritableStreamClose(this);
32372 }
32373 /**
32374 * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
32375 * is locked, no other writer can be acquired until this one is released.
32376 *
32377 * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
32378 * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
32379 * the same time, which would cause the resulting written data to be unpredictable and probably useless.
32380 */
32381 getWriter() {
32382 if (!IsWritableStream(this)) {
32383 throw streamBrandCheckException$2('getWriter');
32384 }
32385 return AcquireWritableStreamDefaultWriter(this);
32386 }
32387 }
32388 Object.defineProperties(WritableStream$1.prototype, {
32389 abort: { enumerable: true },
32390 close: { enumerable: true },
32391 getWriter: { enumerable: true },
32392 locked: { enumerable: true }
32393 });
32394 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
32395 Object.defineProperty(WritableStream$1.prototype, SymbolPolyfill.toStringTag, {
32396 value: 'WritableStream',
32397 configurable: true
32398 });
32399 }
32400 // Abstract operations for the WritableStream.
32401 function AcquireWritableStreamDefaultWriter(stream) {
32402 return new WritableStreamDefaultWriter(stream);
32403 }
32404 // Throws if and only if startAlgorithm throws.
32405 function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
32406 const stream = Object.create(WritableStream$1.prototype);
32407 InitializeWritableStream(stream);
32408 const controller = Object.create(WritableStreamDefaultController.prototype);
32409 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
32410 return stream;
32411 }
32412 function InitializeWritableStream(stream) {
32413 stream._state = 'writable';
32414 // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is
32415 // 'erroring' or 'errored'. May be set to an undefined value.
32416 stream._storedError = undefined;
32417 stream._writer = undefined;
32418 // Initialize to undefined first because the constructor of the controller checks this
32419 // variable to validate the caller.
32420 stream._writableStreamController = undefined;
32421 // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data
32422 // producer without waiting for the queued writes to finish.
32423 stream._writeRequests = new SimpleQueue();
32424 // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents
32425 // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.
32426 stream._inFlightWriteRequest = undefined;
32427 // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer
32428 // has been detached.
32429 stream._closeRequest = undefined;
32430 // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it
32431 // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.
32432 stream._inFlightCloseRequest = undefined;
32433 // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.
32434 stream._pendingAbortRequest = undefined;
32435 // The backpressure signal set by the controller.
32436 stream._backpressure = false;
32437 }
32438 function IsWritableStream(x) {
32439 if (!typeIsObject(x)) {
32440 return false;
32441 }
32442 if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {
32443 return false;
32444 }
32445 return true;
32446 }
32447 function IsWritableStreamLocked(stream) {
32448 if (stream._writer === undefined) {
32449 return false;
32450 }
32451 return true;
32452 }
32453 function WritableStreamAbort(stream, reason) {
32454 const state = stream._state;
32455 if (state === 'closed' || state === 'errored') {
32456 return promiseResolvedWith(undefined);
32457 }
32458 if (stream._pendingAbortRequest !== undefined) {
32459 return stream._pendingAbortRequest._promise;
32460 }
32461 let wasAlreadyErroring = false;
32462 if (state === 'erroring') {
32463 wasAlreadyErroring = true;
32464 // reason will not be used, so don't keep a reference to it.
32465 reason = undefined;
32466 }
32467 const promise = newPromise((resolve, reject) => {
32468 stream._pendingAbortRequest = {
32469 _promise: undefined,
32470 _resolve: resolve,
32471 _reject: reject,
32472 _reason: reason,
32473 _wasAlreadyErroring: wasAlreadyErroring
32474 };
32475 });
32476 stream._pendingAbortRequest._promise = promise;
32477 if (!wasAlreadyErroring) {
32478 WritableStreamStartErroring(stream, reason);
32479 }
32480 return promise;
32481 }
32482 function WritableStreamClose(stream) {
32483 const state = stream._state;
32484 if (state === 'closed' || state === 'errored') {
32485 return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
32486 }
32487 const promise = newPromise((resolve, reject) => {
32488 const closeRequest = {
32489 _resolve: resolve,
32490 _reject: reject
32491 };
32492 stream._closeRequest = closeRequest;
32493 });
32494 const writer = stream._writer;
32495 if (writer !== undefined && stream._backpressure && state === 'writable') {
32496 defaultWriterReadyPromiseResolve(writer);
32497 }
32498 WritableStreamDefaultControllerClose(stream._writableStreamController);
32499 return promise;
32500 }
32501 // WritableStream API exposed for controllers.
32502 function WritableStreamAddWriteRequest(stream) {
32503 const promise = newPromise((resolve, reject) => {
32504 const writeRequest = {
32505 _resolve: resolve,
32506 _reject: reject
32507 };
32508 stream._writeRequests.push(writeRequest);
32509 });
32510 return promise;
32511 }
32512 function WritableStreamDealWithRejection(stream, error) {
32513 const state = stream._state;
32514 if (state === 'writable') {
32515 WritableStreamStartErroring(stream, error);
32516 return;
32517 }
32518 WritableStreamFinishErroring(stream);
32519 }
32520 function WritableStreamStartErroring(stream, reason) {
32521 const controller = stream._writableStreamController;
32522 stream._state = 'erroring';
32523 stream._storedError = reason;
32524 const writer = stream._writer;
32525 if (writer !== undefined) {
32526 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
32527 }
32528 if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {
32529 WritableStreamFinishErroring(stream);
32530 }
32531 }
32532 function WritableStreamFinishErroring(stream) {
32533 stream._state = 'errored';
32534 stream._writableStreamController[ErrorSteps]();
32535 const storedError = stream._storedError;
32536 stream._writeRequests.forEach(writeRequest => {
32537 writeRequest._reject(storedError);
32538 });
32539 stream._writeRequests = new SimpleQueue();
32540 if (stream._pendingAbortRequest === undefined) {
32541 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
32542 return;
32543 }
32544 const abortRequest = stream._pendingAbortRequest;
32545 stream._pendingAbortRequest = undefined;
32546 if (abortRequest._wasAlreadyErroring) {
32547 abortRequest._reject(storedError);
32548 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
32549 return;
32550 }
32551 const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
32552 uponPromise(promise, () => {
32553 abortRequest._resolve();
32554 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
32555 }, (reason) => {
32556 abortRequest._reject(reason);
32557 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
32558 });
32559 }
32560 function WritableStreamFinishInFlightWrite(stream) {
32561 stream._inFlightWriteRequest._resolve(undefined);
32562 stream._inFlightWriteRequest = undefined;
32563 }
32564 function WritableStreamFinishInFlightWriteWithError(stream, error) {
32565 stream._inFlightWriteRequest._reject(error);
32566 stream._inFlightWriteRequest = undefined;
32567 WritableStreamDealWithRejection(stream, error);
32568 }
32569 function WritableStreamFinishInFlightClose(stream) {
32570 stream._inFlightCloseRequest._resolve(undefined);
32571 stream._inFlightCloseRequest = undefined;
32572 const state = stream._state;
32573 if (state === 'erroring') {
32574 // The error was too late to do anything, so it is ignored.
32575 stream._storedError = undefined;
32576 if (stream._pendingAbortRequest !== undefined) {
32577 stream._pendingAbortRequest._resolve();
32578 stream._pendingAbortRequest = undefined;
32579 }
32580 }
32581 stream._state = 'closed';
32582 const writer = stream._writer;
32583 if (writer !== undefined) {
32584 defaultWriterClosedPromiseResolve(writer);
32585 }
32586 }
32587 function WritableStreamFinishInFlightCloseWithError(stream, error) {
32588 stream._inFlightCloseRequest._reject(error);
32589 stream._inFlightCloseRequest = undefined;
32590 // Never execute sink abort() after sink close().
32591 if (stream._pendingAbortRequest !== undefined) {
32592 stream._pendingAbortRequest._reject(error);
32593 stream._pendingAbortRequest = undefined;
32594 }
32595 WritableStreamDealWithRejection(stream, error);
32596 }
32597 // TODO(ricea): Fix alphabetical order.
32598 function WritableStreamCloseQueuedOrInFlight(stream) {
32599 if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {
32600 return false;
32601 }
32602 return true;
32603 }
32604 function WritableStreamHasOperationMarkedInFlight(stream) {
32605 if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {
32606 return false;
32607 }
32608 return true;
32609 }
32610 function WritableStreamMarkCloseRequestInFlight(stream) {
32611 stream._inFlightCloseRequest = stream._closeRequest;
32612 stream._closeRequest = undefined;
32613 }
32614 function WritableStreamMarkFirstWriteRequestInFlight(stream) {
32615 stream._inFlightWriteRequest = stream._writeRequests.shift();
32616 }
32617 function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
32618 if (stream._closeRequest !== undefined) {
32619 stream._closeRequest._reject(stream._storedError);
32620 stream._closeRequest = undefined;
32621 }
32622 const writer = stream._writer;
32623 if (writer !== undefined) {
32624 defaultWriterClosedPromiseReject(writer, stream._storedError);
32625 }
32626 }
32627 function WritableStreamUpdateBackpressure(stream, backpressure) {
32628 const writer = stream._writer;
32629 if (writer !== undefined && backpressure !== stream._backpressure) {
32630 if (backpressure) {
32631 defaultWriterReadyPromiseReset(writer);
32632 }
32633 else {
32634 defaultWriterReadyPromiseResolve(writer);
32635 }
32636 }
32637 stream._backpressure = backpressure;
32638 }
32639 /**
32640 * A default writer vended by a {@link WritableStream}.
32641 *
32642 * @public
32643 */
32644 class WritableStreamDefaultWriter {
32645 constructor(stream) {
32646 assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');
32647 assertWritableStream(stream, 'First parameter');
32648 if (IsWritableStreamLocked(stream)) {
32649 throw new TypeError('This stream has already been locked for exclusive writing by another writer');
32650 }
32651 this._ownerWritableStream = stream;
32652 stream._writer = this;
32653 const state = stream._state;
32654 if (state === 'writable') {
32655 if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
32656 defaultWriterReadyPromiseInitialize(this);
32657 }
32658 else {
32659 defaultWriterReadyPromiseInitializeAsResolved(this);
32660 }
32661 defaultWriterClosedPromiseInitialize(this);
32662 }
32663 else if (state === 'erroring') {
32664 defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
32665 defaultWriterClosedPromiseInitialize(this);
32666 }
32667 else if (state === 'closed') {
32668 defaultWriterReadyPromiseInitializeAsResolved(this);
32669 defaultWriterClosedPromiseInitializeAsResolved(this);
32670 }
32671 else {
32672 const storedError = stream._storedError;
32673 defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
32674 defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
32675 }
32676 }
32677 /**
32678 * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
32679 * the writer’s lock is released before the stream finishes closing.
32680 */
32681 get closed() {
32682 if (!IsWritableStreamDefaultWriter(this)) {
32683 return promiseRejectedWith(defaultWriterBrandCheckException('closed'));
32684 }
32685 return this._closedPromise;
32686 }
32687 /**
32688 * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
32689 * A producer can use this information to determine the right amount of data to write.
32690 *
32691 * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
32692 * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
32693 * the writer’s lock is released.
32694 */
32695 get desiredSize() {
32696 if (!IsWritableStreamDefaultWriter(this)) {
32697 throw defaultWriterBrandCheckException('desiredSize');
32698 }
32699 if (this._ownerWritableStream === undefined) {
32700 throw defaultWriterLockException('desiredSize');
32701 }
32702 return WritableStreamDefaultWriterGetDesiredSize(this);
32703 }
32704 /**
32705 * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
32706 * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
32707 * back to zero or below, the getter will return a new promise that stays pending until the next transition.
32708 *
32709 * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
32710 * rejected.
32711 */
32712 get ready() {
32713 if (!IsWritableStreamDefaultWriter(this)) {
32714 return promiseRejectedWith(defaultWriterBrandCheckException('ready'));
32715 }
32716 return this._readyPromise;
32717 }
32718 /**
32719 * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
32720 */
32721 abort(reason = undefined) {
32722 if (!IsWritableStreamDefaultWriter(this)) {
32723 return promiseRejectedWith(defaultWriterBrandCheckException('abort'));
32724 }
32725 if (this._ownerWritableStream === undefined) {
32726 return promiseRejectedWith(defaultWriterLockException('abort'));
32727 }
32728 return WritableStreamDefaultWriterAbort(this, reason);
32729 }
32730 /**
32731 * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
32732 */
32733 close() {
32734 if (!IsWritableStreamDefaultWriter(this)) {
32735 return promiseRejectedWith(defaultWriterBrandCheckException('close'));
32736 }
32737 const stream = this._ownerWritableStream;
32738 if (stream === undefined) {
32739 return promiseRejectedWith(defaultWriterLockException('close'));
32740 }
32741 if (WritableStreamCloseQueuedOrInFlight(stream)) {
32742 return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
32743 }
32744 return WritableStreamDefaultWriterClose(this);
32745 }
32746 /**
32747 * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
32748 * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
32749 * now on; otherwise, the writer will appear closed.
32750 *
32751 * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
32752 * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
32753 * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
32754 * other producers from writing in an interleaved manner.
32755 */
32756 releaseLock() {
32757 if (!IsWritableStreamDefaultWriter(this)) {
32758 throw defaultWriterBrandCheckException('releaseLock');
32759 }
32760 const stream = this._ownerWritableStream;
32761 if (stream === undefined) {
32762 return;
32763 }
32764 WritableStreamDefaultWriterRelease(this);
32765 }
32766 write(chunk = undefined) {
32767 if (!IsWritableStreamDefaultWriter(this)) {
32768 return promiseRejectedWith(defaultWriterBrandCheckException('write'));
32769 }
32770 if (this._ownerWritableStream === undefined) {
32771 return promiseRejectedWith(defaultWriterLockException('write to'));
32772 }
32773 return WritableStreamDefaultWriterWrite(this, chunk);
32774 }
32775 }
32776 Object.defineProperties(WritableStreamDefaultWriter.prototype, {
32777 abort: { enumerable: true },
32778 close: { enumerable: true },
32779 releaseLock: { enumerable: true },
32780 write: { enumerable: true },
32781 closed: { enumerable: true },
32782 desiredSize: { enumerable: true },
32783 ready: { enumerable: true }
32784 });
32785 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
32786 Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
32787 value: 'WritableStreamDefaultWriter',
32788 configurable: true
32789 });
32790 }
32791 // Abstract operations for the WritableStreamDefaultWriter.
32792 function IsWritableStreamDefaultWriter(x) {
32793 if (!typeIsObject(x)) {
32794 return false;
32795 }
32796 if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {
32797 return false;
32798 }
32799 return true;
32800 }
32801 // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.
32802 function WritableStreamDefaultWriterAbort(writer, reason) {
32803 const stream = writer._ownerWritableStream;
32804 return WritableStreamAbort(stream, reason);
32805 }
32806 function WritableStreamDefaultWriterClose(writer) {
32807 const stream = writer._ownerWritableStream;
32808 return WritableStreamClose(stream);
32809 }
32810 function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
32811 const stream = writer._ownerWritableStream;
32812 const state = stream._state;
32813 if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
32814 return promiseResolvedWith(undefined);
32815 }
32816 if (state === 'errored') {
32817 return promiseRejectedWith(stream._storedError);
32818 }
32819 return WritableStreamDefaultWriterClose(writer);
32820 }
32821 function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
32822 if (writer._closedPromiseState === 'pending') {
32823 defaultWriterClosedPromiseReject(writer, error);
32824 }
32825 else {
32826 defaultWriterClosedPromiseResetToRejected(writer, error);
32827 }
32828 }
32829 function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
32830 if (writer._readyPromiseState === 'pending') {
32831 defaultWriterReadyPromiseReject(writer, error);
32832 }
32833 else {
32834 defaultWriterReadyPromiseResetToRejected(writer, error);
32835 }
32836 }
32837 function WritableStreamDefaultWriterGetDesiredSize(writer) {
32838 const stream = writer._ownerWritableStream;
32839 const state = stream._state;
32840 if (state === 'errored' || state === 'erroring') {
32841 return null;
32842 }
32843 if (state === 'closed') {
32844 return 0;
32845 }
32846 return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
32847 }
32848 function WritableStreamDefaultWriterRelease(writer) {
32849 const stream = writer._ownerWritableStream;
32850 const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
32851 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
32852 // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not
32853 // rejected until afterwards. This means that simply testing state will not work.
32854 WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
32855 stream._writer = undefined;
32856 writer._ownerWritableStream = undefined;
32857 }
32858 function WritableStreamDefaultWriterWrite(writer, chunk) {
32859 const stream = writer._ownerWritableStream;
32860 const controller = stream._writableStreamController;
32861 const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
32862 if (stream !== writer._ownerWritableStream) {
32863 return promiseRejectedWith(defaultWriterLockException('write to'));
32864 }
32865 const state = stream._state;
32866 if (state === 'errored') {
32867 return promiseRejectedWith(stream._storedError);
32868 }
32869 if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
32870 return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));
32871 }
32872 if (state === 'erroring') {
32873 return promiseRejectedWith(stream._storedError);
32874 }
32875 const promise = WritableStreamAddWriteRequest(stream);
32876 WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
32877 return promise;
32878 }
32879 const closeSentinel = {};
32880 /**
32881 * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
32882 *
32883 * @public
32884 */
32885 class WritableStreamDefaultController {
32886 constructor() {
32887 throw new TypeError('Illegal constructor');
32888 }
32889 /**
32890 * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
32891 *
32892 * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
32893 * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
32894 * normal lifecycle of interactions with the underlying sink.
32895 */
32896 error(e = undefined) {
32897 if (!IsWritableStreamDefaultController(this)) {
32898 throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');
32899 }
32900 const state = this._controlledWritableStream._state;
32901 if (state !== 'writable') {
32902 // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so
32903 // just treat it as a no-op.
32904 return;
32905 }
32906 WritableStreamDefaultControllerError(this, e);
32907 }
32908 /** @internal */
32909 [AbortSteps](reason) {
32910 const result = this._abortAlgorithm(reason);
32911 WritableStreamDefaultControllerClearAlgorithms(this);
32912 return result;
32913 }
32914 /** @internal */
32915 [ErrorSteps]() {
32916 ResetQueue(this);
32917 }
32918 }
32919 Object.defineProperties(WritableStreamDefaultController.prototype, {
32920 error: { enumerable: true }
32921 });
32922 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
32923 Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
32924 value: 'WritableStreamDefaultController',
32925 configurable: true
32926 });
32927 }
32928 // Abstract operations implementing interface required by the WritableStream.
32929 function IsWritableStreamDefaultController(x) {
32930 if (!typeIsObject(x)) {
32931 return false;
32932 }
32933 if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {
32934 return false;
32935 }
32936 return true;
32937 }
32938 function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
32939 controller._controlledWritableStream = stream;
32940 stream._writableStreamController = controller;
32941 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
32942 controller._queue = undefined;
32943 controller._queueTotalSize = undefined;
32944 ResetQueue(controller);
32945 controller._started = false;
32946 controller._strategySizeAlgorithm = sizeAlgorithm;
32947 controller._strategyHWM = highWaterMark;
32948 controller._writeAlgorithm = writeAlgorithm;
32949 controller._closeAlgorithm = closeAlgorithm;
32950 controller._abortAlgorithm = abortAlgorithm;
32951 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
32952 WritableStreamUpdateBackpressure(stream, backpressure);
32953 const startResult = startAlgorithm();
32954 const startPromise = promiseResolvedWith(startResult);
32955 uponPromise(startPromise, () => {
32956 controller._started = true;
32957 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
32958 }, r => {
32959 controller._started = true;
32960 WritableStreamDealWithRejection(stream, r);
32961 });
32962 }
32963 function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
32964 const controller = Object.create(WritableStreamDefaultController.prototype);
32965 let startAlgorithm = () => undefined;
32966 let writeAlgorithm = () => promiseResolvedWith(undefined);
32967 let closeAlgorithm = () => promiseResolvedWith(undefined);
32968 let abortAlgorithm = () => promiseResolvedWith(undefined);
32969 if (underlyingSink.start !== undefined) {
32970 startAlgorithm = () => underlyingSink.start(controller);
32971 }
32972 if (underlyingSink.write !== undefined) {
32973 writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
32974 }
32975 if (underlyingSink.close !== undefined) {
32976 closeAlgorithm = () => underlyingSink.close();
32977 }
32978 if (underlyingSink.abort !== undefined) {
32979 abortAlgorithm = reason => underlyingSink.abort(reason);
32980 }
32981 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
32982 }
32983 // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
32984 function WritableStreamDefaultControllerClearAlgorithms(controller) {
32985 controller._writeAlgorithm = undefined;
32986 controller._closeAlgorithm = undefined;
32987 controller._abortAlgorithm = undefined;
32988 controller._strategySizeAlgorithm = undefined;
32989 }
32990 function WritableStreamDefaultControllerClose(controller) {
32991 EnqueueValueWithSize(controller, closeSentinel, 0);
32992 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
32993 }
32994 function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
32995 try {
32996 return controller._strategySizeAlgorithm(chunk);
32997 }
32998 catch (chunkSizeE) {
32999 WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
33000 return 1;
33001 }
33002 }
33003 function WritableStreamDefaultControllerGetDesiredSize(controller) {
33004 return controller._strategyHWM - controller._queueTotalSize;
33005 }
33006 function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
33007 try {
33008 EnqueueValueWithSize(controller, chunk, chunkSize);
33009 }
33010 catch (enqueueE) {
33011 WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
33012 return;
33013 }
33014 const stream = controller._controlledWritableStream;
33015 if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {
33016 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
33017 WritableStreamUpdateBackpressure(stream, backpressure);
33018 }
33019 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
33020 }
33021 // Abstract operations for the WritableStreamDefaultController.
33022 function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
33023 const stream = controller._controlledWritableStream;
33024 if (!controller._started) {
33025 return;
33026 }
33027 if (stream._inFlightWriteRequest !== undefined) {
33028 return;
33029 }
33030 const state = stream._state;
33031 if (state === 'erroring') {
33032 WritableStreamFinishErroring(stream);
33033 return;
33034 }
33035 if (controller._queue.length === 0) {
33036 return;
33037 }
33038 const value = PeekQueueValue(controller);
33039 if (value === closeSentinel) {
33040 WritableStreamDefaultControllerProcessClose(controller);
33041 }
33042 else {
33043 WritableStreamDefaultControllerProcessWrite(controller, value);
33044 }
33045 }
33046 function WritableStreamDefaultControllerErrorIfNeeded(controller, error) {
33047 if (controller._controlledWritableStream._state === 'writable') {
33048 WritableStreamDefaultControllerError(controller, error);
33049 }
33050 }
33051 function WritableStreamDefaultControllerProcessClose(controller) {
33052 const stream = controller._controlledWritableStream;
33053 WritableStreamMarkCloseRequestInFlight(stream);
33054 DequeueValue(controller);
33055 const sinkClosePromise = controller._closeAlgorithm();
33056 WritableStreamDefaultControllerClearAlgorithms(controller);
33057 uponPromise(sinkClosePromise, () => {
33058 WritableStreamFinishInFlightClose(stream);
33059 }, reason => {
33060 WritableStreamFinishInFlightCloseWithError(stream, reason);
33061 });
33062 }
33063 function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
33064 const stream = controller._controlledWritableStream;
33065 WritableStreamMarkFirstWriteRequestInFlight(stream);
33066 const sinkWritePromise = controller._writeAlgorithm(chunk);
33067 uponPromise(sinkWritePromise, () => {
33068 WritableStreamFinishInFlightWrite(stream);
33069 const state = stream._state;
33070 DequeueValue(controller);
33071 if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {
33072 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
33073 WritableStreamUpdateBackpressure(stream, backpressure);
33074 }
33075 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
33076 }, reason => {
33077 if (stream._state === 'writable') {
33078 WritableStreamDefaultControllerClearAlgorithms(controller);
33079 }
33080 WritableStreamFinishInFlightWriteWithError(stream, reason);
33081 });
33082 }
33083 function WritableStreamDefaultControllerGetBackpressure(controller) {
33084 const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
33085 return desiredSize <= 0;
33086 }
33087 // A client of WritableStreamDefaultController may use these functions directly to bypass state check.
33088 function WritableStreamDefaultControllerError(controller, error) {
33089 const stream = controller._controlledWritableStream;
33090 WritableStreamDefaultControllerClearAlgorithms(controller);
33091 WritableStreamStartErroring(stream, error);
33092 }
33093 // Helper functions for the WritableStream.
33094 function streamBrandCheckException$2(name) {
33095 return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
33096 }
33097 // Helper functions for the WritableStreamDefaultWriter.
33098 function defaultWriterBrandCheckException(name) {
33099 return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
33100 }
33101 function defaultWriterLockException(name) {
33102 return new TypeError('Cannot ' + name + ' a stream using a released writer');
33103 }
33104 function defaultWriterClosedPromiseInitialize(writer) {
33105 writer._closedPromise = newPromise((resolve, reject) => {
33106 writer._closedPromise_resolve = resolve;
33107 writer._closedPromise_reject = reject;
33108 writer._closedPromiseState = 'pending';
33109 });
33110 }
33111 function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
33112 defaultWriterClosedPromiseInitialize(writer);
33113 defaultWriterClosedPromiseReject(writer, reason);
33114 }
33115 function defaultWriterClosedPromiseInitializeAsResolved(writer) {
33116 defaultWriterClosedPromiseInitialize(writer);
33117 defaultWriterClosedPromiseResolve(writer);
33118 }
33119 function defaultWriterClosedPromiseReject(writer, reason) {
33120 if (writer._closedPromise_reject === undefined) {
33121 return;
33122 }
33123 setPromiseIsHandledToTrue(writer._closedPromise);
33124 writer._closedPromise_reject(reason);
33125 writer._closedPromise_resolve = undefined;
33126 writer._closedPromise_reject = undefined;
33127 writer._closedPromiseState = 'rejected';
33128 }
33129 function defaultWriterClosedPromiseResetToRejected(writer, reason) {
33130 defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
33131 }
33132 function defaultWriterClosedPromiseResolve(writer) {
33133 if (writer._closedPromise_resolve === undefined) {
33134 return;
33135 }
33136 writer._closedPromise_resolve(undefined);
33137 writer._closedPromise_resolve = undefined;
33138 writer._closedPromise_reject = undefined;
33139 writer._closedPromiseState = 'resolved';
33140 }
33141 function defaultWriterReadyPromiseInitialize(writer) {
33142 writer._readyPromise = newPromise((resolve, reject) => {
33143 writer._readyPromise_resolve = resolve;
33144 writer._readyPromise_reject = reject;
33145 });
33146 writer._readyPromiseState = 'pending';
33147 }
33148 function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
33149 defaultWriterReadyPromiseInitialize(writer);
33150 defaultWriterReadyPromiseReject(writer, reason);
33151 }
33152 function defaultWriterReadyPromiseInitializeAsResolved(writer) {
33153 defaultWriterReadyPromiseInitialize(writer);
33154 defaultWriterReadyPromiseResolve(writer);
33155 }
33156 function defaultWriterReadyPromiseReject(writer, reason) {
33157 if (writer._readyPromise_reject === undefined) {
33158 return;
33159 }
33160 setPromiseIsHandledToTrue(writer._readyPromise);
33161 writer._readyPromise_reject(reason);
33162 writer._readyPromise_resolve = undefined;
33163 writer._readyPromise_reject = undefined;
33164 writer._readyPromiseState = 'rejected';
33165 }
33166 function defaultWriterReadyPromiseReset(writer) {
33167 defaultWriterReadyPromiseInitialize(writer);
33168 }
33169 function defaultWriterReadyPromiseResetToRejected(writer, reason) {
33170 defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
33171 }
33172 function defaultWriterReadyPromiseResolve(writer) {
33173 if (writer._readyPromise_resolve === undefined) {
33174 return;
33175 }
33176 writer._readyPromise_resolve(undefined);
33177 writer._readyPromise_resolve = undefined;
33178 writer._readyPromise_reject = undefined;
33179 writer._readyPromiseState = 'fulfilled';
33180 }
33181
33182 function isAbortSignal(value) {
33183 if (typeof value !== 'object' || value === null) {
33184 return false;
33185 }
33186 try {
33187 return typeof value.aborted === 'boolean';
33188 }
33189 catch (_a) {
33190 // AbortSignal.prototype.aborted throws if its brand check fails
33191 return false;
33192 }
33193 }
33194
33195 /// <reference lib="dom" />
33196 const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;
33197
33198 /// <reference types="node" />
33199 function isDOMExceptionConstructor(ctor) {
33200 if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
33201 return false;
33202 }
33203 try {
33204 new ctor();
33205 return true;
33206 }
33207 catch (_a) {
33208 return false;
33209 }
33210 }
33211 function createDOMExceptionPolyfill() {
33212 // eslint-disable-next-line no-shadow
33213 const ctor = function DOMException(message, name) {
33214 this.message = message || '';
33215 this.name = name || 'Error';
33216 if (Error.captureStackTrace) {
33217 Error.captureStackTrace(this, this.constructor);
33218 }
33219 };
33220 ctor.prototype = Object.create(Error.prototype);
33221 Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
33222 return ctor;
33223 }
33224 // eslint-disable-next-line no-redeclare
33225 const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();
33226
33227 function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
33228 const reader = AcquireReadableStreamDefaultReader(source);
33229 const writer = AcquireWritableStreamDefaultWriter(dest);
33230 source._disturbed = true;
33231 let shuttingDown = false;
33232 // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.
33233 let currentWrite = promiseResolvedWith(undefined);
33234 return newPromise((resolve, reject) => {
33235 let abortAlgorithm;
33236 if (signal !== undefined) {
33237 abortAlgorithm = () => {
33238 const error = new DOMException$1('Aborted', 'AbortError');
33239 const actions = [];
33240 if (!preventAbort) {
33241 actions.push(() => {
33242 if (dest._state === 'writable') {
33243 return WritableStreamAbort(dest, error);
33244 }
33245 return promiseResolvedWith(undefined);
33246 });
33247 }
33248 if (!preventCancel) {
33249 actions.push(() => {
33250 if (source._state === 'readable') {
33251 return ReadableStreamCancel(source, error);
33252 }
33253 return promiseResolvedWith(undefined);
33254 });
33255 }
33256 shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);
33257 };
33258 if (signal.aborted) {
33259 abortAlgorithm();
33260 return;
33261 }
33262 signal.addEventListener('abort', abortAlgorithm);
33263 }
33264 // Using reader and writer, read all chunks from this and write them to dest
33265 // - Backpressure must be enforced
33266 // - Shutdown must stop all activity
33267 function pipeLoop() {
33268 return newPromise((resolveLoop, rejectLoop) => {
33269 function next(done) {
33270 if (done) {
33271 resolveLoop();
33272 }
33273 else {
33274 // Use `PerformPromiseThen` instead of `uponPromise` to avoid
33275 // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers
33276 PerformPromiseThen(pipeStep(), next, rejectLoop);
33277 }
33278 }
33279 next(false);
33280 });
33281 }
33282 function pipeStep() {
33283 if (shuttingDown) {
33284 return promiseResolvedWith(true);
33285 }
33286 return PerformPromiseThen(writer._readyPromise, () => {
33287 return newPromise((resolveRead, rejectRead) => {
33288 ReadableStreamDefaultReaderRead(reader, {
33289 _chunkSteps: chunk => {
33290 currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);
33291 resolveRead(false);
33292 },
33293 _closeSteps: () => resolveRead(true),
33294 _errorSteps: rejectRead
33295 });
33296 });
33297 });
33298 }
33299 // Errors must be propagated forward
33300 isOrBecomesErrored(source, reader._closedPromise, storedError => {
33301 if (!preventAbort) {
33302 shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
33303 }
33304 else {
33305 shutdown(true, storedError);
33306 }
33307 });
33308 // Errors must be propagated backward
33309 isOrBecomesErrored(dest, writer._closedPromise, storedError => {
33310 if (!preventCancel) {
33311 shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
33312 }
33313 else {
33314 shutdown(true, storedError);
33315 }
33316 });
33317 // Closing must be propagated forward
33318 isOrBecomesClosed(source, reader._closedPromise, () => {
33319 if (!preventClose) {
33320 shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
33321 }
33322 else {
33323 shutdown();
33324 }
33325 });
33326 // Closing must be propagated backward
33327 if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {
33328 const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');
33329 if (!preventCancel) {
33330 shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
33331 }
33332 else {
33333 shutdown(true, destClosed);
33334 }
33335 }
33336 setPromiseIsHandledToTrue(pipeLoop());
33337 function waitForWritesToFinish() {
33338 // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait
33339 // for that too.
33340 const oldCurrentWrite = currentWrite;
33341 return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);
33342 }
33343 function isOrBecomesErrored(stream, promise, action) {
33344 if (stream._state === 'errored') {
33345 action(stream._storedError);
33346 }
33347 else {
33348 uponRejection(promise, action);
33349 }
33350 }
33351 function isOrBecomesClosed(stream, promise, action) {
33352 if (stream._state === 'closed') {
33353 action();
33354 }
33355 else {
33356 uponFulfillment(promise, action);
33357 }
33358 }
33359 function shutdownWithAction(action, originalIsError, originalError) {
33360 if (shuttingDown) {
33361 return;
33362 }
33363 shuttingDown = true;
33364 if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
33365 uponFulfillment(waitForWritesToFinish(), doTheRest);
33366 }
33367 else {
33368 doTheRest();
33369 }
33370 function doTheRest() {
33371 uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
33372 }
33373 }
33374 function shutdown(isError, error) {
33375 if (shuttingDown) {
33376 return;
33377 }
33378 shuttingDown = true;
33379 if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
33380 uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));
33381 }
33382 else {
33383 finalize(isError, error);
33384 }
33385 }
33386 function finalize(isError, error) {
33387 WritableStreamDefaultWriterRelease(writer);
33388 ReadableStreamReaderGenericRelease(reader);
33389 if (signal !== undefined) {
33390 signal.removeEventListener('abort', abortAlgorithm);
33391 }
33392 if (isError) {
33393 reject(error);
33394 }
33395 else {
33396 resolve(undefined);
33397 }
33398 }
33399 });
33400 }
33401
33402 /**
33403 * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
33404 *
33405 * @public
33406 */
33407 class ReadableStreamDefaultController {
33408 constructor() {
33409 throw new TypeError('Illegal constructor');
33410 }
33411 /**
33412 * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
33413 * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
33414 */
33415 get desiredSize() {
33416 if (!IsReadableStreamDefaultController(this)) {
33417 throw defaultControllerBrandCheckException$1('desiredSize');
33418 }
33419 return ReadableStreamDefaultControllerGetDesiredSize(this);
33420 }
33421 /**
33422 * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
33423 * the stream, but once those are read, the stream will become closed.
33424 */
33425 close() {
33426 if (!IsReadableStreamDefaultController(this)) {
33427 throw defaultControllerBrandCheckException$1('close');
33428 }
33429 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
33430 throw new TypeError('The stream is not in a state that permits close');
33431 }
33432 ReadableStreamDefaultControllerClose(this);
33433 }
33434 enqueue(chunk = undefined) {
33435 if (!IsReadableStreamDefaultController(this)) {
33436 throw defaultControllerBrandCheckException$1('enqueue');
33437 }
33438 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
33439 throw new TypeError('The stream is not in a state that permits enqueue');
33440 }
33441 return ReadableStreamDefaultControllerEnqueue(this, chunk);
33442 }
33443 /**
33444 * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
33445 */
33446 error(e = undefined) {
33447 if (!IsReadableStreamDefaultController(this)) {
33448 throw defaultControllerBrandCheckException$1('error');
33449 }
33450 ReadableStreamDefaultControllerError(this, e);
33451 }
33452 /** @internal */
33453 [CancelSteps](reason) {
33454 ResetQueue(this);
33455 const result = this._cancelAlgorithm(reason);
33456 ReadableStreamDefaultControllerClearAlgorithms(this);
33457 return result;
33458 }
33459 /** @internal */
33460 [PullSteps](readRequest) {
33461 const stream = this._controlledReadableStream;
33462 if (this._queue.length > 0) {
33463 const chunk = DequeueValue(this);
33464 if (this._closeRequested && this._queue.length === 0) {
33465 ReadableStreamDefaultControllerClearAlgorithms(this);
33466 ReadableStreamClose(stream);
33467 }
33468 else {
33469 ReadableStreamDefaultControllerCallPullIfNeeded(this);
33470 }
33471 readRequest._chunkSteps(chunk);
33472 }
33473 else {
33474 ReadableStreamAddReadRequest(stream, readRequest);
33475 ReadableStreamDefaultControllerCallPullIfNeeded(this);
33476 }
33477 }
33478 }
33479 Object.defineProperties(ReadableStreamDefaultController.prototype, {
33480 close: { enumerable: true },
33481 enqueue: { enumerable: true },
33482 error: { enumerable: true },
33483 desiredSize: { enumerable: true }
33484 });
33485 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
33486 Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
33487 value: 'ReadableStreamDefaultController',
33488 configurable: true
33489 });
33490 }
33491 // Abstract operations for the ReadableStreamDefaultController.
33492 function IsReadableStreamDefaultController(x) {
33493 if (!typeIsObject(x)) {
33494 return false;
33495 }
33496 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {
33497 return false;
33498 }
33499 return true;
33500 }
33501 function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
33502 const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
33503 if (!shouldPull) {
33504 return;
33505 }
33506 if (controller._pulling) {
33507 controller._pullAgain = true;
33508 return;
33509 }
33510 controller._pulling = true;
33511 const pullPromise = controller._pullAlgorithm();
33512 uponPromise(pullPromise, () => {
33513 controller._pulling = false;
33514 if (controller._pullAgain) {
33515 controller._pullAgain = false;
33516 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
33517 }
33518 }, e => {
33519 ReadableStreamDefaultControllerError(controller, e);
33520 });
33521 }
33522 function ReadableStreamDefaultControllerShouldCallPull(controller) {
33523 const stream = controller._controlledReadableStream;
33524 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
33525 return false;
33526 }
33527 if (!controller._started) {
33528 return false;
33529 }
33530 if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
33531 return true;
33532 }
33533 const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
33534 if (desiredSize > 0) {
33535 return true;
33536 }
33537 return false;
33538 }
33539 function ReadableStreamDefaultControllerClearAlgorithms(controller) {
33540 controller._pullAlgorithm = undefined;
33541 controller._cancelAlgorithm = undefined;
33542 controller._strategySizeAlgorithm = undefined;
33543 }
33544 // A client of ReadableStreamDefaultController may use these functions directly to bypass state check.
33545 function ReadableStreamDefaultControllerClose(controller) {
33546 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
33547 return;
33548 }
33549 const stream = controller._controlledReadableStream;
33550 controller._closeRequested = true;
33551 if (controller._queue.length === 0) {
33552 ReadableStreamDefaultControllerClearAlgorithms(controller);
33553 ReadableStreamClose(stream);
33554 }
33555 }
33556 function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
33557 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
33558 return;
33559 }
33560 const stream = controller._controlledReadableStream;
33561 if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
33562 ReadableStreamFulfillReadRequest(stream, chunk, false);
33563 }
33564 else {
33565 let chunkSize;
33566 try {
33567 chunkSize = controller._strategySizeAlgorithm(chunk);
33568 }
33569 catch (chunkSizeE) {
33570 ReadableStreamDefaultControllerError(controller, chunkSizeE);
33571 throw chunkSizeE;
33572 }
33573 try {
33574 EnqueueValueWithSize(controller, chunk, chunkSize);
33575 }
33576 catch (enqueueE) {
33577 ReadableStreamDefaultControllerError(controller, enqueueE);
33578 throw enqueueE;
33579 }
33580 }
33581 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
33582 }
33583 function ReadableStreamDefaultControllerError(controller, e) {
33584 const stream = controller._controlledReadableStream;
33585 if (stream._state !== 'readable') {
33586 return;
33587 }
33588 ResetQueue(controller);
33589 ReadableStreamDefaultControllerClearAlgorithms(controller);
33590 ReadableStreamError(stream, e);
33591 }
33592 function ReadableStreamDefaultControllerGetDesiredSize(controller) {
33593 const state = controller._controlledReadableStream._state;
33594 if (state === 'errored') {
33595 return null;
33596 }
33597 if (state === 'closed') {
33598 return 0;
33599 }
33600 return controller._strategyHWM - controller._queueTotalSize;
33601 }
33602 // This is used in the implementation of TransformStream.
33603 function ReadableStreamDefaultControllerHasBackpressure(controller) {
33604 if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
33605 return false;
33606 }
33607 return true;
33608 }
33609 function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
33610 const state = controller._controlledReadableStream._state;
33611 if (!controller._closeRequested && state === 'readable') {
33612 return true;
33613 }
33614 return false;
33615 }
33616 function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
33617 controller._controlledReadableStream = stream;
33618 controller._queue = undefined;
33619 controller._queueTotalSize = undefined;
33620 ResetQueue(controller);
33621 controller._started = false;
33622 controller._closeRequested = false;
33623 controller._pullAgain = false;
33624 controller._pulling = false;
33625 controller._strategySizeAlgorithm = sizeAlgorithm;
33626 controller._strategyHWM = highWaterMark;
33627 controller._pullAlgorithm = pullAlgorithm;
33628 controller._cancelAlgorithm = cancelAlgorithm;
33629 stream._readableStreamController = controller;
33630 const startResult = startAlgorithm();
33631 uponPromise(promiseResolvedWith(startResult), () => {
33632 controller._started = true;
33633 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
33634 }, r => {
33635 ReadableStreamDefaultControllerError(controller, r);
33636 });
33637 }
33638 function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
33639 const controller = Object.create(ReadableStreamDefaultController.prototype);
33640 let startAlgorithm = () => undefined;
33641 let pullAlgorithm = () => promiseResolvedWith(undefined);
33642 let cancelAlgorithm = () => promiseResolvedWith(undefined);
33643 if (underlyingSource.start !== undefined) {
33644 startAlgorithm = () => underlyingSource.start(controller);
33645 }
33646 if (underlyingSource.pull !== undefined) {
33647 pullAlgorithm = () => underlyingSource.pull(controller);
33648 }
33649 if (underlyingSource.cancel !== undefined) {
33650 cancelAlgorithm = reason => underlyingSource.cancel(reason);
33651 }
33652 SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
33653 }
33654 // Helper functions for the ReadableStreamDefaultController.
33655 function defaultControllerBrandCheckException$1(name) {
33656 return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
33657 }
33658
33659 function ReadableStreamTee(stream, cloneForBranch2) {
33660 const reader = AcquireReadableStreamDefaultReader(stream);
33661 let reading = false;
33662 let canceled1 = false;
33663 let canceled2 = false;
33664 let reason1;
33665 let reason2;
33666 let branch1;
33667 let branch2;
33668 let resolveCancelPromise;
33669 const cancelPromise = newPromise(resolve => {
33670 resolveCancelPromise = resolve;
33671 });
33672 function pullAlgorithm() {
33673 if (reading) {
33674 return promiseResolvedWith(undefined);
33675 }
33676 reading = true;
33677 const readRequest = {
33678 _chunkSteps: value => {
33679 // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
33680 // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
33681 // successful synchronously-available reads get ahead of asynchronously-available errors.
33682 queueMicrotask(() => {
33683 reading = false;
33684 const value1 = value;
33685 const value2 = value;
33686 // There is no way to access the cloning code right now in the reference implementation.
33687 // If we add one then we'll need an implementation for serializable objects.
33688 // if (!canceled2 && cloneForBranch2) {
33689 // value2 = StructuredDeserialize(StructuredSerialize(value2));
33690 // }
33691 if (!canceled1) {
33692 ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, value1);
33693 }
33694 if (!canceled2) {
33695 ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, value2);
33696 }
33697 });
33698 },
33699 _closeSteps: () => {
33700 reading = false;
33701 if (!canceled1) {
33702 ReadableStreamDefaultControllerClose(branch1._readableStreamController);
33703 }
33704 if (!canceled2) {
33705 ReadableStreamDefaultControllerClose(branch2._readableStreamController);
33706 }
33707 if (!canceled1 || !canceled2) {
33708 resolveCancelPromise(undefined);
33709 }
33710 },
33711 _errorSteps: () => {
33712 reading = false;
33713 }
33714 };
33715 ReadableStreamDefaultReaderRead(reader, readRequest);
33716 return promiseResolvedWith(undefined);
33717 }
33718 function cancel1Algorithm(reason) {
33719 canceled1 = true;
33720 reason1 = reason;
33721 if (canceled2) {
33722 const compositeReason = CreateArrayFromList([reason1, reason2]);
33723 const cancelResult = ReadableStreamCancel(stream, compositeReason);
33724 resolveCancelPromise(cancelResult);
33725 }
33726 return cancelPromise;
33727 }
33728 function cancel2Algorithm(reason) {
33729 canceled2 = true;
33730 reason2 = reason;
33731 if (canceled1) {
33732 const compositeReason = CreateArrayFromList([reason1, reason2]);
33733 const cancelResult = ReadableStreamCancel(stream, compositeReason);
33734 resolveCancelPromise(cancelResult);
33735 }
33736 return cancelPromise;
33737 }
33738 function startAlgorithm() {
33739 // do nothing
33740 }
33741 branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
33742 branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
33743 uponRejection(reader._closedPromise, (r) => {
33744 ReadableStreamDefaultControllerError(branch1._readableStreamController, r);
33745 ReadableStreamDefaultControllerError(branch2._readableStreamController, r);
33746 if (!canceled1 || !canceled2) {
33747 resolveCancelPromise(undefined);
33748 }
33749 });
33750 return [branch1, branch2];
33751 }
33752
33753 function convertUnderlyingDefaultOrByteSource(source, context) {
33754 assertDictionary(source, context);
33755 const original = source;
33756 const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
33757 const cancel = original === null || original === void 0 ? void 0 : original.cancel;
33758 const pull = original === null || original === void 0 ? void 0 : original.pull;
33759 const start = original === null || original === void 0 ? void 0 : original.start;
33760 const type = original === null || original === void 0 ? void 0 : original.type;
33761 return {
33762 autoAllocateChunkSize: autoAllocateChunkSize === undefined ?
33763 undefined :
33764 convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),
33765 cancel: cancel === undefined ?
33766 undefined :
33767 convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),
33768 pull: pull === undefined ?
33769 undefined :
33770 convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),
33771 start: start === undefined ?
33772 undefined :
33773 convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),
33774 type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)
33775 };
33776 }
33777 function convertUnderlyingSourceCancelCallback(fn, original, context) {
33778 assertFunction(fn, context);
33779 return (reason) => promiseCall(fn, original, [reason]);
33780 }
33781 function convertUnderlyingSourcePullCallback(fn, original, context) {
33782 assertFunction(fn, context);
33783 return (controller) => promiseCall(fn, original, [controller]);
33784 }
33785 function convertUnderlyingSourceStartCallback(fn, original, context) {
33786 assertFunction(fn, context);
33787 return (controller) => reflectCall(fn, original, [controller]);
33788 }
33789 function convertReadableStreamType(type, context) {
33790 type = `${type}`;
33791 if (type !== 'bytes') {
33792 throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);
33793 }
33794 return type;
33795 }
33796
33797 function convertReaderOptions(options, context) {
33798 assertDictionary(options, context);
33799 const mode = options === null || options === void 0 ? void 0 : options.mode;
33800 return {
33801 mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
33802 };
33803 }
33804 function convertReadableStreamReaderMode(mode, context) {
33805 mode = `${mode}`;
33806 if (mode !== 'byob') {
33807 throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
33808 }
33809 return mode;
33810 }
33811
33812 function convertIteratorOptions(options, context) {
33813 assertDictionary(options, context);
33814 const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
33815 return { preventCancel: Boolean(preventCancel) };
33816 }
33817
33818 function convertPipeOptions(options, context) {
33819 assertDictionary(options, context);
33820 const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;
33821 const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
33822 const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;
33823 const signal = options === null || options === void 0 ? void 0 : options.signal;
33824 if (signal !== undefined) {
33825 assertAbortSignal(signal, `${context} has member 'signal' that`);
33826 }
33827 return {
33828 preventAbort: Boolean(preventAbort),
33829 preventCancel: Boolean(preventCancel),
33830 preventClose: Boolean(preventClose),
33831 signal
33832 };
33833 }
33834 function assertAbortSignal(signal, context) {
33835 if (!isAbortSignal(signal)) {
33836 throw new TypeError(`${context} is not an AbortSignal.`);
33837 }
33838 }
33839
33840 function convertReadableWritablePair(pair, context) {
33841 assertDictionary(pair, context);
33842 const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
33843 assertRequiredField(readable, 'readable', 'ReadableWritablePair');
33844 assertReadableStream(readable, `${context} has member 'readable' that`);
33845 const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
33846 assertRequiredField(writable, 'writable', 'ReadableWritablePair');
33847 assertWritableStream(writable, `${context} has member 'writable' that`);
33848 return { readable, writable };
33849 }
33850
33851 /**
33852 * A readable stream represents a source of data, from which you can read.
33853 *
33854 * @public
33855 */
33856 class ReadableStream$1 {
33857 constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
33858 if (rawUnderlyingSource === undefined) {
33859 rawUnderlyingSource = null;
33860 }
33861 else {
33862 assertObject(rawUnderlyingSource, 'First parameter');
33863 }
33864 const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
33865 const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');
33866 InitializeReadableStream(this);
33867 if (underlyingSource.type === 'bytes') {
33868 if (strategy.size !== undefined) {
33869 throw new RangeError('The strategy for a byte stream cannot have a size function');
33870 }
33871 const highWaterMark = ExtractHighWaterMark(strategy, 0);
33872 SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
33873 }
33874 else {
33875 const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
33876 const highWaterMark = ExtractHighWaterMark(strategy, 1);
33877 SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
33878 }
33879 }
33880 /**
33881 * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
33882 */
33883 get locked() {
33884 if (!IsReadableStream(this)) {
33885 throw streamBrandCheckException$1('locked');
33886 }
33887 return IsReadableStreamLocked(this);
33888 }
33889 /**
33890 * Cancels the stream, signaling a loss of interest in the stream by a consumer.
33891 *
33892 * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
33893 * method, which might or might not use it.
33894 */
33895 cancel(reason = undefined) {
33896 if (!IsReadableStream(this)) {
33897 return promiseRejectedWith(streamBrandCheckException$1('cancel'));
33898 }
33899 if (IsReadableStreamLocked(this)) {
33900 return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));
33901 }
33902 return ReadableStreamCancel(this, reason);
33903 }
33904 getReader(rawOptions = undefined) {
33905 if (!IsReadableStream(this)) {
33906 throw streamBrandCheckException$1('getReader');
33907 }
33908 const options = convertReaderOptions(rawOptions, 'First parameter');
33909 if (options.mode === undefined) {
33910 return AcquireReadableStreamDefaultReader(this);
33911 }
33912 return AcquireReadableStreamBYOBReader(this);
33913 }
33914 pipeThrough(rawTransform, rawOptions = {}) {
33915 if (!IsReadableStream(this)) {
33916 throw streamBrandCheckException$1('pipeThrough');
33917 }
33918 assertRequiredArgument(rawTransform, 1, 'pipeThrough');
33919 const transform = convertReadableWritablePair(rawTransform, 'First parameter');
33920 const options = convertPipeOptions(rawOptions, 'Second parameter');
33921 if (IsReadableStreamLocked(this)) {
33922 throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');
33923 }
33924 if (IsWritableStreamLocked(transform.writable)) {
33925 throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');
33926 }
33927 const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
33928 setPromiseIsHandledToTrue(promise);
33929 return transform.readable;
33930 }
33931 pipeTo(destination, rawOptions = {}) {
33932 if (!IsReadableStream(this)) {
33933 return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));
33934 }
33935 if (destination === undefined) {
33936 return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
33937 }
33938 if (!IsWritableStream(destination)) {
33939 return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
33940 }
33941 let options;
33942 try {
33943 options = convertPipeOptions(rawOptions, 'Second parameter');
33944 }
33945 catch (e) {
33946 return promiseRejectedWith(e);
33947 }
33948 if (IsReadableStreamLocked(this)) {
33949 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));
33950 }
33951 if (IsWritableStreamLocked(destination)) {
33952 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));
33953 }
33954 return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
33955 }
33956 /**
33957 * Tees this readable stream, returning a two-element array containing the two resulting branches as
33958 * new {@link ReadableStream} instances.
33959 *
33960 * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
33961 * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
33962 * propagated to the stream's underlying source.
33963 *
33964 * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
33965 * this could allow interference between the two branches.
33966 */
33967 tee() {
33968 if (!IsReadableStream(this)) {
33969 throw streamBrandCheckException$1('tee');
33970 }
33971 const branches = ReadableStreamTee(this);
33972 return CreateArrayFromList(branches);
33973 }
33974 values(rawOptions = undefined) {
33975 if (!IsReadableStream(this)) {
33976 throw streamBrandCheckException$1('values');
33977 }
33978 const options = convertIteratorOptions(rawOptions, 'First parameter');
33979 return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
33980 }
33981 }
33982 Object.defineProperties(ReadableStream$1.prototype, {
33983 cancel: { enumerable: true },
33984 getReader: { enumerable: true },
33985 pipeThrough: { enumerable: true },
33986 pipeTo: { enumerable: true },
33987 tee: { enumerable: true },
33988 values: { enumerable: true },
33989 locked: { enumerable: true }
33990 });
33991 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
33992 Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.toStringTag, {
33993 value: 'ReadableStream',
33994 configurable: true
33995 });
33996 }
33997 if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
33998 Object.defineProperty(ReadableStream$1.prototype, SymbolPolyfill.asyncIterator, {
33999 value: ReadableStream$1.prototype.values,
34000 writable: true,
34001 configurable: true
34002 });
34003 }
34004 // Abstract operations for the ReadableStream.
34005 // Throws if and only if startAlgorithm throws.
34006 function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
34007 const stream = Object.create(ReadableStream$1.prototype);
34008 InitializeReadableStream(stream);
34009 const controller = Object.create(ReadableStreamDefaultController.prototype);
34010 SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
34011 return stream;
34012 }
34013 function InitializeReadableStream(stream) {
34014 stream._state = 'readable';
34015 stream._reader = undefined;
34016 stream._storedError = undefined;
34017 stream._disturbed = false;
34018 }
34019 function IsReadableStream(x) {
34020 if (!typeIsObject(x)) {
34021 return false;
34022 }
34023 if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {
34024 return false;
34025 }
34026 return true;
34027 }
34028 function IsReadableStreamLocked(stream) {
34029 if (stream._reader === undefined) {
34030 return false;
34031 }
34032 return true;
34033 }
34034 // ReadableStream API exposed for controllers.
34035 function ReadableStreamCancel(stream, reason) {
34036 stream._disturbed = true;
34037 if (stream._state === 'closed') {
34038 return promiseResolvedWith(undefined);
34039 }
34040 if (stream._state === 'errored') {
34041 return promiseRejectedWith(stream._storedError);
34042 }
34043 ReadableStreamClose(stream);
34044 const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
34045 return transformPromiseWith(sourceCancelPromise, noop);
34046 }
34047 function ReadableStreamClose(stream) {
34048 stream._state = 'closed';
34049 const reader = stream._reader;
34050 if (reader === undefined) {
34051 return;
34052 }
34053 defaultReaderClosedPromiseResolve(reader);
34054 if (IsReadableStreamDefaultReader(reader)) {
34055 reader._readRequests.forEach(readRequest => {
34056 readRequest._closeSteps();
34057 });
34058 reader._readRequests = new SimpleQueue();
34059 }
34060 }
34061 function ReadableStreamError(stream, e) {
34062 stream._state = 'errored';
34063 stream._storedError = e;
34064 const reader = stream._reader;
34065 if (reader === undefined) {
34066 return;
34067 }
34068 defaultReaderClosedPromiseReject(reader, e);
34069 if (IsReadableStreamDefaultReader(reader)) {
34070 reader._readRequests.forEach(readRequest => {
34071 readRequest._errorSteps(e);
34072 });
34073 reader._readRequests = new SimpleQueue();
34074 }
34075 else {
34076 reader._readIntoRequests.forEach(readIntoRequest => {
34077 readIntoRequest._errorSteps(e);
34078 });
34079 reader._readIntoRequests = new SimpleQueue();
34080 }
34081 }
34082 // Helper functions for the ReadableStream.
34083 function streamBrandCheckException$1(name) {
34084 return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
34085 }
34086
34087 function convertQueuingStrategyInit(init, context) {
34088 assertDictionary(init, context);
34089 const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
34090 assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');
34091 return {
34092 highWaterMark: convertUnrestrictedDouble(highWaterMark)
34093 };
34094 }
34095
34096 const byteLengthSizeFunction = function size(chunk) {
34097 return chunk.byteLength;
34098 };
34099 /**
34100 * A queuing strategy that counts the number of bytes in each chunk.
34101 *
34102 * @public
34103 */
34104 class ByteLengthQueuingStrategy {
34105 constructor(options) {
34106 assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');
34107 options = convertQueuingStrategyInit(options, 'First parameter');
34108 this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;
34109 }
34110 /**
34111 * Returns the high water mark provided to the constructor.
34112 */
34113 get highWaterMark() {
34114 if (!IsByteLengthQueuingStrategy(this)) {
34115 throw byteLengthBrandCheckException('highWaterMark');
34116 }
34117 return this._byteLengthQueuingStrategyHighWaterMark;
34118 }
34119 /**
34120 * Measures the size of `chunk` by returning the value of its `byteLength` property.
34121 */
34122 get size() {
34123 if (!IsByteLengthQueuingStrategy(this)) {
34124 throw byteLengthBrandCheckException('size');
34125 }
34126 return byteLengthSizeFunction;
34127 }
34128 }
34129 Object.defineProperties(ByteLengthQueuingStrategy.prototype, {
34130 highWaterMark: { enumerable: true },
34131 size: { enumerable: true }
34132 });
34133 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34134 Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
34135 value: 'ByteLengthQueuingStrategy',
34136 configurable: true
34137 });
34138 }
34139 // Helper functions for the ByteLengthQueuingStrategy.
34140 function byteLengthBrandCheckException(name) {
34141 return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
34142 }
34143 function IsByteLengthQueuingStrategy(x) {
34144 if (!typeIsObject(x)) {
34145 return false;
34146 }
34147 if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {
34148 return false;
34149 }
34150 return true;
34151 }
34152
34153 const countSizeFunction = function size() {
34154 return 1;
34155 };
34156 /**
34157 * A queuing strategy that counts the number of chunks.
34158 *
34159 * @public
34160 */
34161 class CountQueuingStrategy {
34162 constructor(options) {
34163 assertRequiredArgument(options, 1, 'CountQueuingStrategy');
34164 options = convertQueuingStrategyInit(options, 'First parameter');
34165 this._countQueuingStrategyHighWaterMark = options.highWaterMark;
34166 }
34167 /**
34168 * Returns the high water mark provided to the constructor.
34169 */
34170 get highWaterMark() {
34171 if (!IsCountQueuingStrategy(this)) {
34172 throw countBrandCheckException('highWaterMark');
34173 }
34174 return this._countQueuingStrategyHighWaterMark;
34175 }
34176 /**
34177 * Measures the size of `chunk` by always returning 1.
34178 * This ensures that the total queue size is a count of the number of chunks in the queue.
34179 */
34180 get size() {
34181 if (!IsCountQueuingStrategy(this)) {
34182 throw countBrandCheckException('size');
34183 }
34184 return countSizeFunction;
34185 }
34186 }
34187 Object.defineProperties(CountQueuingStrategy.prototype, {
34188 highWaterMark: { enumerable: true },
34189 size: { enumerable: true }
34190 });
34191 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34192 Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
34193 value: 'CountQueuingStrategy',
34194 configurable: true
34195 });
34196 }
34197 // Helper functions for the CountQueuingStrategy.
34198 function countBrandCheckException(name) {
34199 return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
34200 }
34201 function IsCountQueuingStrategy(x) {
34202 if (!typeIsObject(x)) {
34203 return false;
34204 }
34205 if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {
34206 return false;
34207 }
34208 return true;
34209 }
34210
34211 function convertTransformer(original, context) {
34212 assertDictionary(original, context);
34213 const flush = original === null || original === void 0 ? void 0 : original.flush;
34214 const readableType = original === null || original === void 0 ? void 0 : original.readableType;
34215 const start = original === null || original === void 0 ? void 0 : original.start;
34216 const transform = original === null || original === void 0 ? void 0 : original.transform;
34217 const writableType = original === null || original === void 0 ? void 0 : original.writableType;
34218 return {
34219 flush: flush === undefined ?
34220 undefined :
34221 convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
34222 readableType,
34223 start: start === undefined ?
34224 undefined :
34225 convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
34226 transform: transform === undefined ?
34227 undefined :
34228 convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),
34229 writableType
34230 };
34231 }
34232 function convertTransformerFlushCallback(fn, original, context) {
34233 assertFunction(fn, context);
34234 return (controller) => promiseCall(fn, original, [controller]);
34235 }
34236 function convertTransformerStartCallback(fn, original, context) {
34237 assertFunction(fn, context);
34238 return (controller) => reflectCall(fn, original, [controller]);
34239 }
34240 function convertTransformerTransformCallback(fn, original, context) {
34241 assertFunction(fn, context);
34242 return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
34243 }
34244
34245 // Class TransformStream
34246 /**
34247 * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
34248 * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
34249 * In a manner specific to the transform stream in question, writes to the writable side result in new data being
34250 * made available for reading from the readable side.
34251 *
34252 * @public
34253 */
34254 class TransformStream$1 {
34255 constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
34256 if (rawTransformer === undefined) {
34257 rawTransformer = null;
34258 }
34259 const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');
34260 const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');
34261 const transformer = convertTransformer(rawTransformer, 'First parameter');
34262 if (transformer.readableType !== undefined) {
34263 throw new RangeError('Invalid readableType specified');
34264 }
34265 if (transformer.writableType !== undefined) {
34266 throw new RangeError('Invalid writableType specified');
34267 }
34268 const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
34269 const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
34270 const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
34271 const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
34272 let startPromise_resolve;
34273 const startPromise = newPromise(resolve => {
34274 startPromise_resolve = resolve;
34275 });
34276 InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
34277 SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
34278 if (transformer.start !== undefined) {
34279 startPromise_resolve(transformer.start(this._transformStreamController));
34280 }
34281 else {
34282 startPromise_resolve(undefined);
34283 }
34284 }
34285 /**
34286 * The readable side of the transform stream.
34287 */
34288 get readable() {
34289 if (!IsTransformStream(this)) {
34290 throw streamBrandCheckException('readable');
34291 }
34292 return this._readable;
34293 }
34294 /**
34295 * The writable side of the transform stream.
34296 */
34297 get writable() {
34298 if (!IsTransformStream(this)) {
34299 throw streamBrandCheckException('writable');
34300 }
34301 return this._writable;
34302 }
34303 }
34304 Object.defineProperties(TransformStream$1.prototype, {
34305 readable: { enumerable: true },
34306 writable: { enumerable: true }
34307 });
34308 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34309 Object.defineProperty(TransformStream$1.prototype, SymbolPolyfill.toStringTag, {
34310 value: 'TransformStream',
34311 configurable: true
34312 });
34313 }
34314 function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
34315 function startAlgorithm() {
34316 return startPromise;
34317 }
34318 function writeAlgorithm(chunk) {
34319 return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
34320 }
34321 function abortAlgorithm(reason) {
34322 return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
34323 }
34324 function closeAlgorithm() {
34325 return TransformStreamDefaultSinkCloseAlgorithm(stream);
34326 }
34327 stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
34328 function pullAlgorithm() {
34329 return TransformStreamDefaultSourcePullAlgorithm(stream);
34330 }
34331 function cancelAlgorithm(reason) {
34332 TransformStreamErrorWritableAndUnblockWrite(stream, reason);
34333 return promiseResolvedWith(undefined);
34334 }
34335 stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
34336 // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
34337 stream._backpressure = undefined;
34338 stream._backpressureChangePromise = undefined;
34339 stream._backpressureChangePromise_resolve = undefined;
34340 TransformStreamSetBackpressure(stream, true);
34341 stream._transformStreamController = undefined;
34342 }
34343 function IsTransformStream(x) {
34344 if (!typeIsObject(x)) {
34345 return false;
34346 }
34347 if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {
34348 return false;
34349 }
34350 return true;
34351 }
34352 // This is a no-op if both sides are already errored.
34353 function TransformStreamError(stream, e) {
34354 ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);
34355 TransformStreamErrorWritableAndUnblockWrite(stream, e);
34356 }
34357 function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
34358 TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
34359 WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
34360 if (stream._backpressure) {
34361 // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
34362 // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
34363 // _backpressure is set.
34364 TransformStreamSetBackpressure(stream, false);
34365 }
34366 }
34367 function TransformStreamSetBackpressure(stream, backpressure) {
34368 // Passes also when called during construction.
34369 if (stream._backpressureChangePromise !== undefined) {
34370 stream._backpressureChangePromise_resolve();
34371 }
34372 stream._backpressureChangePromise = newPromise(resolve => {
34373 stream._backpressureChangePromise_resolve = resolve;
34374 });
34375 stream._backpressure = backpressure;
34376 }
34377 // Class TransformStreamDefaultController
34378 /**
34379 * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
34380 *
34381 * @public
34382 */
34383 class TransformStreamDefaultController {
34384 constructor() {
34385 throw new TypeError('Illegal constructor');
34386 }
34387 /**
34388 * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
34389 */
34390 get desiredSize() {
34391 if (!IsTransformStreamDefaultController(this)) {
34392 throw defaultControllerBrandCheckException('desiredSize');
34393 }
34394 const readableController = this._controlledTransformStream._readable._readableStreamController;
34395 return ReadableStreamDefaultControllerGetDesiredSize(readableController);
34396 }
34397 enqueue(chunk = undefined) {
34398 if (!IsTransformStreamDefaultController(this)) {
34399 throw defaultControllerBrandCheckException('enqueue');
34400 }
34401 TransformStreamDefaultControllerEnqueue(this, chunk);
34402 }
34403 /**
34404 * Errors both the readable side and the writable side of the controlled transform stream, making all future
34405 * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
34406 */
34407 error(reason = undefined) {
34408 if (!IsTransformStreamDefaultController(this)) {
34409 throw defaultControllerBrandCheckException('error');
34410 }
34411 TransformStreamDefaultControllerError(this, reason);
34412 }
34413 /**
34414 * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
34415 * transformer only needs to consume a portion of the chunks written to the writable side.
34416 */
34417 terminate() {
34418 if (!IsTransformStreamDefaultController(this)) {
34419 throw defaultControllerBrandCheckException('terminate');
34420 }
34421 TransformStreamDefaultControllerTerminate(this);
34422 }
34423 }
34424 Object.defineProperties(TransformStreamDefaultController.prototype, {
34425 enqueue: { enumerable: true },
34426 error: { enumerable: true },
34427 terminate: { enumerable: true },
34428 desiredSize: { enumerable: true }
34429 });
34430 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
34431 Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
34432 value: 'TransformStreamDefaultController',
34433 configurable: true
34434 });
34435 }
34436 // Transform Stream Default Controller Abstract Operations
34437 function IsTransformStreamDefaultController(x) {
34438 if (!typeIsObject(x)) {
34439 return false;
34440 }
34441 if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {
34442 return false;
34443 }
34444 return true;
34445 }
34446 function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {
34447 controller._controlledTransformStream = stream;
34448 stream._transformStreamController = controller;
34449 controller._transformAlgorithm = transformAlgorithm;
34450 controller._flushAlgorithm = flushAlgorithm;
34451 }
34452 function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
34453 const controller = Object.create(TransformStreamDefaultController.prototype);
34454 let transformAlgorithm = (chunk) => {
34455 try {
34456 TransformStreamDefaultControllerEnqueue(controller, chunk);
34457 return promiseResolvedWith(undefined);
34458 }
34459 catch (transformResultE) {
34460 return promiseRejectedWith(transformResultE);
34461 }
34462 };
34463 let flushAlgorithm = () => promiseResolvedWith(undefined);
34464 if (transformer.transform !== undefined) {
34465 transformAlgorithm = chunk => transformer.transform(chunk, controller);
34466 }
34467 if (transformer.flush !== undefined) {
34468 flushAlgorithm = () => transformer.flush(controller);
34469 }
34470 SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);
34471 }
34472 function TransformStreamDefaultControllerClearAlgorithms(controller) {
34473 controller._transformAlgorithm = undefined;
34474 controller._flushAlgorithm = undefined;
34475 }
34476 function TransformStreamDefaultControllerEnqueue(controller, chunk) {
34477 const stream = controller._controlledTransformStream;
34478 const readableController = stream._readable._readableStreamController;
34479 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
34480 throw new TypeError('Readable side is not in a state that permits enqueue');
34481 }
34482 // We throttle transform invocations based on the backpressure of the ReadableStream, but we still
34483 // accept TransformStreamDefaultControllerEnqueue() calls.
34484 try {
34485 ReadableStreamDefaultControllerEnqueue(readableController, chunk);
34486 }
34487 catch (e) {
34488 // This happens when readableStrategy.size() throws.
34489 TransformStreamErrorWritableAndUnblockWrite(stream, e);
34490 throw stream._readable._storedError;
34491 }
34492 const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
34493 if (backpressure !== stream._backpressure) {
34494 TransformStreamSetBackpressure(stream, true);
34495 }
34496 }
34497 function TransformStreamDefaultControllerError(controller, e) {
34498 TransformStreamError(controller._controlledTransformStream, e);
34499 }
34500 function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
34501 const transformPromise = controller._transformAlgorithm(chunk);
34502 return transformPromiseWith(transformPromise, undefined, r => {
34503 TransformStreamError(controller._controlledTransformStream, r);
34504 throw r;
34505 });
34506 }
34507 function TransformStreamDefaultControllerTerminate(controller) {
34508 const stream = controller._controlledTransformStream;
34509 const readableController = stream._readable._readableStreamController;
34510 ReadableStreamDefaultControllerClose(readableController);
34511 const error = new TypeError('TransformStream terminated');
34512 TransformStreamErrorWritableAndUnblockWrite(stream, error);
34513 }
34514 // TransformStreamDefaultSink Algorithms
34515 function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
34516 const controller = stream._transformStreamController;
34517 if (stream._backpressure) {
34518 const backpressureChangePromise = stream._backpressureChangePromise;
34519 return transformPromiseWith(backpressureChangePromise, () => {
34520 const writable = stream._writable;
34521 const state = writable._state;
34522 if (state === 'erroring') {
34523 throw writable._storedError;
34524 }
34525 return TransformStreamDefaultControllerPerformTransform(controller, chunk);
34526 });
34527 }
34528 return TransformStreamDefaultControllerPerformTransform(controller, chunk);
34529 }
34530 function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
34531 // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already
34532 // errored.
34533 TransformStreamError(stream, reason);
34534 return promiseResolvedWith(undefined);
34535 }
34536 function TransformStreamDefaultSinkCloseAlgorithm(stream) {
34537 // stream._readable cannot change after construction, so caching it across a call to user code is safe.
34538 const readable = stream._readable;
34539 const controller = stream._transformStreamController;
34540 const flushPromise = controller._flushAlgorithm();
34541 TransformStreamDefaultControllerClearAlgorithms(controller);
34542 // Return a promise that is fulfilled with undefined on success.
34543 return transformPromiseWith(flushPromise, () => {
34544 if (readable._state === 'errored') {
34545 throw readable._storedError;
34546 }
34547 ReadableStreamDefaultControllerClose(readable._readableStreamController);
34548 }, r => {
34549 TransformStreamError(stream, r);
34550 throw readable._storedError;
34551 });
34552 }
34553 // TransformStreamDefaultSource Algorithms
34554 function TransformStreamDefaultSourcePullAlgorithm(stream) {
34555 // Invariant. Enforced by the promises returned by start() and pull().
34556 TransformStreamSetBackpressure(stream, false);
34557 // Prevent the next pull() call until there is backpressure.
34558 return stream._backpressureChangePromise;
34559 }
34560 // Helper functions for the TransformStreamDefaultController.
34561 function defaultControllerBrandCheckException(name) {
34562 return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
34563 }
34564 // Helper functions for the TransformStream.
34565 function streamBrandCheckException(name) {
34566 return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
34567 }
34568
34569 var ponyfill_es6 = /*#__PURE__*/Object.freeze({
34570 __proto__: null,
34571 ByteLengthQueuingStrategy: ByteLengthQueuingStrategy,
34572 CountQueuingStrategy: CountQueuingStrategy,
34573 ReadableByteStreamController: ReadableByteStreamController,
34574 ReadableStream: ReadableStream$1,
34575 ReadableStreamBYOBReader: ReadableStreamBYOBReader,
34576 ReadableStreamBYOBRequest: ReadableStreamBYOBRequest,
34577 ReadableStreamDefaultController: ReadableStreamDefaultController,
34578 ReadableStreamDefaultReader: ReadableStreamDefaultReader,
34579 TransformStream: TransformStream$1,
34580 TransformStreamDefaultController: TransformStreamDefaultController,
34581 WritableStream: WritableStream$1,
34582 WritableStreamDefaultController: WritableStreamDefaultController,
34583 WritableStreamDefaultWriter: WritableStreamDefaultWriter
34584 });
34585
34586 /*! *****************************************************************************
34587 Copyright (c) Microsoft Corporation.
34588
34589 Permission to use, copy, modify, and/or distribute this software for any
34590 purpose with or without fee is hereby granted.
34591
34592 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
34593 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
34594 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
34595 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
34596 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
34597 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
34598 PERFORMANCE OF THIS SOFTWARE.
34599 ***************************************************************************** */
34600 /* global Reflect, Promise */
34601
34602 var extendStatics = function(d, b) {
34603 extendStatics = Object.setPrototypeOf ||
34604 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34605 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
34606 return extendStatics(d, b);
34607 };
34608
34609 function __extends(d, b) {
34610 if (typeof b !== "function" && b !== null)
34611 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
34612 extendStatics(d, b);
34613 function __() { this.constructor = d; }
34614 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34615 }
34616
34617 function assert$1(test) {
34618 if (!test) {
34619 throw new TypeError('Assertion failed');
34620 }
34621 }
34622
34623 function noop$1() {
34624 return;
34625 }
34626 function typeIsObject$1(x) {
34627 return (typeof x === 'object' && x !== null) || typeof x === 'function';
34628 }
34629
34630 function isStreamConstructor(ctor) {
34631 if (typeof ctor !== 'function') {
34632 return false;
34633 }
34634 var startCalled = false;
34635 try {
34636 new ctor({
34637 start: function () {
34638 startCalled = true;
34639 }
34640 });
34641 }
34642 catch (e) {
34643 // ignore
34644 }
34645 return startCalled;
34646 }
34647 function isReadableStream(readable) {
34648 if (!typeIsObject$1(readable)) {
34649 return false;
34650 }
34651 if (typeof readable.getReader !== 'function') {
34652 return false;
34653 }
34654 return true;
34655 }
34656 function isReadableStreamConstructor(ctor) {
34657 if (!isStreamConstructor(ctor)) {
34658 return false;
34659 }
34660 if (!isReadableStream(new ctor())) {
34661 return false;
34662 }
34663 return true;
34664 }
34665 function isWritableStream(writable) {
34666 if (!typeIsObject$1(writable)) {
34667 return false;
34668 }
34669 if (typeof writable.getWriter !== 'function') {
34670 return false;
34671 }
34672 return true;
34673 }
34674 function isWritableStreamConstructor(ctor) {
34675 if (!isStreamConstructor(ctor)) {
34676 return false;
34677 }
34678 if (!isWritableStream(new ctor())) {
34679 return false;
34680 }
34681 return true;
34682 }
34683 function isTransformStream(transform) {
34684 if (!typeIsObject$1(transform)) {
34685 return false;
34686 }
34687 if (!isReadableStream(transform.readable)) {
34688 return false;
34689 }
34690 if (!isWritableStream(transform.writable)) {
34691 return false;
34692 }
34693 return true;
34694 }
34695 function isTransformStreamConstructor(ctor) {
34696 if (!isStreamConstructor(ctor)) {
34697 return false;
34698 }
34699 if (!isTransformStream(new ctor())) {
34700 return false;
34701 }
34702 return true;
34703 }
34704 function supportsByobReader(readable) {
34705 try {
34706 var reader = readable.getReader({ mode: 'byob' });
34707 reader.releaseLock();
34708 return true;
34709 }
34710 catch (_a) {
34711 return false;
34712 }
34713 }
34714 function supportsByteSource(ctor) {
34715 try {
34716 new ctor({ type: 'bytes' });
34717 return true;
34718 }
34719 catch (_a) {
34720 return false;
34721 }
34722 }
34723
34724 function createReadableStreamWrapper(ctor) {
34725 assert$1(isReadableStreamConstructor(ctor));
34726 var byteSourceSupported = supportsByteSource(ctor);
34727 return function (readable, _a) {
34728 var _b = _a === void 0 ? {} : _a, type = _b.type;
34729 type = parseReadableType(type);
34730 if (type === 'bytes' && !byteSourceSupported) {
34731 type = undefined;
34732 }
34733 if (readable.constructor === ctor) {
34734 if (type !== 'bytes' || supportsByobReader(readable)) {
34735 return readable;
34736 }
34737 }
34738 if (type === 'bytes') {
34739 var source = createWrappingReadableSource(readable, { type: type });
34740 return new ctor(source);
34741 }
34742 else {
34743 var source = createWrappingReadableSource(readable);
34744 return new ctor(source);
34745 }
34746 };
34747 }
34748 function createWrappingReadableSource(readable, _a) {
34749 var _b = _a === void 0 ? {} : _a, type = _b.type;
34750 assert$1(isReadableStream(readable));
34751 assert$1(readable.locked === false);
34752 type = parseReadableType(type);
34753 var source;
34754 if (type === 'bytes') {
34755 source = new WrappingReadableByteStreamSource(readable);
34756 }
34757 else {
34758 source = new WrappingReadableStreamDefaultSource(readable);
34759 }
34760 return source;
34761 }
34762 function parseReadableType(type) {
34763 var typeString = String(type);
34764 if (typeString === 'bytes') {
34765 return typeString;
34766 }
34767 else if (type === undefined) {
34768 return type;
34769 }
34770 else {
34771 throw new RangeError('Invalid type is specified');
34772 }
34773 }
34774 var AbstractWrappingReadableStreamSource = /** @class */ (function () {
34775 function AbstractWrappingReadableStreamSource(underlyingStream) {
34776 this._underlyingReader = undefined;
34777 this._readerMode = undefined;
34778 this._readableStreamController = undefined;
34779 this._pendingRead = undefined;
34780 this._underlyingStream = underlyingStream;
34781 // always keep a reader attached to detect close/error
34782 this._attachDefaultReader();
34783 }
34784 AbstractWrappingReadableStreamSource.prototype.start = function (controller) {
34785 this._readableStreamController = controller;
34786 };
34787 AbstractWrappingReadableStreamSource.prototype.cancel = function (reason) {
34788 assert$1(this._underlyingReader !== undefined);
34789 return this._underlyingReader.cancel(reason);
34790 };
34791 AbstractWrappingReadableStreamSource.prototype._attachDefaultReader = function () {
34792 if (this._readerMode === "default" /* DEFAULT */) {
34793 return;
34794 }
34795 this._detachReader();
34796 var reader = this._underlyingStream.getReader();
34797 this._readerMode = "default" /* DEFAULT */;
34798 this._attachReader(reader);
34799 };
34800 AbstractWrappingReadableStreamSource.prototype._attachReader = function (reader) {
34801 var _this = this;
34802 assert$1(this._underlyingReader === undefined);
34803 this._underlyingReader = reader;
34804 var closed = this._underlyingReader.closed;
34805 if (!closed) {
34806 return;
34807 }
34808 closed
34809 .then(function () { return _this._finishPendingRead(); })
34810 .then(function () {
34811 if (reader === _this._underlyingReader) {
34812 _this._readableStreamController.close();
34813 }
34814 }, function (reason) {
34815 if (reader === _this._underlyingReader) {
34816 _this._readableStreamController.error(reason);
34817 }
34818 })
34819 .catch(noop$1);
34820 };
34821 AbstractWrappingReadableStreamSource.prototype._detachReader = function () {
34822 if (this._underlyingReader === undefined) {
34823 return;
34824 }
34825 this._underlyingReader.releaseLock();
34826 this._underlyingReader = undefined;
34827 this._readerMode = undefined;
34828 };
34829 AbstractWrappingReadableStreamSource.prototype._pullWithDefaultReader = function () {
34830 var _this = this;
34831 this._attachDefaultReader();
34832 // TODO Backpressure?
34833 var read = this._underlyingReader.read()
34834 .then(function (result) {
34835 var controller = _this._readableStreamController;
34836 if (result.done) {
34837 _this._tryClose();
34838 }
34839 else {
34840 controller.enqueue(result.value);
34841 }
34842 });
34843 this._setPendingRead(read);
34844 return read;
34845 };
34846 AbstractWrappingReadableStreamSource.prototype._tryClose = function () {
34847 try {
34848 this._readableStreamController.close();
34849 }
34850 catch (_a) {
34851 // already errored or closed
34852 }
34853 };
34854 AbstractWrappingReadableStreamSource.prototype._setPendingRead = function (readPromise) {
34855 var _this = this;
34856 var pendingRead;
34857 var finishRead = function () {
34858 if (_this._pendingRead === pendingRead) {
34859 _this._pendingRead = undefined;
34860 }
34861 };
34862 this._pendingRead = pendingRead = readPromise.then(finishRead, finishRead);
34863 };
34864 AbstractWrappingReadableStreamSource.prototype._finishPendingRead = function () {
34865 var _this = this;
34866 if (!this._pendingRead) {
34867 return undefined;
34868 }
34869 var afterRead = function () { return _this._finishPendingRead(); };
34870 return this._pendingRead.then(afterRead, afterRead);
34871 };
34872 return AbstractWrappingReadableStreamSource;
34873 }());
34874 var WrappingReadableStreamDefaultSource = /** @class */ (function (_super) {
34875 __extends(WrappingReadableStreamDefaultSource, _super);
34876 function WrappingReadableStreamDefaultSource() {
34877 return _super !== null && _super.apply(this, arguments) || this;
34878 }
34879 WrappingReadableStreamDefaultSource.prototype.pull = function () {
34880 return this._pullWithDefaultReader();
34881 };
34882 return WrappingReadableStreamDefaultSource;
34883 }(AbstractWrappingReadableStreamSource));
34884 function toUint8Array(view) {
34885 return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
34886 }
34887 function copyArrayBufferView(from, to) {
34888 var fromArray = toUint8Array(from);
34889 var toArray = toUint8Array(to);
34890 toArray.set(fromArray, 0);
34891 }
34892 var WrappingReadableByteStreamSource = /** @class */ (function (_super) {
34893 __extends(WrappingReadableByteStreamSource, _super);
34894 function WrappingReadableByteStreamSource(underlyingStream) {
34895 var _this = this;
34896 var supportsByob = supportsByobReader(underlyingStream);
34897 _this = _super.call(this, underlyingStream) || this;
34898 _this._supportsByob = supportsByob;
34899 return _this;
34900 }
34901 Object.defineProperty(WrappingReadableByteStreamSource.prototype, "type", {
34902 get: function () {
34903 return 'bytes';
34904 },
34905 enumerable: false,
34906 configurable: true
34907 });
34908 WrappingReadableByteStreamSource.prototype._attachByobReader = function () {
34909 if (this._readerMode === "byob" /* BYOB */) {
34910 return;
34911 }
34912 assert$1(this._supportsByob);
34913 this._detachReader();
34914 var reader = this._underlyingStream.getReader({ mode: 'byob' });
34915 this._readerMode = "byob" /* BYOB */;
34916 this._attachReader(reader);
34917 };
34918 WrappingReadableByteStreamSource.prototype.pull = function () {
34919 if (this._supportsByob) {
34920 var byobRequest = this._readableStreamController.byobRequest;
34921 if (byobRequest) {
34922 return this._pullWithByobRequest(byobRequest);
34923 }
34924 }
34925 return this._pullWithDefaultReader();
34926 };
34927 WrappingReadableByteStreamSource.prototype._pullWithByobRequest = function (byobRequest) {
34928 var _this = this;
34929 this._attachByobReader();
34930 // reader.read(view) detaches the input view, therefore we cannot pass byobRequest.view directly
34931 // create a separate buffer to read into, then copy that to byobRequest.view
34932 var buffer = new Uint8Array(byobRequest.view.byteLength);
34933 // TODO Backpressure?
34934 var read = this._underlyingReader.read(buffer)
34935 .then(function (result) {
34936 _this._readableStreamController;
34937 if (result.done) {
34938 _this._tryClose();
34939 byobRequest.respond(0);
34940 }
34941 else {
34942 copyArrayBufferView(result.value, byobRequest.view);
34943 byobRequest.respond(result.value.byteLength);
34944 }
34945 });
34946 this._setPendingRead(read);
34947 return read;
34948 };
34949 return WrappingReadableByteStreamSource;
34950 }(AbstractWrappingReadableStreamSource));
34951
34952 function createWritableStreamWrapper(ctor) {
34953 assert$1(isWritableStreamConstructor(ctor));
34954 return function (writable) {
34955 if (writable.constructor === ctor) {
34956 return writable;
34957 }
34958 var sink = createWrappingWritableSink(writable);
34959 return new ctor(sink);
34960 };
34961 }
34962 function createWrappingWritableSink(writable) {
34963 assert$1(isWritableStream(writable));
34964 assert$1(writable.locked === false);
34965 var writer = writable.getWriter();
34966 return new WrappingWritableStreamSink(writer);
34967 }
34968 var WrappingWritableStreamSink = /** @class */ (function () {
34969 function WrappingWritableStreamSink(underlyingWriter) {
34970 var _this = this;
34971 this._writableStreamController = undefined;
34972 this._pendingWrite = undefined;
34973 this._state = "writable" /* WRITABLE */;
34974 this._storedError = undefined;
34975 this._underlyingWriter = underlyingWriter;
34976 this._errorPromise = new Promise(function (resolve, reject) {
34977 _this._errorPromiseReject = reject;
34978 });
34979 this._errorPromise.catch(noop$1);
34980 }
34981 WrappingWritableStreamSink.prototype.start = function (controller) {
34982 var _this = this;
34983 this._writableStreamController = controller;
34984 this._underlyingWriter.closed
34985 .then(function () {
34986 _this._state = "closed" /* CLOSED */;
34987 })
34988 .catch(function (reason) { return _this._finishErroring(reason); });
34989 };
34990 WrappingWritableStreamSink.prototype.write = function (chunk) {
34991 var _this = this;
34992 var writer = this._underlyingWriter;
34993 // Detect past errors
34994 if (writer.desiredSize === null) {
34995 return writer.ready;
34996 }
34997 var writeRequest = writer.write(chunk);
34998 // Detect future errors
34999 writeRequest.catch(function (reason) { return _this._finishErroring(reason); });
35000 writer.ready.catch(function (reason) { return _this._startErroring(reason); });
35001 // Reject write when errored
35002 var write = Promise.race([writeRequest, this._errorPromise]);
35003 this._setPendingWrite(write);
35004 return write;
35005 };
35006 WrappingWritableStreamSink.prototype.close = function () {
35007 var _this = this;
35008 if (this._pendingWrite === undefined) {
35009 return this._underlyingWriter.close();
35010 }
35011 return this._finishPendingWrite().then(function () { return _this.close(); });
35012 };
35013 WrappingWritableStreamSink.prototype.abort = function (reason) {
35014 if (this._state === "errored" /* ERRORED */) {
35015 return undefined;
35016 }
35017 var writer = this._underlyingWriter;
35018 return writer.abort(reason);
35019 };
35020 WrappingWritableStreamSink.prototype._setPendingWrite = function (writePromise) {
35021 var _this = this;
35022 var pendingWrite;
35023 var finishWrite = function () {
35024 if (_this._pendingWrite === pendingWrite) {
35025 _this._pendingWrite = undefined;
35026 }
35027 };
35028 this._pendingWrite = pendingWrite = writePromise.then(finishWrite, finishWrite);
35029 };
35030 WrappingWritableStreamSink.prototype._finishPendingWrite = function () {
35031 var _this = this;
35032 if (this._pendingWrite === undefined) {
35033 return Promise.resolve();
35034 }
35035 var afterWrite = function () { return _this._finishPendingWrite(); };
35036 return this._pendingWrite.then(afterWrite, afterWrite);
35037 };
35038 WrappingWritableStreamSink.prototype._startErroring = function (reason) {
35039 var _this = this;
35040 if (this._state === "writable" /* WRITABLE */) {
35041 this._state = "erroring" /* ERRORING */;
35042 this._storedError = reason;
35043 var afterWrite = function () { return _this._finishErroring(reason); };
35044 if (this._pendingWrite === undefined) {
35045 afterWrite();
35046 }
35047 else {
35048 this._finishPendingWrite().then(afterWrite, afterWrite);
35049 }
35050 this._writableStreamController.error(reason);
35051 }
35052 };
35053 WrappingWritableStreamSink.prototype._finishErroring = function (reason) {
35054 if (this._state === "writable" /* WRITABLE */) {
35055 this._startErroring(reason);
35056 }
35057 if (this._state === "erroring" /* ERRORING */) {
35058 this._state = "errored" /* ERRORED */;
35059 this._errorPromiseReject(this._storedError);
35060 }
35061 };
35062 return WrappingWritableStreamSink;
35063 }());
35064
35065 function createTransformStreamWrapper(ctor) {
35066 assert$1(isTransformStreamConstructor(ctor));
35067 return function (transform) {
35068 if (transform.constructor === ctor) {
35069 return transform;
35070 }
35071 var transformer = createWrappingTransformer(transform);
35072 return new ctor(transformer);
35073 };
35074 }
35075 function createWrappingTransformer(transform) {
35076 assert$1(isTransformStream(transform));
35077 var readable = transform.readable, writable = transform.writable;
35078 assert$1(readable.locked === false);
35079 assert$1(writable.locked === false);
35080 var reader = readable.getReader();
35081 var writer;
35082 try {
35083 writer = writable.getWriter();
35084 }
35085 catch (e) {
35086 reader.releaseLock(); // do not leak reader
35087 throw e;
35088 }
35089 return new WrappingTransformStreamTransformer(reader, writer);
35090 }
35091 var WrappingTransformStreamTransformer = /** @class */ (function () {
35092 function WrappingTransformStreamTransformer(reader, writer) {
35093 var _this = this;
35094 this._transformStreamController = undefined;
35095 this._onRead = function (result) {
35096 if (result.done) {
35097 return;
35098 }
35099 _this._transformStreamController.enqueue(result.value);
35100 return _this._reader.read().then(_this._onRead);
35101 };
35102 this._onError = function (reason) {
35103 _this._flushReject(reason);
35104 _this._transformStreamController.error(reason);
35105 _this._reader.cancel(reason).catch(noop$1);
35106 _this._writer.abort(reason).catch(noop$1);
35107 };
35108 this._onTerminate = function () {
35109 _this._flushResolve();
35110 _this._transformStreamController.terminate();
35111 var error = new TypeError('TransformStream terminated');
35112 _this._writer.abort(error).catch(noop$1);
35113 };
35114 this._reader = reader;
35115 this._writer = writer;
35116 this._flushPromise = new Promise(function (resolve, reject) {
35117 _this._flushResolve = resolve;
35118 _this._flushReject = reject;
35119 });
35120 }
35121 WrappingTransformStreamTransformer.prototype.start = function (controller) {
35122 this._transformStreamController = controller;
35123 this._reader.read()
35124 .then(this._onRead)
35125 .then(this._onTerminate, this._onError);
35126 var readerClosed = this._reader.closed;
35127 if (readerClosed) {
35128 readerClosed
35129 .then(this._onTerminate, this._onError);
35130 }
35131 };
35132 WrappingTransformStreamTransformer.prototype.transform = function (chunk) {
35133 return this._writer.write(chunk);
35134 };
35135 WrappingTransformStreamTransformer.prototype.flush = function () {
35136 var _this = this;
35137 return this._writer.close()
35138 .then(function () { return _this._flushPromise; });
35139 };
35140 return WrappingTransformStreamTransformer;
35141 }());
35142
35143 var webStreamsAdapter = /*#__PURE__*/Object.freeze({
35144 __proto__: null,
35145 createReadableStreamWrapper: createReadableStreamWrapper,
35146 createTransformStreamWrapper: createTransformStreamWrapper,
35147 createWrappingReadableSource: createWrappingReadableSource,
35148 createWrappingTransformer: createWrappingTransformer,
35149 createWrappingWritableSink: createWrappingWritableSink,
35150 createWritableStreamWrapper: createWritableStreamWrapper
35151 });
35152
35153 var bn = createCommonjsModule(function (module) {
35154 (function (module, exports) {
35155
35156 // Utils
35157 function assert (val, msg) {
35158 if (!val) throw new Error(msg || 'Assertion failed');
35159 }
35160
35161 // Could use `inherits` module, but don't want to move from single file
35162 // architecture yet.
35163 function inherits (ctor, superCtor) {
35164 ctor.super_ = superCtor;
35165 var TempCtor = function () {};
35166 TempCtor.prototype = superCtor.prototype;
35167 ctor.prototype = new TempCtor();
35168 ctor.prototype.constructor = ctor;
35169 }
35170
35171 // BN
35172
35173 function BN (number, base, endian) {
35174 if (BN.isBN(number)) {
35175 return number;
35176 }
35177
35178 this.negative = 0;
35179 this.words = null;
35180 this.length = 0;
35181
35182 // Reduction context
35183 this.red = null;
35184
35185 if (number !== null) {
35186 if (base === 'le' || base === 'be') {
35187 endian = base;
35188 base = 10;
35189 }
35190
35191 this._init(number || 0, base || 10, endian || 'be');
35192 }
35193 }
35194 if (typeof module === 'object') {
35195 module.exports = BN;
35196 } else {
35197 exports.BN = BN;
35198 }
35199
35200 BN.BN = BN;
35201 BN.wordSize = 26;
35202
35203 var Buffer;
35204 try {
35205 Buffer = void('buffer').Buffer;
35206 } catch (e) {
35207 }
35208
35209 BN.isBN = function isBN (num) {
35210 if (num instanceof BN) {
35211 return true;
35212 }
35213
35214 return num !== null && typeof num === 'object' &&
35215 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
35216 };
35217
35218 BN.max = function max (left, right) {
35219 if (left.cmp(right) > 0) return left;
35220 return right;
35221 };
35222
35223 BN.min = function min (left, right) {
35224 if (left.cmp(right) < 0) return left;
35225 return right;
35226 };
35227
35228 BN.prototype._init = function init (number, base, endian) {
35229 if (typeof number === 'number') {
35230 return this._initNumber(number, base, endian);
35231 }
35232
35233 if (typeof number === 'object') {
35234 return this._initArray(number, base, endian);
35235 }
35236
35237 if (base === 'hex') {
35238 base = 16;
35239 }
35240 assert(base === (base | 0) && base >= 2 && base <= 36);
35241
35242 number = number.toString().replace(/\s+/g, '');
35243 var start = 0;
35244 if (number[0] === '-') {
35245 start++;
35246 }
35247
35248 if (base === 16) {
35249 this._parseHex(number, start);
35250 } else {
35251 this._parseBase(number, base, start);
35252 }
35253
35254 if (number[0] === '-') {
35255 this.negative = 1;
35256 }
35257
35258 this.strip();
35259
35260 if (endian !== 'le') return;
35261
35262 this._initArray(this.toArray(), base, endian);
35263 };
35264
35265 BN.prototype._initNumber = function _initNumber (number, base, endian) {
35266 if (number < 0) {
35267 this.negative = 1;
35268 number = -number;
35269 }
35270 if (number < 0x4000000) {
35271 this.words = [ number & 0x3ffffff ];
35272 this.length = 1;
35273 } else if (number < 0x10000000000000) {
35274 this.words = [
35275 number & 0x3ffffff,
35276 (number / 0x4000000) & 0x3ffffff
35277 ];
35278 this.length = 2;
35279 } else {
35280 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
35281 this.words = [
35282 number & 0x3ffffff,
35283 (number / 0x4000000) & 0x3ffffff,
35284 1
35285 ];
35286 this.length = 3;
35287 }
35288
35289 if (endian !== 'le') return;
35290
35291 // Reverse the bytes
35292 this._initArray(this.toArray(), base, endian);
35293 };
35294
35295 BN.prototype._initArray = function _initArray (number, base, endian) {
35296 // Perhaps a Uint8Array
35297 assert(typeof number.length === 'number');
35298 if (number.length <= 0) {
35299 this.words = [ 0 ];
35300 this.length = 1;
35301 return this;
35302 }
35303
35304 this.length = Math.ceil(number.length / 3);
35305 this.words = new Array(this.length);
35306 for (var i = 0; i < this.length; i++) {
35307 this.words[i] = 0;
35308 }
35309
35310 var j, w;
35311 var off = 0;
35312 if (endian === 'be') {
35313 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
35314 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
35315 this.words[j] |= (w << off) & 0x3ffffff;
35316 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
35317 off += 24;
35318 if (off >= 26) {
35319 off -= 26;
35320 j++;
35321 }
35322 }
35323 } else if (endian === 'le') {
35324 for (i = 0, j = 0; i < number.length; i += 3) {
35325 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
35326 this.words[j] |= (w << off) & 0x3ffffff;
35327 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
35328 off += 24;
35329 if (off >= 26) {
35330 off -= 26;
35331 j++;
35332 }
35333 }
35334 }
35335 return this.strip();
35336 };
35337
35338 function parseHex (str, start, end) {
35339 var r = 0;
35340 var len = Math.min(str.length, end);
35341 for (var i = start; i < len; i++) {
35342 var c = str.charCodeAt(i) - 48;
35343
35344 r <<= 4;
35345
35346 // 'a' - 'f'
35347 if (c >= 49 && c <= 54) {
35348 r |= c - 49 + 0xa;
35349
35350 // 'A' - 'F'
35351 } else if (c >= 17 && c <= 22) {
35352 r |= c - 17 + 0xa;
35353
35354 // '0' - '9'
35355 } else {
35356 r |= c & 0xf;
35357 }
35358 }
35359 return r;
35360 }
35361
35362 BN.prototype._parseHex = function _parseHex (number, start) {
35363 // Create possibly bigger array to ensure that it fits the number
35364 this.length = Math.ceil((number.length - start) / 6);
35365 this.words = new Array(this.length);
35366 for (var i = 0; i < this.length; i++) {
35367 this.words[i] = 0;
35368 }
35369
35370 var j, w;
35371 // Scan 24-bit chunks and add them to the number
35372 var off = 0;
35373 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
35374 w = parseHex(number, i, i + 6);
35375 this.words[j] |= (w << off) & 0x3ffffff;
35376 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
35377 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
35378 off += 24;
35379 if (off >= 26) {
35380 off -= 26;
35381 j++;
35382 }
35383 }
35384 if (i + 6 !== start) {
35385 w = parseHex(number, start, i + 6);
35386 this.words[j] |= (w << off) & 0x3ffffff;
35387 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
35388 }
35389 this.strip();
35390 };
35391
35392 function parseBase (str, start, end, mul) {
35393 var r = 0;
35394 var len = Math.min(str.length, end);
35395 for (var i = start; i < len; i++) {
35396 var c = str.charCodeAt(i) - 48;
35397
35398 r *= mul;
35399
35400 // 'a'
35401 if (c >= 49) {
35402 r += c - 49 + 0xa;
35403
35404 // 'A'
35405 } else if (c >= 17) {
35406 r += c - 17 + 0xa;
35407
35408 // '0' - '9'
35409 } else {
35410 r += c;
35411 }
35412 }
35413 return r;
35414 }
35415
35416 BN.prototype._parseBase = function _parseBase (number, base, start) {
35417 // Initialize as zero
35418 this.words = [ 0 ];
35419 this.length = 1;
35420
35421 // Find length of limb in base
35422 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
35423 limbLen++;
35424 }
35425 limbLen--;
35426 limbPow = (limbPow / base) | 0;
35427
35428 var total = number.length - start;
35429 var mod = total % limbLen;
35430 var end = Math.min(total, total - mod) + start;
35431
35432 var word = 0;
35433 for (var i = start; i < end; i += limbLen) {
35434 word = parseBase(number, i, i + limbLen, base);
35435
35436 this.imuln(limbPow);
35437 if (this.words[0] + word < 0x4000000) {
35438 this.words[0] += word;
35439 } else {
35440 this._iaddn(word);
35441 }
35442 }
35443
35444 if (mod !== 0) {
35445 var pow = 1;
35446 word = parseBase(number, i, number.length, base);
35447
35448 for (i = 0; i < mod; i++) {
35449 pow *= base;
35450 }
35451
35452 this.imuln(pow);
35453 if (this.words[0] + word < 0x4000000) {
35454 this.words[0] += word;
35455 } else {
35456 this._iaddn(word);
35457 }
35458 }
35459 };
35460
35461 BN.prototype.copy = function copy (dest) {
35462 dest.words = new Array(this.length);
35463 for (var i = 0; i < this.length; i++) {
35464 dest.words[i] = this.words[i];
35465 }
35466 dest.length = this.length;
35467 dest.negative = this.negative;
35468 dest.red = this.red;
35469 };
35470
35471 BN.prototype.clone = function clone () {
35472 var r = new BN(null);
35473 this.copy(r);
35474 return r;
35475 };
35476
35477 BN.prototype._expand = function _expand (size) {
35478 while (this.length < size) {
35479 this.words[this.length++] = 0;
35480 }
35481 return this;
35482 };
35483
35484 // Remove leading `0` from `this`
35485 BN.prototype.strip = function strip () {
35486 while (this.length > 1 && this.words[this.length - 1] === 0) {
35487 this.length--;
35488 }
35489 return this._normSign();
35490 };
35491
35492 BN.prototype._normSign = function _normSign () {
35493 // -0 = 0
35494 if (this.length === 1 && this.words[0] === 0) {
35495 this.negative = 0;
35496 }
35497 return this;
35498 };
35499
35500 BN.prototype.inspect = function inspect () {
35501 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
35502 };
35503
35504 /*
35505
35506 var zeros = [];
35507 var groupSizes = [];
35508 var groupBases = [];
35509
35510 var s = '';
35511 var i = -1;
35512 while (++i < BN.wordSize) {
35513 zeros[i] = s;
35514 s += '0';
35515 }
35516 groupSizes[0] = 0;
35517 groupSizes[1] = 0;
35518 groupBases[0] = 0;
35519 groupBases[1] = 0;
35520 var base = 2 - 1;
35521 while (++base < 36 + 1) {
35522 var groupSize = 0;
35523 var groupBase = 1;
35524 while (groupBase < (1 << BN.wordSize) / base) {
35525 groupBase *= base;
35526 groupSize += 1;
35527 }
35528 groupSizes[base] = groupSize;
35529 groupBases[base] = groupBase;
35530 }
35531
35532 */
35533
35534 var zeros = [
35535 '',
35536 '0',
35537 '00',
35538 '000',
35539 '0000',
35540 '00000',
35541 '000000',
35542 '0000000',
35543 '00000000',
35544 '000000000',
35545 '0000000000',
35546 '00000000000',
35547 '000000000000',
35548 '0000000000000',
35549 '00000000000000',
35550 '000000000000000',
35551 '0000000000000000',
35552 '00000000000000000',
35553 '000000000000000000',
35554 '0000000000000000000',
35555 '00000000000000000000',
35556 '000000000000000000000',
35557 '0000000000000000000000',
35558 '00000000000000000000000',
35559 '000000000000000000000000',
35560 '0000000000000000000000000'
35561 ];
35562
35563 var groupSizes = [
35564 0, 0,
35565 25, 16, 12, 11, 10, 9, 8,
35566 8, 7, 7, 7, 7, 6, 6,
35567 6, 6, 6, 6, 6, 5, 5,
35568 5, 5, 5, 5, 5, 5, 5,
35569 5, 5, 5, 5, 5, 5, 5
35570 ];
35571
35572 var groupBases = [
35573 0, 0,
35574 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
35575 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
35576 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
35577 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
35578 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
35579 ];
35580
35581 BN.prototype.toString = function toString (base, padding) {
35582 base = base || 10;
35583 padding = padding | 0 || 1;
35584
35585 var out;
35586 if (base === 16 || base === 'hex') {
35587 out = '';
35588 var off = 0;
35589 var carry = 0;
35590 for (var i = 0; i < this.length; i++) {
35591 var w = this.words[i];
35592 var word = (((w << off) | carry) & 0xffffff).toString(16);
35593 carry = (w >>> (24 - off)) & 0xffffff;
35594 if (carry !== 0 || i !== this.length - 1) {
35595 out = zeros[6 - word.length] + word + out;
35596 } else {
35597 out = word + out;
35598 }
35599 off += 2;
35600 if (off >= 26) {
35601 off -= 26;
35602 i--;
35603 }
35604 }
35605 if (carry !== 0) {
35606 out = carry.toString(16) + out;
35607 }
35608 while (out.length % padding !== 0) {
35609 out = '0' + out;
35610 }
35611 if (this.negative !== 0) {
35612 out = '-' + out;
35613 }
35614 return out;
35615 }
35616
35617 if (base === (base | 0) && base >= 2 && base <= 36) {
35618 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
35619 var groupSize = groupSizes[base];
35620 // var groupBase = Math.pow(base, groupSize);
35621 var groupBase = groupBases[base];
35622 out = '';
35623 var c = this.clone();
35624 c.negative = 0;
35625 while (!c.isZero()) {
35626 var r = c.modn(groupBase).toString(base);
35627 c = c.idivn(groupBase);
35628
35629 if (!c.isZero()) {
35630 out = zeros[groupSize - r.length] + r + out;
35631 } else {
35632 out = r + out;
35633 }
35634 }
35635 if (this.isZero()) {
35636 out = '0' + out;
35637 }
35638 while (out.length % padding !== 0) {
35639 out = '0' + out;
35640 }
35641 if (this.negative !== 0) {
35642 out = '-' + out;
35643 }
35644 return out;
35645 }
35646
35647 assert(false, 'Base should be between 2 and 36');
35648 };
35649
35650 BN.prototype.toNumber = function toNumber () {
35651 var ret = this.words[0];
35652 if (this.length === 2) {
35653 ret += this.words[1] * 0x4000000;
35654 } else if (this.length === 3 && this.words[2] === 0x01) {
35655 // NOTE: at this stage it is known that the top bit is set
35656 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
35657 } else if (this.length > 2) {
35658 assert(false, 'Number can only safely store up to 53 bits');
35659 }
35660 return (this.negative !== 0) ? -ret : ret;
35661 };
35662
35663 BN.prototype.toJSON = function toJSON () {
35664 return this.toString(16);
35665 };
35666
35667 BN.prototype.toBuffer = function toBuffer (endian, length) {
35668 assert(typeof Buffer !== 'undefined');
35669 return this.toArrayLike(Buffer, endian, length);
35670 };
35671
35672 BN.prototype.toArray = function toArray (endian, length) {
35673 return this.toArrayLike(Array, endian, length);
35674 };
35675
35676 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
35677 var byteLength = this.byteLength();
35678 var reqLength = length || Math.max(1, byteLength);
35679 assert(byteLength <= reqLength, 'byte array longer than desired length');
35680 assert(reqLength > 0, 'Requested array length <= 0');
35681
35682 this.strip();
35683 var littleEndian = endian === 'le';
35684 var res = new ArrayType(reqLength);
35685
35686 var b, i;
35687 var q = this.clone();
35688 if (!littleEndian) {
35689 // Assume big-endian
35690 for (i = 0; i < reqLength - byteLength; i++) {
35691 res[i] = 0;
35692 }
35693
35694 for (i = 0; !q.isZero(); i++) {
35695 b = q.andln(0xff);
35696 q.iushrn(8);
35697
35698 res[reqLength - i - 1] = b;
35699 }
35700 } else {
35701 for (i = 0; !q.isZero(); i++) {
35702 b = q.andln(0xff);
35703 q.iushrn(8);
35704
35705 res[i] = b;
35706 }
35707
35708 for (; i < reqLength; i++) {
35709 res[i] = 0;
35710 }
35711 }
35712
35713 return res;
35714 };
35715
35716 if (Math.clz32) {
35717 BN.prototype._countBits = function _countBits (w) {
35718 return 32 - Math.clz32(w);
35719 };
35720 } else {
35721 BN.prototype._countBits = function _countBits (w) {
35722 var t = w;
35723 var r = 0;
35724 if (t >= 0x1000) {
35725 r += 13;
35726 t >>>= 13;
35727 }
35728 if (t >= 0x40) {
35729 r += 7;
35730 t >>>= 7;
35731 }
35732 if (t >= 0x8) {
35733 r += 4;
35734 t >>>= 4;
35735 }
35736 if (t >= 0x02) {
35737 r += 2;
35738 t >>>= 2;
35739 }
35740 return r + t;
35741 };
35742 }
35743
35744 BN.prototype._zeroBits = function _zeroBits (w) {
35745 // Short-cut
35746 if (w === 0) return 26;
35747
35748 var t = w;
35749 var r = 0;
35750 if ((t & 0x1fff) === 0) {
35751 r += 13;
35752 t >>>= 13;
35753 }
35754 if ((t & 0x7f) === 0) {
35755 r += 7;
35756 t >>>= 7;
35757 }
35758 if ((t & 0xf) === 0) {
35759 r += 4;
35760 t >>>= 4;
35761 }
35762 if ((t & 0x3) === 0) {
35763 r += 2;
35764 t >>>= 2;
35765 }
35766 if ((t & 0x1) === 0) {
35767 r++;
35768 }
35769 return r;
35770 };
35771
35772 // Return number of used bits in a BN
35773 BN.prototype.bitLength = function bitLength () {
35774 var w = this.words[this.length - 1];
35775 var hi = this._countBits(w);
35776 return (this.length - 1) * 26 + hi;
35777 };
35778
35779 function toBitArray (num) {
35780 var w = new Array(num.bitLength());
35781
35782 for (var bit = 0; bit < w.length; bit++) {
35783 var off = (bit / 26) | 0;
35784 var wbit = bit % 26;
35785
35786 w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
35787 }
35788
35789 return w;
35790 }
35791
35792 // Number of trailing zero bits
35793 BN.prototype.zeroBits = function zeroBits () {
35794 if (this.isZero()) return 0;
35795
35796 var r = 0;
35797 for (var i = 0; i < this.length; i++) {
35798 var b = this._zeroBits(this.words[i]);
35799 r += b;
35800 if (b !== 26) break;
35801 }
35802 return r;
35803 };
35804
35805 BN.prototype.byteLength = function byteLength () {
35806 return Math.ceil(this.bitLength() / 8);
35807 };
35808
35809 BN.prototype.toTwos = function toTwos (width) {
35810 if (this.negative !== 0) {
35811 return this.abs().inotn(width).iaddn(1);
35812 }
35813 return this.clone();
35814 };
35815
35816 BN.prototype.fromTwos = function fromTwos (width) {
35817 if (this.testn(width - 1)) {
35818 return this.notn(width).iaddn(1).ineg();
35819 }
35820 return this.clone();
35821 };
35822
35823 BN.prototype.isNeg = function isNeg () {
35824 return this.negative !== 0;
35825 };
35826
35827 // Return negative clone of `this`
35828 BN.prototype.neg = function neg () {
35829 return this.clone().ineg();
35830 };
35831
35832 BN.prototype.ineg = function ineg () {
35833 if (!this.isZero()) {
35834 this.negative ^= 1;
35835 }
35836
35837 return this;
35838 };
35839
35840 // Or `num` with `this` in-place
35841 BN.prototype.iuor = function iuor (num) {
35842 while (this.length < num.length) {
35843 this.words[this.length++] = 0;
35844 }
35845
35846 for (var i = 0; i < num.length; i++) {
35847 this.words[i] = this.words[i] | num.words[i];
35848 }
35849
35850 return this.strip();
35851 };
35852
35853 BN.prototype.ior = function ior (num) {
35854 assert((this.negative | num.negative) === 0);
35855 return this.iuor(num);
35856 };
35857
35858 // Or `num` with `this`
35859 BN.prototype.or = function or (num) {
35860 if (this.length > num.length) return this.clone().ior(num);
35861 return num.clone().ior(this);
35862 };
35863
35864 BN.prototype.uor = function uor (num) {
35865 if (this.length > num.length) return this.clone().iuor(num);
35866 return num.clone().iuor(this);
35867 };
35868
35869 // And `num` with `this` in-place
35870 BN.prototype.iuand = function iuand (num) {
35871 // b = min-length(num, this)
35872 var b;
35873 if (this.length > num.length) {
35874 b = num;
35875 } else {
35876 b = this;
35877 }
35878
35879 for (var i = 0; i < b.length; i++) {
35880 this.words[i] = this.words[i] & num.words[i];
35881 }
35882
35883 this.length = b.length;
35884
35885 return this.strip();
35886 };
35887
35888 BN.prototype.iand = function iand (num) {
35889 assert((this.negative | num.negative) === 0);
35890 return this.iuand(num);
35891 };
35892
35893 // And `num` with `this`
35894 BN.prototype.and = function and (num) {
35895 if (this.length > num.length) return this.clone().iand(num);
35896 return num.clone().iand(this);
35897 };
35898
35899 BN.prototype.uand = function uand (num) {
35900 if (this.length > num.length) return this.clone().iuand(num);
35901 return num.clone().iuand(this);
35902 };
35903
35904 // Xor `num` with `this` in-place
35905 BN.prototype.iuxor = function iuxor (num) {
35906 // a.length > b.length
35907 var a;
35908 var b;
35909 if (this.length > num.length) {
35910 a = this;
35911 b = num;
35912 } else {
35913 a = num;
35914 b = this;
35915 }
35916
35917 for (var i = 0; i < b.length; i++) {
35918 this.words[i] = a.words[i] ^ b.words[i];
35919 }
35920
35921 if (this !== a) {
35922 for (; i < a.length; i++) {
35923 this.words[i] = a.words[i];
35924 }
35925 }
35926
35927 this.length = a.length;
35928
35929 return this.strip();
35930 };
35931
35932 BN.prototype.ixor = function ixor (num) {
35933 assert((this.negative | num.negative) === 0);
35934 return this.iuxor(num);
35935 };
35936
35937 // Xor `num` with `this`
35938 BN.prototype.xor = function xor (num) {
35939 if (this.length > num.length) return this.clone().ixor(num);
35940 return num.clone().ixor(this);
35941 };
35942
35943 BN.prototype.uxor = function uxor (num) {
35944 if (this.length > num.length) return this.clone().iuxor(num);
35945 return num.clone().iuxor(this);
35946 };
35947
35948 // Not ``this`` with ``width`` bitwidth
35949 BN.prototype.inotn = function inotn (width) {
35950 assert(typeof width === 'number' && width >= 0);
35951
35952 var bytesNeeded = Math.ceil(width / 26) | 0;
35953 var bitsLeft = width % 26;
35954
35955 // Extend the buffer with leading zeroes
35956 this._expand(bytesNeeded);
35957
35958 if (bitsLeft > 0) {
35959 bytesNeeded--;
35960 }
35961
35962 // Handle complete words
35963 for (var i = 0; i < bytesNeeded; i++) {
35964 this.words[i] = ~this.words[i] & 0x3ffffff;
35965 }
35966
35967 // Handle the residue
35968 if (bitsLeft > 0) {
35969 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
35970 }
35971
35972 // And remove leading zeroes
35973 return this.strip();
35974 };
35975
35976 BN.prototype.notn = function notn (width) {
35977 return this.clone().inotn(width);
35978 };
35979
35980 // Set `bit` of `this`
35981 BN.prototype.setn = function setn (bit, val) {
35982 assert(typeof bit === 'number' && bit >= 0);
35983
35984 var off = (bit / 26) | 0;
35985 var wbit = bit % 26;
35986
35987 this._expand(off + 1);
35988
35989 if (val) {
35990 this.words[off] = this.words[off] | (1 << wbit);
35991 } else {
35992 this.words[off] = this.words[off] & ~(1 << wbit);
35993 }
35994
35995 return this.strip();
35996 };
35997
35998 // Add `num` to `this` in-place
35999 BN.prototype.iadd = function iadd (num) {
36000 var r;
36001
36002 // negative + positive
36003 if (this.negative !== 0 && num.negative === 0) {
36004 this.negative = 0;
36005 r = this.isub(num);
36006 this.negative ^= 1;
36007 return this._normSign();
36008
36009 // positive + negative
36010 } else if (this.negative === 0 && num.negative !== 0) {
36011 num.negative = 0;
36012 r = this.isub(num);
36013 num.negative = 1;
36014 return r._normSign();
36015 }
36016
36017 // a.length > b.length
36018 var a, b;
36019 if (this.length > num.length) {
36020 a = this;
36021 b = num;
36022 } else {
36023 a = num;
36024 b = this;
36025 }
36026
36027 var carry = 0;
36028 for (var i = 0; i < b.length; i++) {
36029 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
36030 this.words[i] = r & 0x3ffffff;
36031 carry = r >>> 26;
36032 }
36033 for (; carry !== 0 && i < a.length; i++) {
36034 r = (a.words[i] | 0) + carry;
36035 this.words[i] = r & 0x3ffffff;
36036 carry = r >>> 26;
36037 }
36038
36039 this.length = a.length;
36040 if (carry !== 0) {
36041 this.words[this.length] = carry;
36042 this.length++;
36043 // Copy the rest of the words
36044 } else if (a !== this) {
36045 for (; i < a.length; i++) {
36046 this.words[i] = a.words[i];
36047 }
36048 }
36049
36050 return this;
36051 };
36052
36053 // Add `num` to `this`
36054 BN.prototype.add = function add (num) {
36055 var res;
36056 if (num.negative !== 0 && this.negative === 0) {
36057 num.negative = 0;
36058 res = this.sub(num);
36059 num.negative ^= 1;
36060 return res;
36061 } else if (num.negative === 0 && this.negative !== 0) {
36062 this.negative = 0;
36063 res = num.sub(this);
36064 this.negative = 1;
36065 return res;
36066 }
36067
36068 if (this.length > num.length) return this.clone().iadd(num);
36069
36070 return num.clone().iadd(this);
36071 };
36072
36073 // Subtract `num` from `this` in-place
36074 BN.prototype.isub = function isub (num) {
36075 // this - (-num) = this + num
36076 if (num.negative !== 0) {
36077 num.negative = 0;
36078 var r = this.iadd(num);
36079 num.negative = 1;
36080 return r._normSign();
36081
36082 // -this - num = -(this + num)
36083 } else if (this.negative !== 0) {
36084 this.negative = 0;
36085 this.iadd(num);
36086 this.negative = 1;
36087 return this._normSign();
36088 }
36089
36090 // At this point both numbers are positive
36091 var cmp = this.cmp(num);
36092
36093 // Optimization - zeroify
36094 if (cmp === 0) {
36095 this.negative = 0;
36096 this.length = 1;
36097 this.words[0] = 0;
36098 return this;
36099 }
36100
36101 // a > b
36102 var a, b;
36103 if (cmp > 0) {
36104 a = this;
36105 b = num;
36106 } else {
36107 a = num;
36108 b = this;
36109 }
36110
36111 var carry = 0;
36112 for (var i = 0; i < b.length; i++) {
36113 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
36114 carry = r >> 26;
36115 this.words[i] = r & 0x3ffffff;
36116 }
36117 for (; carry !== 0 && i < a.length; i++) {
36118 r = (a.words[i] | 0) + carry;
36119 carry = r >> 26;
36120 this.words[i] = r & 0x3ffffff;
36121 }
36122
36123 // Copy rest of the words
36124 if (carry === 0 && i < a.length && a !== this) {
36125 for (; i < a.length; i++) {
36126 this.words[i] = a.words[i];
36127 }
36128 }
36129
36130 this.length = Math.max(this.length, i);
36131
36132 if (a !== this) {
36133 this.negative = 1;
36134 }
36135
36136 return this.strip();
36137 };
36138
36139 // Subtract `num` from `this`
36140 BN.prototype.sub = function sub (num) {
36141 return this.clone().isub(num);
36142 };
36143
36144 function smallMulTo (self, num, out) {
36145 out.negative = num.negative ^ self.negative;
36146 var len = (self.length + num.length) | 0;
36147 out.length = len;
36148 len = (len - 1) | 0;
36149
36150 // Peel one iteration (compiler can't do it, because of code complexity)
36151 var a = self.words[0] | 0;
36152 var b = num.words[0] | 0;
36153 var r = a * b;
36154
36155 var lo = r & 0x3ffffff;
36156 var carry = (r / 0x4000000) | 0;
36157 out.words[0] = lo;
36158
36159 for (var k = 1; k < len; k++) {
36160 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
36161 // note that ncarry could be >= 0x3ffffff
36162 var ncarry = carry >>> 26;
36163 var rword = carry & 0x3ffffff;
36164 var maxJ = Math.min(k, num.length - 1);
36165 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
36166 var i = (k - j) | 0;
36167 a = self.words[i] | 0;
36168 b = num.words[j] | 0;
36169 r = a * b + rword;
36170 ncarry += (r / 0x4000000) | 0;
36171 rword = r & 0x3ffffff;
36172 }
36173 out.words[k] = rword | 0;
36174 carry = ncarry | 0;
36175 }
36176 if (carry !== 0) {
36177 out.words[k] = carry | 0;
36178 } else {
36179 out.length--;
36180 }
36181
36182 return out.strip();
36183 }
36184
36185 // TODO(indutny): it may be reasonable to omit it for users who don't need
36186 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
36187 // multiplication (like elliptic secp256k1).
36188 var comb10MulTo = function comb10MulTo (self, num, out) {
36189 var a = self.words;
36190 var b = num.words;
36191 var o = out.words;
36192 var c = 0;
36193 var lo;
36194 var mid;
36195 var hi;
36196 var a0 = a[0] | 0;
36197 var al0 = a0 & 0x1fff;
36198 var ah0 = a0 >>> 13;
36199 var a1 = a[1] | 0;
36200 var al1 = a1 & 0x1fff;
36201 var ah1 = a1 >>> 13;
36202 var a2 = a[2] | 0;
36203 var al2 = a2 & 0x1fff;
36204 var ah2 = a2 >>> 13;
36205 var a3 = a[3] | 0;
36206 var al3 = a3 & 0x1fff;
36207 var ah3 = a3 >>> 13;
36208 var a4 = a[4] | 0;
36209 var al4 = a4 & 0x1fff;
36210 var ah4 = a4 >>> 13;
36211 var a5 = a[5] | 0;
36212 var al5 = a5 & 0x1fff;
36213 var ah5 = a5 >>> 13;
36214 var a6 = a[6] | 0;
36215 var al6 = a6 & 0x1fff;
36216 var ah6 = a6 >>> 13;
36217 var a7 = a[7] | 0;
36218 var al7 = a7 & 0x1fff;
36219 var ah7 = a7 >>> 13;
36220 var a8 = a[8] | 0;
36221 var al8 = a8 & 0x1fff;
36222 var ah8 = a8 >>> 13;
36223 var a9 = a[9] | 0;
36224 var al9 = a9 & 0x1fff;
36225 var ah9 = a9 >>> 13;
36226 var b0 = b[0] | 0;
36227 var bl0 = b0 & 0x1fff;
36228 var bh0 = b0 >>> 13;
36229 var b1 = b[1] | 0;
36230 var bl1 = b1 & 0x1fff;
36231 var bh1 = b1 >>> 13;
36232 var b2 = b[2] | 0;
36233 var bl2 = b2 & 0x1fff;
36234 var bh2 = b2 >>> 13;
36235 var b3 = b[3] | 0;
36236 var bl3 = b3 & 0x1fff;
36237 var bh3 = b3 >>> 13;
36238 var b4 = b[4] | 0;
36239 var bl4 = b4 & 0x1fff;
36240 var bh4 = b4 >>> 13;
36241 var b5 = b[5] | 0;
36242 var bl5 = b5 & 0x1fff;
36243 var bh5 = b5 >>> 13;
36244 var b6 = b[6] | 0;
36245 var bl6 = b6 & 0x1fff;
36246 var bh6 = b6 >>> 13;
36247 var b7 = b[7] | 0;
36248 var bl7 = b7 & 0x1fff;
36249 var bh7 = b7 >>> 13;
36250 var b8 = b[8] | 0;
36251 var bl8 = b8 & 0x1fff;
36252 var bh8 = b8 >>> 13;
36253 var b9 = b[9] | 0;
36254 var bl9 = b9 & 0x1fff;
36255 var bh9 = b9 >>> 13;
36256
36257 out.negative = self.negative ^ num.negative;
36258 out.length = 19;
36259 /* k = 0 */
36260 lo = Math.imul(al0, bl0);
36261 mid = Math.imul(al0, bh0);
36262 mid = (mid + Math.imul(ah0, bl0)) | 0;
36263 hi = Math.imul(ah0, bh0);
36264 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36265 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
36266 w0 &= 0x3ffffff;
36267 /* k = 1 */
36268 lo = Math.imul(al1, bl0);
36269 mid = Math.imul(al1, bh0);
36270 mid = (mid + Math.imul(ah1, bl0)) | 0;
36271 hi = Math.imul(ah1, bh0);
36272 lo = (lo + Math.imul(al0, bl1)) | 0;
36273 mid = (mid + Math.imul(al0, bh1)) | 0;
36274 mid = (mid + Math.imul(ah0, bl1)) | 0;
36275 hi = (hi + Math.imul(ah0, bh1)) | 0;
36276 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36277 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
36278 w1 &= 0x3ffffff;
36279 /* k = 2 */
36280 lo = Math.imul(al2, bl0);
36281 mid = Math.imul(al2, bh0);
36282 mid = (mid + Math.imul(ah2, bl0)) | 0;
36283 hi = Math.imul(ah2, bh0);
36284 lo = (lo + Math.imul(al1, bl1)) | 0;
36285 mid = (mid + Math.imul(al1, bh1)) | 0;
36286 mid = (mid + Math.imul(ah1, bl1)) | 0;
36287 hi = (hi + Math.imul(ah1, bh1)) | 0;
36288 lo = (lo + Math.imul(al0, bl2)) | 0;
36289 mid = (mid + Math.imul(al0, bh2)) | 0;
36290 mid = (mid + Math.imul(ah0, bl2)) | 0;
36291 hi = (hi + Math.imul(ah0, bh2)) | 0;
36292 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36293 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
36294 w2 &= 0x3ffffff;
36295 /* k = 3 */
36296 lo = Math.imul(al3, bl0);
36297 mid = Math.imul(al3, bh0);
36298 mid = (mid + Math.imul(ah3, bl0)) | 0;
36299 hi = Math.imul(ah3, bh0);
36300 lo = (lo + Math.imul(al2, bl1)) | 0;
36301 mid = (mid + Math.imul(al2, bh1)) | 0;
36302 mid = (mid + Math.imul(ah2, bl1)) | 0;
36303 hi = (hi + Math.imul(ah2, bh1)) | 0;
36304 lo = (lo + Math.imul(al1, bl2)) | 0;
36305 mid = (mid + Math.imul(al1, bh2)) | 0;
36306 mid = (mid + Math.imul(ah1, bl2)) | 0;
36307 hi = (hi + Math.imul(ah1, bh2)) | 0;
36308 lo = (lo + Math.imul(al0, bl3)) | 0;
36309 mid = (mid + Math.imul(al0, bh3)) | 0;
36310 mid = (mid + Math.imul(ah0, bl3)) | 0;
36311 hi = (hi + Math.imul(ah0, bh3)) | 0;
36312 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36313 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
36314 w3 &= 0x3ffffff;
36315 /* k = 4 */
36316 lo = Math.imul(al4, bl0);
36317 mid = Math.imul(al4, bh0);
36318 mid = (mid + Math.imul(ah4, bl0)) | 0;
36319 hi = Math.imul(ah4, bh0);
36320 lo = (lo + Math.imul(al3, bl1)) | 0;
36321 mid = (mid + Math.imul(al3, bh1)) | 0;
36322 mid = (mid + Math.imul(ah3, bl1)) | 0;
36323 hi = (hi + Math.imul(ah3, bh1)) | 0;
36324 lo = (lo + Math.imul(al2, bl2)) | 0;
36325 mid = (mid + Math.imul(al2, bh2)) | 0;
36326 mid = (mid + Math.imul(ah2, bl2)) | 0;
36327 hi = (hi + Math.imul(ah2, bh2)) | 0;
36328 lo = (lo + Math.imul(al1, bl3)) | 0;
36329 mid = (mid + Math.imul(al1, bh3)) | 0;
36330 mid = (mid + Math.imul(ah1, bl3)) | 0;
36331 hi = (hi + Math.imul(ah1, bh3)) | 0;
36332 lo = (lo + Math.imul(al0, bl4)) | 0;
36333 mid = (mid + Math.imul(al0, bh4)) | 0;
36334 mid = (mid + Math.imul(ah0, bl4)) | 0;
36335 hi = (hi + Math.imul(ah0, bh4)) | 0;
36336 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36337 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
36338 w4 &= 0x3ffffff;
36339 /* k = 5 */
36340 lo = Math.imul(al5, bl0);
36341 mid = Math.imul(al5, bh0);
36342 mid = (mid + Math.imul(ah5, bl0)) | 0;
36343 hi = Math.imul(ah5, bh0);
36344 lo = (lo + Math.imul(al4, bl1)) | 0;
36345 mid = (mid + Math.imul(al4, bh1)) | 0;
36346 mid = (mid + Math.imul(ah4, bl1)) | 0;
36347 hi = (hi + Math.imul(ah4, bh1)) | 0;
36348 lo = (lo + Math.imul(al3, bl2)) | 0;
36349 mid = (mid + Math.imul(al3, bh2)) | 0;
36350 mid = (mid + Math.imul(ah3, bl2)) | 0;
36351 hi = (hi + Math.imul(ah3, bh2)) | 0;
36352 lo = (lo + Math.imul(al2, bl3)) | 0;
36353 mid = (mid + Math.imul(al2, bh3)) | 0;
36354 mid = (mid + Math.imul(ah2, bl3)) | 0;
36355 hi = (hi + Math.imul(ah2, bh3)) | 0;
36356 lo = (lo + Math.imul(al1, bl4)) | 0;
36357 mid = (mid + Math.imul(al1, bh4)) | 0;
36358 mid = (mid + Math.imul(ah1, bl4)) | 0;
36359 hi = (hi + Math.imul(ah1, bh4)) | 0;
36360 lo = (lo + Math.imul(al0, bl5)) | 0;
36361 mid = (mid + Math.imul(al0, bh5)) | 0;
36362 mid = (mid + Math.imul(ah0, bl5)) | 0;
36363 hi = (hi + Math.imul(ah0, bh5)) | 0;
36364 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36365 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
36366 w5 &= 0x3ffffff;
36367 /* k = 6 */
36368 lo = Math.imul(al6, bl0);
36369 mid = Math.imul(al6, bh0);
36370 mid = (mid + Math.imul(ah6, bl0)) | 0;
36371 hi = Math.imul(ah6, bh0);
36372 lo = (lo + Math.imul(al5, bl1)) | 0;
36373 mid = (mid + Math.imul(al5, bh1)) | 0;
36374 mid = (mid + Math.imul(ah5, bl1)) | 0;
36375 hi = (hi + Math.imul(ah5, bh1)) | 0;
36376 lo = (lo + Math.imul(al4, bl2)) | 0;
36377 mid = (mid + Math.imul(al4, bh2)) | 0;
36378 mid = (mid + Math.imul(ah4, bl2)) | 0;
36379 hi = (hi + Math.imul(ah4, bh2)) | 0;
36380 lo = (lo + Math.imul(al3, bl3)) | 0;
36381 mid = (mid + Math.imul(al3, bh3)) | 0;
36382 mid = (mid + Math.imul(ah3, bl3)) | 0;
36383 hi = (hi + Math.imul(ah3, bh3)) | 0;
36384 lo = (lo + Math.imul(al2, bl4)) | 0;
36385 mid = (mid + Math.imul(al2, bh4)) | 0;
36386 mid = (mid + Math.imul(ah2, bl4)) | 0;
36387 hi = (hi + Math.imul(ah2, bh4)) | 0;
36388 lo = (lo + Math.imul(al1, bl5)) | 0;
36389 mid = (mid + Math.imul(al1, bh5)) | 0;
36390 mid = (mid + Math.imul(ah1, bl5)) | 0;
36391 hi = (hi + Math.imul(ah1, bh5)) | 0;
36392 lo = (lo + Math.imul(al0, bl6)) | 0;
36393 mid = (mid + Math.imul(al0, bh6)) | 0;
36394 mid = (mid + Math.imul(ah0, bl6)) | 0;
36395 hi = (hi + Math.imul(ah0, bh6)) | 0;
36396 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36397 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
36398 w6 &= 0x3ffffff;
36399 /* k = 7 */
36400 lo = Math.imul(al7, bl0);
36401 mid = Math.imul(al7, bh0);
36402 mid = (mid + Math.imul(ah7, bl0)) | 0;
36403 hi = Math.imul(ah7, bh0);
36404 lo = (lo + Math.imul(al6, bl1)) | 0;
36405 mid = (mid + Math.imul(al6, bh1)) | 0;
36406 mid = (mid + Math.imul(ah6, bl1)) | 0;
36407 hi = (hi + Math.imul(ah6, bh1)) | 0;
36408 lo = (lo + Math.imul(al5, bl2)) | 0;
36409 mid = (mid + Math.imul(al5, bh2)) | 0;
36410 mid = (mid + Math.imul(ah5, bl2)) | 0;
36411 hi = (hi + Math.imul(ah5, bh2)) | 0;
36412 lo = (lo + Math.imul(al4, bl3)) | 0;
36413 mid = (mid + Math.imul(al4, bh3)) | 0;
36414 mid = (mid + Math.imul(ah4, bl3)) | 0;
36415 hi = (hi + Math.imul(ah4, bh3)) | 0;
36416 lo = (lo + Math.imul(al3, bl4)) | 0;
36417 mid = (mid + Math.imul(al3, bh4)) | 0;
36418 mid = (mid + Math.imul(ah3, bl4)) | 0;
36419 hi = (hi + Math.imul(ah3, bh4)) | 0;
36420 lo = (lo + Math.imul(al2, bl5)) | 0;
36421 mid = (mid + Math.imul(al2, bh5)) | 0;
36422 mid = (mid + Math.imul(ah2, bl5)) | 0;
36423 hi = (hi + Math.imul(ah2, bh5)) | 0;
36424 lo = (lo + Math.imul(al1, bl6)) | 0;
36425 mid = (mid + Math.imul(al1, bh6)) | 0;
36426 mid = (mid + Math.imul(ah1, bl6)) | 0;
36427 hi = (hi + Math.imul(ah1, bh6)) | 0;
36428 lo = (lo + Math.imul(al0, bl7)) | 0;
36429 mid = (mid + Math.imul(al0, bh7)) | 0;
36430 mid = (mid + Math.imul(ah0, bl7)) | 0;
36431 hi = (hi + Math.imul(ah0, bh7)) | 0;
36432 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36433 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
36434 w7 &= 0x3ffffff;
36435 /* k = 8 */
36436 lo = Math.imul(al8, bl0);
36437 mid = Math.imul(al8, bh0);
36438 mid = (mid + Math.imul(ah8, bl0)) | 0;
36439 hi = Math.imul(ah8, bh0);
36440 lo = (lo + Math.imul(al7, bl1)) | 0;
36441 mid = (mid + Math.imul(al7, bh1)) | 0;
36442 mid = (mid + Math.imul(ah7, bl1)) | 0;
36443 hi = (hi + Math.imul(ah7, bh1)) | 0;
36444 lo = (lo + Math.imul(al6, bl2)) | 0;
36445 mid = (mid + Math.imul(al6, bh2)) | 0;
36446 mid = (mid + Math.imul(ah6, bl2)) | 0;
36447 hi = (hi + Math.imul(ah6, bh2)) | 0;
36448 lo = (lo + Math.imul(al5, bl3)) | 0;
36449 mid = (mid + Math.imul(al5, bh3)) | 0;
36450 mid = (mid + Math.imul(ah5, bl3)) | 0;
36451 hi = (hi + Math.imul(ah5, bh3)) | 0;
36452 lo = (lo + Math.imul(al4, bl4)) | 0;
36453 mid = (mid + Math.imul(al4, bh4)) | 0;
36454 mid = (mid + Math.imul(ah4, bl4)) | 0;
36455 hi = (hi + Math.imul(ah4, bh4)) | 0;
36456 lo = (lo + Math.imul(al3, bl5)) | 0;
36457 mid = (mid + Math.imul(al3, bh5)) | 0;
36458 mid = (mid + Math.imul(ah3, bl5)) | 0;
36459 hi = (hi + Math.imul(ah3, bh5)) | 0;
36460 lo = (lo + Math.imul(al2, bl6)) | 0;
36461 mid = (mid + Math.imul(al2, bh6)) | 0;
36462 mid = (mid + Math.imul(ah2, bl6)) | 0;
36463 hi = (hi + Math.imul(ah2, bh6)) | 0;
36464 lo = (lo + Math.imul(al1, bl7)) | 0;
36465 mid = (mid + Math.imul(al1, bh7)) | 0;
36466 mid = (mid + Math.imul(ah1, bl7)) | 0;
36467 hi = (hi + Math.imul(ah1, bh7)) | 0;
36468 lo = (lo + Math.imul(al0, bl8)) | 0;
36469 mid = (mid + Math.imul(al0, bh8)) | 0;
36470 mid = (mid + Math.imul(ah0, bl8)) | 0;
36471 hi = (hi + Math.imul(ah0, bh8)) | 0;
36472 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36473 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
36474 w8 &= 0x3ffffff;
36475 /* k = 9 */
36476 lo = Math.imul(al9, bl0);
36477 mid = Math.imul(al9, bh0);
36478 mid = (mid + Math.imul(ah9, bl0)) | 0;
36479 hi = Math.imul(ah9, bh0);
36480 lo = (lo + Math.imul(al8, bl1)) | 0;
36481 mid = (mid + Math.imul(al8, bh1)) | 0;
36482 mid = (mid + Math.imul(ah8, bl1)) | 0;
36483 hi = (hi + Math.imul(ah8, bh1)) | 0;
36484 lo = (lo + Math.imul(al7, bl2)) | 0;
36485 mid = (mid + Math.imul(al7, bh2)) | 0;
36486 mid = (mid + Math.imul(ah7, bl2)) | 0;
36487 hi = (hi + Math.imul(ah7, bh2)) | 0;
36488 lo = (lo + Math.imul(al6, bl3)) | 0;
36489 mid = (mid + Math.imul(al6, bh3)) | 0;
36490 mid = (mid + Math.imul(ah6, bl3)) | 0;
36491 hi = (hi + Math.imul(ah6, bh3)) | 0;
36492 lo = (lo + Math.imul(al5, bl4)) | 0;
36493 mid = (mid + Math.imul(al5, bh4)) | 0;
36494 mid = (mid + Math.imul(ah5, bl4)) | 0;
36495 hi = (hi + Math.imul(ah5, bh4)) | 0;
36496 lo = (lo + Math.imul(al4, bl5)) | 0;
36497 mid = (mid + Math.imul(al4, bh5)) | 0;
36498 mid = (mid + Math.imul(ah4, bl5)) | 0;
36499 hi = (hi + Math.imul(ah4, bh5)) | 0;
36500 lo = (lo + Math.imul(al3, bl6)) | 0;
36501 mid = (mid + Math.imul(al3, bh6)) | 0;
36502 mid = (mid + Math.imul(ah3, bl6)) | 0;
36503 hi = (hi + Math.imul(ah3, bh6)) | 0;
36504 lo = (lo + Math.imul(al2, bl7)) | 0;
36505 mid = (mid + Math.imul(al2, bh7)) | 0;
36506 mid = (mid + Math.imul(ah2, bl7)) | 0;
36507 hi = (hi + Math.imul(ah2, bh7)) | 0;
36508 lo = (lo + Math.imul(al1, bl8)) | 0;
36509 mid = (mid + Math.imul(al1, bh8)) | 0;
36510 mid = (mid + Math.imul(ah1, bl8)) | 0;
36511 hi = (hi + Math.imul(ah1, bh8)) | 0;
36512 lo = (lo + Math.imul(al0, bl9)) | 0;
36513 mid = (mid + Math.imul(al0, bh9)) | 0;
36514 mid = (mid + Math.imul(ah0, bl9)) | 0;
36515 hi = (hi + Math.imul(ah0, bh9)) | 0;
36516 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36517 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
36518 w9 &= 0x3ffffff;
36519 /* k = 10 */
36520 lo = Math.imul(al9, bl1);
36521 mid = Math.imul(al9, bh1);
36522 mid = (mid + Math.imul(ah9, bl1)) | 0;
36523 hi = Math.imul(ah9, bh1);
36524 lo = (lo + Math.imul(al8, bl2)) | 0;
36525 mid = (mid + Math.imul(al8, bh2)) | 0;
36526 mid = (mid + Math.imul(ah8, bl2)) | 0;
36527 hi = (hi + Math.imul(ah8, bh2)) | 0;
36528 lo = (lo + Math.imul(al7, bl3)) | 0;
36529 mid = (mid + Math.imul(al7, bh3)) | 0;
36530 mid = (mid + Math.imul(ah7, bl3)) | 0;
36531 hi = (hi + Math.imul(ah7, bh3)) | 0;
36532 lo = (lo + Math.imul(al6, bl4)) | 0;
36533 mid = (mid + Math.imul(al6, bh4)) | 0;
36534 mid = (mid + Math.imul(ah6, bl4)) | 0;
36535 hi = (hi + Math.imul(ah6, bh4)) | 0;
36536 lo = (lo + Math.imul(al5, bl5)) | 0;
36537 mid = (mid + Math.imul(al5, bh5)) | 0;
36538 mid = (mid + Math.imul(ah5, bl5)) | 0;
36539 hi = (hi + Math.imul(ah5, bh5)) | 0;
36540 lo = (lo + Math.imul(al4, bl6)) | 0;
36541 mid = (mid + Math.imul(al4, bh6)) | 0;
36542 mid = (mid + Math.imul(ah4, bl6)) | 0;
36543 hi = (hi + Math.imul(ah4, bh6)) | 0;
36544 lo = (lo + Math.imul(al3, bl7)) | 0;
36545 mid = (mid + Math.imul(al3, bh7)) | 0;
36546 mid = (mid + Math.imul(ah3, bl7)) | 0;
36547 hi = (hi + Math.imul(ah3, bh7)) | 0;
36548 lo = (lo + Math.imul(al2, bl8)) | 0;
36549 mid = (mid + Math.imul(al2, bh8)) | 0;
36550 mid = (mid + Math.imul(ah2, bl8)) | 0;
36551 hi = (hi + Math.imul(ah2, bh8)) | 0;
36552 lo = (lo + Math.imul(al1, bl9)) | 0;
36553 mid = (mid + Math.imul(al1, bh9)) | 0;
36554 mid = (mid + Math.imul(ah1, bl9)) | 0;
36555 hi = (hi + Math.imul(ah1, bh9)) | 0;
36556 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36557 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
36558 w10 &= 0x3ffffff;
36559 /* k = 11 */
36560 lo = Math.imul(al9, bl2);
36561 mid = Math.imul(al9, bh2);
36562 mid = (mid + Math.imul(ah9, bl2)) | 0;
36563 hi = Math.imul(ah9, bh2);
36564 lo = (lo + Math.imul(al8, bl3)) | 0;
36565 mid = (mid + Math.imul(al8, bh3)) | 0;
36566 mid = (mid + Math.imul(ah8, bl3)) | 0;
36567 hi = (hi + Math.imul(ah8, bh3)) | 0;
36568 lo = (lo + Math.imul(al7, bl4)) | 0;
36569 mid = (mid + Math.imul(al7, bh4)) | 0;
36570 mid = (mid + Math.imul(ah7, bl4)) | 0;
36571 hi = (hi + Math.imul(ah7, bh4)) | 0;
36572 lo = (lo + Math.imul(al6, bl5)) | 0;
36573 mid = (mid + Math.imul(al6, bh5)) | 0;
36574 mid = (mid + Math.imul(ah6, bl5)) | 0;
36575 hi = (hi + Math.imul(ah6, bh5)) | 0;
36576 lo = (lo + Math.imul(al5, bl6)) | 0;
36577 mid = (mid + Math.imul(al5, bh6)) | 0;
36578 mid = (mid + Math.imul(ah5, bl6)) | 0;
36579 hi = (hi + Math.imul(ah5, bh6)) | 0;
36580 lo = (lo + Math.imul(al4, bl7)) | 0;
36581 mid = (mid + Math.imul(al4, bh7)) | 0;
36582 mid = (mid + Math.imul(ah4, bl7)) | 0;
36583 hi = (hi + Math.imul(ah4, bh7)) | 0;
36584 lo = (lo + Math.imul(al3, bl8)) | 0;
36585 mid = (mid + Math.imul(al3, bh8)) | 0;
36586 mid = (mid + Math.imul(ah3, bl8)) | 0;
36587 hi = (hi + Math.imul(ah3, bh8)) | 0;
36588 lo = (lo + Math.imul(al2, bl9)) | 0;
36589 mid = (mid + Math.imul(al2, bh9)) | 0;
36590 mid = (mid + Math.imul(ah2, bl9)) | 0;
36591 hi = (hi + Math.imul(ah2, bh9)) | 0;
36592 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36593 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
36594 w11 &= 0x3ffffff;
36595 /* k = 12 */
36596 lo = Math.imul(al9, bl3);
36597 mid = Math.imul(al9, bh3);
36598 mid = (mid + Math.imul(ah9, bl3)) | 0;
36599 hi = Math.imul(ah9, bh3);
36600 lo = (lo + Math.imul(al8, bl4)) | 0;
36601 mid = (mid + Math.imul(al8, bh4)) | 0;
36602 mid = (mid + Math.imul(ah8, bl4)) | 0;
36603 hi = (hi + Math.imul(ah8, bh4)) | 0;
36604 lo = (lo + Math.imul(al7, bl5)) | 0;
36605 mid = (mid + Math.imul(al7, bh5)) | 0;
36606 mid = (mid + Math.imul(ah7, bl5)) | 0;
36607 hi = (hi + Math.imul(ah7, bh5)) | 0;
36608 lo = (lo + Math.imul(al6, bl6)) | 0;
36609 mid = (mid + Math.imul(al6, bh6)) | 0;
36610 mid = (mid + Math.imul(ah6, bl6)) | 0;
36611 hi = (hi + Math.imul(ah6, bh6)) | 0;
36612 lo = (lo + Math.imul(al5, bl7)) | 0;
36613 mid = (mid + Math.imul(al5, bh7)) | 0;
36614 mid = (mid + Math.imul(ah5, bl7)) | 0;
36615 hi = (hi + Math.imul(ah5, bh7)) | 0;
36616 lo = (lo + Math.imul(al4, bl8)) | 0;
36617 mid = (mid + Math.imul(al4, bh8)) | 0;
36618 mid = (mid + Math.imul(ah4, bl8)) | 0;
36619 hi = (hi + Math.imul(ah4, bh8)) | 0;
36620 lo = (lo + Math.imul(al3, bl9)) | 0;
36621 mid = (mid + Math.imul(al3, bh9)) | 0;
36622 mid = (mid + Math.imul(ah3, bl9)) | 0;
36623 hi = (hi + Math.imul(ah3, bh9)) | 0;
36624 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36625 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
36626 w12 &= 0x3ffffff;
36627 /* k = 13 */
36628 lo = Math.imul(al9, bl4);
36629 mid = Math.imul(al9, bh4);
36630 mid = (mid + Math.imul(ah9, bl4)) | 0;
36631 hi = Math.imul(ah9, bh4);
36632 lo = (lo + Math.imul(al8, bl5)) | 0;
36633 mid = (mid + Math.imul(al8, bh5)) | 0;
36634 mid = (mid + Math.imul(ah8, bl5)) | 0;
36635 hi = (hi + Math.imul(ah8, bh5)) | 0;
36636 lo = (lo + Math.imul(al7, bl6)) | 0;
36637 mid = (mid + Math.imul(al7, bh6)) | 0;
36638 mid = (mid + Math.imul(ah7, bl6)) | 0;
36639 hi = (hi + Math.imul(ah7, bh6)) | 0;
36640 lo = (lo + Math.imul(al6, bl7)) | 0;
36641 mid = (mid + Math.imul(al6, bh7)) | 0;
36642 mid = (mid + Math.imul(ah6, bl7)) | 0;
36643 hi = (hi + Math.imul(ah6, bh7)) | 0;
36644 lo = (lo + Math.imul(al5, bl8)) | 0;
36645 mid = (mid + Math.imul(al5, bh8)) | 0;
36646 mid = (mid + Math.imul(ah5, bl8)) | 0;
36647 hi = (hi + Math.imul(ah5, bh8)) | 0;
36648 lo = (lo + Math.imul(al4, bl9)) | 0;
36649 mid = (mid + Math.imul(al4, bh9)) | 0;
36650 mid = (mid + Math.imul(ah4, bl9)) | 0;
36651 hi = (hi + Math.imul(ah4, bh9)) | 0;
36652 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36653 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
36654 w13 &= 0x3ffffff;
36655 /* k = 14 */
36656 lo = Math.imul(al9, bl5);
36657 mid = Math.imul(al9, bh5);
36658 mid = (mid + Math.imul(ah9, bl5)) | 0;
36659 hi = Math.imul(ah9, bh5);
36660 lo = (lo + Math.imul(al8, bl6)) | 0;
36661 mid = (mid + Math.imul(al8, bh6)) | 0;
36662 mid = (mid + Math.imul(ah8, bl6)) | 0;
36663 hi = (hi + Math.imul(ah8, bh6)) | 0;
36664 lo = (lo + Math.imul(al7, bl7)) | 0;
36665 mid = (mid + Math.imul(al7, bh7)) | 0;
36666 mid = (mid + Math.imul(ah7, bl7)) | 0;
36667 hi = (hi + Math.imul(ah7, bh7)) | 0;
36668 lo = (lo + Math.imul(al6, bl8)) | 0;
36669 mid = (mid + Math.imul(al6, bh8)) | 0;
36670 mid = (mid + Math.imul(ah6, bl8)) | 0;
36671 hi = (hi + Math.imul(ah6, bh8)) | 0;
36672 lo = (lo + Math.imul(al5, bl9)) | 0;
36673 mid = (mid + Math.imul(al5, bh9)) | 0;
36674 mid = (mid + Math.imul(ah5, bl9)) | 0;
36675 hi = (hi + Math.imul(ah5, bh9)) | 0;
36676 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36677 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
36678 w14 &= 0x3ffffff;
36679 /* k = 15 */
36680 lo = Math.imul(al9, bl6);
36681 mid = Math.imul(al9, bh6);
36682 mid = (mid + Math.imul(ah9, bl6)) | 0;
36683 hi = Math.imul(ah9, bh6);
36684 lo = (lo + Math.imul(al8, bl7)) | 0;
36685 mid = (mid + Math.imul(al8, bh7)) | 0;
36686 mid = (mid + Math.imul(ah8, bl7)) | 0;
36687 hi = (hi + Math.imul(ah8, bh7)) | 0;
36688 lo = (lo + Math.imul(al7, bl8)) | 0;
36689 mid = (mid + Math.imul(al7, bh8)) | 0;
36690 mid = (mid + Math.imul(ah7, bl8)) | 0;
36691 hi = (hi + Math.imul(ah7, bh8)) | 0;
36692 lo = (lo + Math.imul(al6, bl9)) | 0;
36693 mid = (mid + Math.imul(al6, bh9)) | 0;
36694 mid = (mid + Math.imul(ah6, bl9)) | 0;
36695 hi = (hi + Math.imul(ah6, bh9)) | 0;
36696 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36697 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
36698 w15 &= 0x3ffffff;
36699 /* k = 16 */
36700 lo = Math.imul(al9, bl7);
36701 mid = Math.imul(al9, bh7);
36702 mid = (mid + Math.imul(ah9, bl7)) | 0;
36703 hi = Math.imul(ah9, bh7);
36704 lo = (lo + Math.imul(al8, bl8)) | 0;
36705 mid = (mid + Math.imul(al8, bh8)) | 0;
36706 mid = (mid + Math.imul(ah8, bl8)) | 0;
36707 hi = (hi + Math.imul(ah8, bh8)) | 0;
36708 lo = (lo + Math.imul(al7, bl9)) | 0;
36709 mid = (mid + Math.imul(al7, bh9)) | 0;
36710 mid = (mid + Math.imul(ah7, bl9)) | 0;
36711 hi = (hi + Math.imul(ah7, bh9)) | 0;
36712 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36713 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
36714 w16 &= 0x3ffffff;
36715 /* k = 17 */
36716 lo = Math.imul(al9, bl8);
36717 mid = Math.imul(al9, bh8);
36718 mid = (mid + Math.imul(ah9, bl8)) | 0;
36719 hi = Math.imul(ah9, bh8);
36720 lo = (lo + Math.imul(al8, bl9)) | 0;
36721 mid = (mid + Math.imul(al8, bh9)) | 0;
36722 mid = (mid + Math.imul(ah8, bl9)) | 0;
36723 hi = (hi + Math.imul(ah8, bh9)) | 0;
36724 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36725 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
36726 w17 &= 0x3ffffff;
36727 /* k = 18 */
36728 lo = Math.imul(al9, bl9);
36729 mid = Math.imul(al9, bh9);
36730 mid = (mid + Math.imul(ah9, bl9)) | 0;
36731 hi = Math.imul(ah9, bh9);
36732 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
36733 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
36734 w18 &= 0x3ffffff;
36735 o[0] = w0;
36736 o[1] = w1;
36737 o[2] = w2;
36738 o[3] = w3;
36739 o[4] = w4;
36740 o[5] = w5;
36741 o[6] = w6;
36742 o[7] = w7;
36743 o[8] = w8;
36744 o[9] = w9;
36745 o[10] = w10;
36746 o[11] = w11;
36747 o[12] = w12;
36748 o[13] = w13;
36749 o[14] = w14;
36750 o[15] = w15;
36751 o[16] = w16;
36752 o[17] = w17;
36753 o[18] = w18;
36754 if (c !== 0) {
36755 o[19] = c;
36756 out.length++;
36757 }
36758 return out;
36759 };
36760
36761 // Polyfill comb
36762 if (!Math.imul) {
36763 comb10MulTo = smallMulTo;
36764 }
36765
36766 function bigMulTo (self, num, out) {
36767 out.negative = num.negative ^ self.negative;
36768 out.length = self.length + num.length;
36769
36770 var carry = 0;
36771 var hncarry = 0;
36772 for (var k = 0; k < out.length - 1; k++) {
36773 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
36774 // note that ncarry could be >= 0x3ffffff
36775 var ncarry = hncarry;
36776 hncarry = 0;
36777 var rword = carry & 0x3ffffff;
36778 var maxJ = Math.min(k, num.length - 1);
36779 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
36780 var i = k - j;
36781 var a = self.words[i] | 0;
36782 var b = num.words[j] | 0;
36783 var r = a * b;
36784
36785 var lo = r & 0x3ffffff;
36786 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
36787 lo = (lo + rword) | 0;
36788 rword = lo & 0x3ffffff;
36789 ncarry = (ncarry + (lo >>> 26)) | 0;
36790
36791 hncarry += ncarry >>> 26;
36792 ncarry &= 0x3ffffff;
36793 }
36794 out.words[k] = rword;
36795 carry = ncarry;
36796 ncarry = hncarry;
36797 }
36798 if (carry !== 0) {
36799 out.words[k] = carry;
36800 } else {
36801 out.length--;
36802 }
36803
36804 return out.strip();
36805 }
36806
36807 function jumboMulTo (self, num, out) {
36808 var fftm = new FFTM();
36809 return fftm.mulp(self, num, out);
36810 }
36811
36812 BN.prototype.mulTo = function mulTo (num, out) {
36813 var res;
36814 var len = this.length + num.length;
36815 if (this.length === 10 && num.length === 10) {
36816 res = comb10MulTo(this, num, out);
36817 } else if (len < 63) {
36818 res = smallMulTo(this, num, out);
36819 } else if (len < 1024) {
36820 res = bigMulTo(this, num, out);
36821 } else {
36822 res = jumboMulTo(this, num, out);
36823 }
36824
36825 return res;
36826 };
36827
36828 // Cooley-Tukey algorithm for FFT
36829 // slightly revisited to rely on looping instead of recursion
36830
36831 function FFTM (x, y) {
36832 this.x = x;
36833 this.y = y;
36834 }
36835
36836 FFTM.prototype.makeRBT = function makeRBT (N) {
36837 var t = new Array(N);
36838 var l = BN.prototype._countBits(N) - 1;
36839 for (var i = 0; i < N; i++) {
36840 t[i] = this.revBin(i, l, N);
36841 }
36842
36843 return t;
36844 };
36845
36846 // Returns binary-reversed representation of `x`
36847 FFTM.prototype.revBin = function revBin (x, l, N) {
36848 if (x === 0 || x === N - 1) return x;
36849
36850 var rb = 0;
36851 for (var i = 0; i < l; i++) {
36852 rb |= (x & 1) << (l - i - 1);
36853 x >>= 1;
36854 }
36855
36856 return rb;
36857 };
36858
36859 // Performs "tweedling" phase, therefore 'emulating'
36860 // behaviour of the recursive algorithm
36861 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
36862 for (var i = 0; i < N; i++) {
36863 rtws[i] = rws[rbt[i]];
36864 itws[i] = iws[rbt[i]];
36865 }
36866 };
36867
36868 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
36869 this.permute(rbt, rws, iws, rtws, itws, N);
36870
36871 for (var s = 1; s < N; s <<= 1) {
36872 var l = s << 1;
36873
36874 var rtwdf = Math.cos(2 * Math.PI / l);
36875 var itwdf = Math.sin(2 * Math.PI / l);
36876
36877 for (var p = 0; p < N; p += l) {
36878 var rtwdf_ = rtwdf;
36879 var itwdf_ = itwdf;
36880
36881 for (var j = 0; j < s; j++) {
36882 var re = rtws[p + j];
36883 var ie = itws[p + j];
36884
36885 var ro = rtws[p + j + s];
36886 var io = itws[p + j + s];
36887
36888 var rx = rtwdf_ * ro - itwdf_ * io;
36889
36890 io = rtwdf_ * io + itwdf_ * ro;
36891 ro = rx;
36892
36893 rtws[p + j] = re + ro;
36894 itws[p + j] = ie + io;
36895
36896 rtws[p + j + s] = re - ro;
36897 itws[p + j + s] = ie - io;
36898
36899 /* jshint maxdepth : false */
36900 if (j !== l) {
36901 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
36902
36903 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
36904 rtwdf_ = rx;
36905 }
36906 }
36907 }
36908 }
36909 };
36910
36911 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
36912 var N = Math.max(m, n) | 1;
36913 var odd = N & 1;
36914 var i = 0;
36915 for (N = N / 2 | 0; N; N = N >>> 1) {
36916 i++;
36917 }
36918
36919 return 1 << i + 1 + odd;
36920 };
36921
36922 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
36923 if (N <= 1) return;
36924
36925 for (var i = 0; i < N / 2; i++) {
36926 var t = rws[i];
36927
36928 rws[i] = rws[N - i - 1];
36929 rws[N - i - 1] = t;
36930
36931 t = iws[i];
36932
36933 iws[i] = -iws[N - i - 1];
36934 iws[N - i - 1] = -t;
36935 }
36936 };
36937
36938 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
36939 var carry = 0;
36940 for (var i = 0; i < N / 2; i++) {
36941 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
36942 Math.round(ws[2 * i] / N) +
36943 carry;
36944
36945 ws[i] = w & 0x3ffffff;
36946
36947 if (w < 0x4000000) {
36948 carry = 0;
36949 } else {
36950 carry = w / 0x4000000 | 0;
36951 }
36952 }
36953
36954 return ws;
36955 };
36956
36957 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
36958 var carry = 0;
36959 for (var i = 0; i < len; i++) {
36960 carry = carry + (ws[i] | 0);
36961
36962 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
36963 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
36964 }
36965
36966 // Pad with zeroes
36967 for (i = 2 * len; i < N; ++i) {
36968 rws[i] = 0;
36969 }
36970
36971 assert(carry === 0);
36972 assert((carry & ~0x1fff) === 0);
36973 };
36974
36975 FFTM.prototype.stub = function stub (N) {
36976 var ph = new Array(N);
36977 for (var i = 0; i < N; i++) {
36978 ph[i] = 0;
36979 }
36980
36981 return ph;
36982 };
36983
36984 FFTM.prototype.mulp = function mulp (x, y, out) {
36985 var N = 2 * this.guessLen13b(x.length, y.length);
36986
36987 var rbt = this.makeRBT(N);
36988
36989 var _ = this.stub(N);
36990
36991 var rws = new Array(N);
36992 var rwst = new Array(N);
36993 var iwst = new Array(N);
36994
36995 var nrws = new Array(N);
36996 var nrwst = new Array(N);
36997 var niwst = new Array(N);
36998
36999 var rmws = out.words;
37000 rmws.length = N;
37001
37002 this.convert13b(x.words, x.length, rws, N);
37003 this.convert13b(y.words, y.length, nrws, N);
37004
37005 this.transform(rws, _, rwst, iwst, N, rbt);
37006 this.transform(nrws, _, nrwst, niwst, N, rbt);
37007
37008 for (var i = 0; i < N; i++) {
37009 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
37010 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
37011 rwst[i] = rx;
37012 }
37013
37014 this.conjugate(rwst, iwst, N);
37015 this.transform(rwst, iwst, rmws, _, N, rbt);
37016 this.conjugate(rmws, _, N);
37017 this.normalize13b(rmws, N);
37018
37019 out.negative = x.negative ^ y.negative;
37020 out.length = x.length + y.length;
37021 return out.strip();
37022 };
37023
37024 // Multiply `this` by `num`
37025 BN.prototype.mul = function mul (num) {
37026 var out = new BN(null);
37027 out.words = new Array(this.length + num.length);
37028 return this.mulTo(num, out);
37029 };
37030
37031 // Multiply employing FFT
37032 BN.prototype.mulf = function mulf (num) {
37033 var out = new BN(null);
37034 out.words = new Array(this.length + num.length);
37035 return jumboMulTo(this, num, out);
37036 };
37037
37038 // In-place Multiplication
37039 BN.prototype.imul = function imul (num) {
37040 return this.clone().mulTo(num, this);
37041 };
37042
37043 BN.prototype.imuln = function imuln (num) {
37044 assert(typeof num === 'number');
37045 assert(num < 0x4000000);
37046
37047 // Carry
37048 var carry = 0;
37049 for (var i = 0; i < this.length; i++) {
37050 var w = (this.words[i] | 0) * num;
37051 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
37052 carry >>= 26;
37053 carry += (w / 0x4000000) | 0;
37054 // NOTE: lo is 27bit maximum
37055 carry += lo >>> 26;
37056 this.words[i] = lo & 0x3ffffff;
37057 }
37058
37059 if (carry !== 0) {
37060 this.words[i] = carry;
37061 this.length++;
37062 }
37063
37064 return this;
37065 };
37066
37067 BN.prototype.muln = function muln (num) {
37068 return this.clone().imuln(num);
37069 };
37070
37071 // `this` * `this`
37072 BN.prototype.sqr = function sqr () {
37073 return this.mul(this);
37074 };
37075
37076 // `this` * `this` in-place
37077 BN.prototype.isqr = function isqr () {
37078 return this.imul(this.clone());
37079 };
37080
37081 // Math.pow(`this`, `num`)
37082 BN.prototype.pow = function pow (num) {
37083 var w = toBitArray(num);
37084 if (w.length === 0) return new BN(1);
37085
37086 // Skip leading zeroes
37087 var res = this;
37088 for (var i = 0; i < w.length; i++, res = res.sqr()) {
37089 if (w[i] !== 0) break;
37090 }
37091
37092 if (++i < w.length) {
37093 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
37094 if (w[i] === 0) continue;
37095
37096 res = res.mul(q);
37097 }
37098 }
37099
37100 return res;
37101 };
37102
37103 // Shift-left in-place
37104 BN.prototype.iushln = function iushln (bits) {
37105 assert(typeof bits === 'number' && bits >= 0);
37106 var r = bits % 26;
37107 var s = (bits - r) / 26;
37108 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
37109 var i;
37110
37111 if (r !== 0) {
37112 var carry = 0;
37113
37114 for (i = 0; i < this.length; i++) {
37115 var newCarry = this.words[i] & carryMask;
37116 var c = ((this.words[i] | 0) - newCarry) << r;
37117 this.words[i] = c | carry;
37118 carry = newCarry >>> (26 - r);
37119 }
37120
37121 if (carry) {
37122 this.words[i] = carry;
37123 this.length++;
37124 }
37125 }
37126
37127 if (s !== 0) {
37128 for (i = this.length - 1; i >= 0; i--) {
37129 this.words[i + s] = this.words[i];
37130 }
37131
37132 for (i = 0; i < s; i++) {
37133 this.words[i] = 0;
37134 }
37135
37136 this.length += s;
37137 }
37138
37139 return this.strip();
37140 };
37141
37142 BN.prototype.ishln = function ishln (bits) {
37143 // TODO(indutny): implement me
37144 assert(this.negative === 0);
37145 return this.iushln(bits);
37146 };
37147
37148 // Shift-right in-place
37149 // NOTE: `hint` is a lowest bit before trailing zeroes
37150 // NOTE: if `extended` is present - it will be filled with destroyed bits
37151 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
37152 assert(typeof bits === 'number' && bits >= 0);
37153 var h;
37154 if (hint) {
37155 h = (hint - (hint % 26)) / 26;
37156 } else {
37157 h = 0;
37158 }
37159
37160 var r = bits % 26;
37161 var s = Math.min((bits - r) / 26, this.length);
37162 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
37163 var maskedWords = extended;
37164
37165 h -= s;
37166 h = Math.max(0, h);
37167
37168 // Extended mode, copy masked part
37169 if (maskedWords) {
37170 for (var i = 0; i < s; i++) {
37171 maskedWords.words[i] = this.words[i];
37172 }
37173 maskedWords.length = s;
37174 }
37175
37176 if (s === 0) ; else if (this.length > s) {
37177 this.length -= s;
37178 for (i = 0; i < this.length; i++) {
37179 this.words[i] = this.words[i + s];
37180 }
37181 } else {
37182 this.words[0] = 0;
37183 this.length = 1;
37184 }
37185
37186 var carry = 0;
37187 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
37188 var word = this.words[i] | 0;
37189 this.words[i] = (carry << (26 - r)) | (word >>> r);
37190 carry = word & mask;
37191 }
37192
37193 // Push carried bits as a mask
37194 if (maskedWords && carry !== 0) {
37195 maskedWords.words[maskedWords.length++] = carry;
37196 }
37197
37198 if (this.length === 0) {
37199 this.words[0] = 0;
37200 this.length = 1;
37201 }
37202
37203 return this.strip();
37204 };
37205
37206 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
37207 // TODO(indutny): implement me
37208 assert(this.negative === 0);
37209 return this.iushrn(bits, hint, extended);
37210 };
37211
37212 // Shift-left
37213 BN.prototype.shln = function shln (bits) {
37214 return this.clone().ishln(bits);
37215 };
37216
37217 BN.prototype.ushln = function ushln (bits) {
37218 return this.clone().iushln(bits);
37219 };
37220
37221 // Shift-right
37222 BN.prototype.shrn = function shrn (bits) {
37223 return this.clone().ishrn(bits);
37224 };
37225
37226 BN.prototype.ushrn = function ushrn (bits) {
37227 return this.clone().iushrn(bits);
37228 };
37229
37230 // Test if n bit is set
37231 BN.prototype.testn = function testn (bit) {
37232 assert(typeof bit === 'number' && bit >= 0);
37233 var r = bit % 26;
37234 var s = (bit - r) / 26;
37235 var q = 1 << r;
37236
37237 // Fast case: bit is much higher than all existing words
37238 if (this.length <= s) return false;
37239
37240 // Check bit and return
37241 var w = this.words[s];
37242
37243 return !!(w & q);
37244 };
37245
37246 // Return only lowers bits of number (in-place)
37247 BN.prototype.imaskn = function imaskn (bits) {
37248 assert(typeof bits === 'number' && bits >= 0);
37249 var r = bits % 26;
37250 var s = (bits - r) / 26;
37251
37252 assert(this.negative === 0, 'imaskn works only with positive numbers');
37253
37254 if (this.length <= s) {
37255 return this;
37256 }
37257
37258 if (r !== 0) {
37259 s++;
37260 }
37261 this.length = Math.min(s, this.length);
37262
37263 if (r !== 0) {
37264 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
37265 this.words[this.length - 1] &= mask;
37266 }
37267
37268 return this.strip();
37269 };
37270
37271 // Return only lowers bits of number
37272 BN.prototype.maskn = function maskn (bits) {
37273 return this.clone().imaskn(bits);
37274 };
37275
37276 // Add plain number `num` to `this`
37277 BN.prototype.iaddn = function iaddn (num) {
37278 assert(typeof num === 'number');
37279 assert(num < 0x4000000);
37280 if (num < 0) return this.isubn(-num);
37281
37282 // Possible sign change
37283 if (this.negative !== 0) {
37284 if (this.length === 1 && (this.words[0] | 0) < num) {
37285 this.words[0] = num - (this.words[0] | 0);
37286 this.negative = 0;
37287 return this;
37288 }
37289
37290 this.negative = 0;
37291 this.isubn(num);
37292 this.negative = 1;
37293 return this;
37294 }
37295
37296 // Add without checks
37297 return this._iaddn(num);
37298 };
37299
37300 BN.prototype._iaddn = function _iaddn (num) {
37301 this.words[0] += num;
37302
37303 // Carry
37304 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
37305 this.words[i] -= 0x4000000;
37306 if (i === this.length - 1) {
37307 this.words[i + 1] = 1;
37308 } else {
37309 this.words[i + 1]++;
37310 }
37311 }
37312 this.length = Math.max(this.length, i + 1);
37313
37314 return this;
37315 };
37316
37317 // Subtract plain number `num` from `this`
37318 BN.prototype.isubn = function isubn (num) {
37319 assert(typeof num === 'number');
37320 assert(num < 0x4000000);
37321 if (num < 0) return this.iaddn(-num);
37322
37323 if (this.negative !== 0) {
37324 this.negative = 0;
37325 this.iaddn(num);
37326 this.negative = 1;
37327 return this;
37328 }
37329
37330 this.words[0] -= num;
37331
37332 if (this.length === 1 && this.words[0] < 0) {
37333 this.words[0] = -this.words[0];
37334 this.negative = 1;
37335 } else {
37336 // Carry
37337 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
37338 this.words[i] += 0x4000000;
37339 this.words[i + 1] -= 1;
37340 }
37341 }
37342
37343 return this.strip();
37344 };
37345
37346 BN.prototype.addn = function addn (num) {
37347 return this.clone().iaddn(num);
37348 };
37349
37350 BN.prototype.subn = function subn (num) {
37351 return this.clone().isubn(num);
37352 };
37353
37354 BN.prototype.iabs = function iabs () {
37355 this.negative = 0;
37356
37357 return this;
37358 };
37359
37360 BN.prototype.abs = function abs () {
37361 return this.clone().iabs();
37362 };
37363
37364 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
37365 var len = num.length + shift;
37366 var i;
37367
37368 this._expand(len);
37369
37370 var w;
37371 var carry = 0;
37372 for (i = 0; i < num.length; i++) {
37373 w = (this.words[i + shift] | 0) + carry;
37374 var right = (num.words[i] | 0) * mul;
37375 w -= right & 0x3ffffff;
37376 carry = (w >> 26) - ((right / 0x4000000) | 0);
37377 this.words[i + shift] = w & 0x3ffffff;
37378 }
37379 for (; i < this.length - shift; i++) {
37380 w = (this.words[i + shift] | 0) + carry;
37381 carry = w >> 26;
37382 this.words[i + shift] = w & 0x3ffffff;
37383 }
37384
37385 if (carry === 0) return this.strip();
37386
37387 // Subtraction overflow
37388 assert(carry === -1);
37389 carry = 0;
37390 for (i = 0; i < this.length; i++) {
37391 w = -(this.words[i] | 0) + carry;
37392 carry = w >> 26;
37393 this.words[i] = w & 0x3ffffff;
37394 }
37395 this.negative = 1;
37396
37397 return this.strip();
37398 };
37399
37400 BN.prototype._wordDiv = function _wordDiv (num, mode) {
37401 var shift = this.length - num.length;
37402
37403 var a = this.clone();
37404 var b = num;
37405
37406 // Normalize
37407 var bhi = b.words[b.length - 1] | 0;
37408 var bhiBits = this._countBits(bhi);
37409 shift = 26 - bhiBits;
37410 if (shift !== 0) {
37411 b = b.ushln(shift);
37412 a.iushln(shift);
37413 bhi = b.words[b.length - 1] | 0;
37414 }
37415
37416 // Initialize quotient
37417 var m = a.length - b.length;
37418 var q;
37419
37420 if (mode !== 'mod') {
37421 q = new BN(null);
37422 q.length = m + 1;
37423 q.words = new Array(q.length);
37424 for (var i = 0; i < q.length; i++) {
37425 q.words[i] = 0;
37426 }
37427 }
37428
37429 var diff = a.clone()._ishlnsubmul(b, 1, m);
37430 if (diff.negative === 0) {
37431 a = diff;
37432 if (q) {
37433 q.words[m] = 1;
37434 }
37435 }
37436
37437 for (var j = m - 1; j >= 0; j--) {
37438 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
37439 (a.words[b.length + j - 1] | 0);
37440
37441 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
37442 // (0x7ffffff)
37443 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
37444
37445 a._ishlnsubmul(b, qj, j);
37446 while (a.negative !== 0) {
37447 qj--;
37448 a.negative = 0;
37449 a._ishlnsubmul(b, 1, j);
37450 if (!a.isZero()) {
37451 a.negative ^= 1;
37452 }
37453 }
37454 if (q) {
37455 q.words[j] = qj;
37456 }
37457 }
37458 if (q) {
37459 q.strip();
37460 }
37461 a.strip();
37462
37463 // Denormalize
37464 if (mode !== 'div' && shift !== 0) {
37465 a.iushrn(shift);
37466 }
37467
37468 return {
37469 div: q || null,
37470 mod: a
37471 };
37472 };
37473
37474 // NOTE: 1) `mode` can be set to `mod` to request mod only,
37475 // to `div` to request div only, or be absent to
37476 // request both div & mod
37477 // 2) `positive` is true if unsigned mod is requested
37478 BN.prototype.divmod = function divmod (num, mode, positive) {
37479 assert(!num.isZero());
37480
37481 if (this.isZero()) {
37482 return {
37483 div: new BN(0),
37484 mod: new BN(0)
37485 };
37486 }
37487
37488 var div, mod, res;
37489 if (this.negative !== 0 && num.negative === 0) {
37490 res = this.neg().divmod(num, mode);
37491
37492 if (mode !== 'mod') {
37493 div = res.div.neg();
37494 }
37495
37496 if (mode !== 'div') {
37497 mod = res.mod.neg();
37498 if (positive && mod.negative !== 0) {
37499 mod.iadd(num);
37500 }
37501 }
37502
37503 return {
37504 div: div,
37505 mod: mod
37506 };
37507 }
37508
37509 if (this.negative === 0 && num.negative !== 0) {
37510 res = this.divmod(num.neg(), mode);
37511
37512 if (mode !== 'mod') {
37513 div = res.div.neg();
37514 }
37515
37516 return {
37517 div: div,
37518 mod: res.mod
37519 };
37520 }
37521
37522 if ((this.negative & num.negative) !== 0) {
37523 res = this.neg().divmod(num.neg(), mode);
37524
37525 if (mode !== 'div') {
37526 mod = res.mod.neg();
37527 if (positive && mod.negative !== 0) {
37528 mod.isub(num);
37529 }
37530 }
37531
37532 return {
37533 div: res.div,
37534 mod: mod
37535 };
37536 }
37537
37538 // Both numbers are positive at this point
37539
37540 // Strip both numbers to approximate shift value
37541 if (num.length > this.length || this.cmp(num) < 0) {
37542 return {
37543 div: new BN(0),
37544 mod: this
37545 };
37546 }
37547
37548 // Very short reduction
37549 if (num.length === 1) {
37550 if (mode === 'div') {
37551 return {
37552 div: this.divn(num.words[0]),
37553 mod: null
37554 };
37555 }
37556
37557 if (mode === 'mod') {
37558 return {
37559 div: null,
37560 mod: new BN(this.modn(num.words[0]))
37561 };
37562 }
37563
37564 return {
37565 div: this.divn(num.words[0]),
37566 mod: new BN(this.modn(num.words[0]))
37567 };
37568 }
37569
37570 return this._wordDiv(num, mode);
37571 };
37572
37573 // Find `this` / `num`
37574 BN.prototype.div = function div (num) {
37575 return this.divmod(num, 'div', false).div;
37576 };
37577
37578 // Find `this` % `num`
37579 BN.prototype.mod = function mod (num) {
37580 return this.divmod(num, 'mod', false).mod;
37581 };
37582
37583 BN.prototype.umod = function umod (num) {
37584 return this.divmod(num, 'mod', true).mod;
37585 };
37586
37587 // Find Round(`this` / `num`)
37588 BN.prototype.divRound = function divRound (num) {
37589 var dm = this.divmod(num);
37590
37591 // Fast case - exact division
37592 if (dm.mod.isZero()) return dm.div;
37593
37594 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
37595
37596 var half = num.ushrn(1);
37597 var r2 = num.andln(1);
37598 var cmp = mod.cmp(half);
37599
37600 // Round down
37601 if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
37602
37603 // Round up
37604 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
37605 };
37606
37607 BN.prototype.modn = function modn (num) {
37608 assert(num <= 0x3ffffff);
37609 var p = (1 << 26) % num;
37610
37611 var acc = 0;
37612 for (var i = this.length - 1; i >= 0; i--) {
37613 acc = (p * acc + (this.words[i] | 0)) % num;
37614 }
37615
37616 return acc;
37617 };
37618
37619 // In-place division by number
37620 BN.prototype.idivn = function idivn (num) {
37621 assert(num <= 0x3ffffff);
37622
37623 var carry = 0;
37624 for (var i = this.length - 1; i >= 0; i--) {
37625 var w = (this.words[i] | 0) + carry * 0x4000000;
37626 this.words[i] = (w / num) | 0;
37627 carry = w % num;
37628 }
37629
37630 return this.strip();
37631 };
37632
37633 BN.prototype.divn = function divn (num) {
37634 return this.clone().idivn(num);
37635 };
37636
37637 BN.prototype.egcd = function egcd (p) {
37638 assert(p.negative === 0);
37639 assert(!p.isZero());
37640
37641 var x = this;
37642 var y = p.clone();
37643
37644 if (x.negative !== 0) {
37645 x = x.umod(p);
37646 } else {
37647 x = x.clone();
37648 }
37649
37650 // A * x + B * y = x
37651 var A = new BN(1);
37652 var B = new BN(0);
37653
37654 // C * x + D * y = y
37655 var C = new BN(0);
37656 var D = new BN(1);
37657
37658 var g = 0;
37659
37660 while (x.isEven() && y.isEven()) {
37661 x.iushrn(1);
37662 y.iushrn(1);
37663 ++g;
37664 }
37665
37666 var yp = y.clone();
37667 var xp = x.clone();
37668
37669 while (!x.isZero()) {
37670 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
37671 if (i > 0) {
37672 x.iushrn(i);
37673 while (i-- > 0) {
37674 if (A.isOdd() || B.isOdd()) {
37675 A.iadd(yp);
37676 B.isub(xp);
37677 }
37678
37679 A.iushrn(1);
37680 B.iushrn(1);
37681 }
37682 }
37683
37684 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
37685 if (j > 0) {
37686 y.iushrn(j);
37687 while (j-- > 0) {
37688 if (C.isOdd() || D.isOdd()) {
37689 C.iadd(yp);
37690 D.isub(xp);
37691 }
37692
37693 C.iushrn(1);
37694 D.iushrn(1);
37695 }
37696 }
37697
37698 if (x.cmp(y) >= 0) {
37699 x.isub(y);
37700 A.isub(C);
37701 B.isub(D);
37702 } else {
37703 y.isub(x);
37704 C.isub(A);
37705 D.isub(B);
37706 }
37707 }
37708
37709 return {
37710 a: C,
37711 b: D,
37712 gcd: y.iushln(g)
37713 };
37714 };
37715
37716 // This is reduced incarnation of the binary EEA
37717 // above, designated to invert members of the
37718 // _prime_ fields F(p) at a maximal speed
37719 BN.prototype._invmp = function _invmp (p) {
37720 assert(p.negative === 0);
37721 assert(!p.isZero());
37722
37723 var a = this;
37724 var b = p.clone();
37725
37726 if (a.negative !== 0) {
37727 a = a.umod(p);
37728 } else {
37729 a = a.clone();
37730 }
37731
37732 var x1 = new BN(1);
37733 var x2 = new BN(0);
37734
37735 var delta = b.clone();
37736
37737 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
37738 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
37739 if (i > 0) {
37740 a.iushrn(i);
37741 while (i-- > 0) {
37742 if (x1.isOdd()) {
37743 x1.iadd(delta);
37744 }
37745
37746 x1.iushrn(1);
37747 }
37748 }
37749
37750 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
37751 if (j > 0) {
37752 b.iushrn(j);
37753 while (j-- > 0) {
37754 if (x2.isOdd()) {
37755 x2.iadd(delta);
37756 }
37757
37758 x2.iushrn(1);
37759 }
37760 }
37761
37762 if (a.cmp(b) >= 0) {
37763 a.isub(b);
37764 x1.isub(x2);
37765 } else {
37766 b.isub(a);
37767 x2.isub(x1);
37768 }
37769 }
37770
37771 var res;
37772 if (a.cmpn(1) === 0) {
37773 res = x1;
37774 } else {
37775 res = x2;
37776 }
37777
37778 if (res.cmpn(0) < 0) {
37779 res.iadd(p);
37780 }
37781
37782 return res;
37783 };
37784
37785 BN.prototype.gcd = function gcd (num) {
37786 if (this.isZero()) return num.abs();
37787 if (num.isZero()) return this.abs();
37788
37789 var a = this.clone();
37790 var b = num.clone();
37791 a.negative = 0;
37792 b.negative = 0;
37793
37794 // Remove common factor of two
37795 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
37796 a.iushrn(1);
37797 b.iushrn(1);
37798 }
37799
37800 do {
37801 while (a.isEven()) {
37802 a.iushrn(1);
37803 }
37804 while (b.isEven()) {
37805 b.iushrn(1);
37806 }
37807
37808 var r = a.cmp(b);
37809 if (r < 0) {
37810 // Swap `a` and `b` to make `a` always bigger than `b`
37811 var t = a;
37812 a = b;
37813 b = t;
37814 } else if (r === 0 || b.cmpn(1) === 0) {
37815 break;
37816 }
37817
37818 a.isub(b);
37819 } while (true);
37820
37821 return b.iushln(shift);
37822 };
37823
37824 // Invert number in the field F(num)
37825 BN.prototype.invm = function invm (num) {
37826 return this.egcd(num).a.umod(num);
37827 };
37828
37829 BN.prototype.isEven = function isEven () {
37830 return (this.words[0] & 1) === 0;
37831 };
37832
37833 BN.prototype.isOdd = function isOdd () {
37834 return (this.words[0] & 1) === 1;
37835 };
37836
37837 // And first word and num
37838 BN.prototype.andln = function andln (num) {
37839 return this.words[0] & num;
37840 };
37841
37842 // Increment at the bit position in-line
37843 BN.prototype.bincn = function bincn (bit) {
37844 assert(typeof bit === 'number');
37845 var r = bit % 26;
37846 var s = (bit - r) / 26;
37847 var q = 1 << r;
37848
37849 // Fast case: bit is much higher than all existing words
37850 if (this.length <= s) {
37851 this._expand(s + 1);
37852 this.words[s] |= q;
37853 return this;
37854 }
37855
37856 // Add bit and propagate, if needed
37857 var carry = q;
37858 for (var i = s; carry !== 0 && i < this.length; i++) {
37859 var w = this.words[i] | 0;
37860 w += carry;
37861 carry = w >>> 26;
37862 w &= 0x3ffffff;
37863 this.words[i] = w;
37864 }
37865 if (carry !== 0) {
37866 this.words[i] = carry;
37867 this.length++;
37868 }
37869 return this;
37870 };
37871
37872 BN.prototype.isZero = function isZero () {
37873 return this.length === 1 && this.words[0] === 0;
37874 };
37875
37876 BN.prototype.cmpn = function cmpn (num) {
37877 var negative = num < 0;
37878
37879 if (this.negative !== 0 && !negative) return -1;
37880 if (this.negative === 0 && negative) return 1;
37881
37882 this.strip();
37883
37884 var res;
37885 if (this.length > 1) {
37886 res = 1;
37887 } else {
37888 if (negative) {
37889 num = -num;
37890 }
37891
37892 assert(num <= 0x3ffffff, 'Number is too big');
37893
37894 var w = this.words[0] | 0;
37895 res = w === num ? 0 : w < num ? -1 : 1;
37896 }
37897 if (this.negative !== 0) return -res | 0;
37898 return res;
37899 };
37900
37901 // Compare two numbers and return:
37902 // 1 - if `this` > `num`
37903 // 0 - if `this` == `num`
37904 // -1 - if `this` < `num`
37905 BN.prototype.cmp = function cmp (num) {
37906 if (this.negative !== 0 && num.negative === 0) return -1;
37907 if (this.negative === 0 && num.negative !== 0) return 1;
37908
37909 var res = this.ucmp(num);
37910 if (this.negative !== 0) return -res | 0;
37911 return res;
37912 };
37913
37914 // Unsigned comparison
37915 BN.prototype.ucmp = function ucmp (num) {
37916 // At this point both numbers have the same sign
37917 if (this.length > num.length) return 1;
37918 if (this.length < num.length) return -1;
37919
37920 var res = 0;
37921 for (var i = this.length - 1; i >= 0; i--) {
37922 var a = this.words[i] | 0;
37923 var b = num.words[i] | 0;
37924
37925 if (a === b) continue;
37926 if (a < b) {
37927 res = -1;
37928 } else if (a > b) {
37929 res = 1;
37930 }
37931 break;
37932 }
37933 return res;
37934 };
37935
37936 BN.prototype.gtn = function gtn (num) {
37937 return this.cmpn(num) === 1;
37938 };
37939
37940 BN.prototype.gt = function gt (num) {
37941 return this.cmp(num) === 1;
37942 };
37943
37944 BN.prototype.gten = function gten (num) {
37945 return this.cmpn(num) >= 0;
37946 };
37947
37948 BN.prototype.gte = function gte (num) {
37949 return this.cmp(num) >= 0;
37950 };
37951
37952 BN.prototype.ltn = function ltn (num) {
37953 return this.cmpn(num) === -1;
37954 };
37955
37956 BN.prototype.lt = function lt (num) {
37957 return this.cmp(num) === -1;
37958 };
37959
37960 BN.prototype.lten = function lten (num) {
37961 return this.cmpn(num) <= 0;
37962 };
37963
37964 BN.prototype.lte = function lte (num) {
37965 return this.cmp(num) <= 0;
37966 };
37967
37968 BN.prototype.eqn = function eqn (num) {
37969 return this.cmpn(num) === 0;
37970 };
37971
37972 BN.prototype.eq = function eq (num) {
37973 return this.cmp(num) === 0;
37974 };
37975
37976 //
37977 // A reduce context, could be using montgomery or something better, depending
37978 // on the `m` itself.
37979 //
37980 BN.red = function red (num) {
37981 return new Red(num);
37982 };
37983
37984 BN.prototype.toRed = function toRed (ctx) {
37985 assert(!this.red, 'Already a number in reduction context');
37986 assert(this.negative === 0, 'red works only with positives');
37987 return ctx.convertTo(this)._forceRed(ctx);
37988 };
37989
37990 BN.prototype.fromRed = function fromRed () {
37991 assert(this.red, 'fromRed works only with numbers in reduction context');
37992 return this.red.convertFrom(this);
37993 };
37994
37995 BN.prototype._forceRed = function _forceRed (ctx) {
37996 this.red = ctx;
37997 return this;
37998 };
37999
38000 BN.prototype.forceRed = function forceRed (ctx) {
38001 assert(!this.red, 'Already a number in reduction context');
38002 return this._forceRed(ctx);
38003 };
38004
38005 BN.prototype.redAdd = function redAdd (num) {
38006 assert(this.red, 'redAdd works only with red numbers');
38007 return this.red.add(this, num);
38008 };
38009
38010 BN.prototype.redIAdd = function redIAdd (num) {
38011 assert(this.red, 'redIAdd works only with red numbers');
38012 return this.red.iadd(this, num);
38013 };
38014
38015 BN.prototype.redSub = function redSub (num) {
38016 assert(this.red, 'redSub works only with red numbers');
38017 return this.red.sub(this, num);
38018 };
38019
38020 BN.prototype.redISub = function redISub (num) {
38021 assert(this.red, 'redISub works only with red numbers');
38022 return this.red.isub(this, num);
38023 };
38024
38025 BN.prototype.redShl = function redShl (num) {
38026 assert(this.red, 'redShl works only with red numbers');
38027 return this.red.shl(this, num);
38028 };
38029
38030 BN.prototype.redMul = function redMul (num) {
38031 assert(this.red, 'redMul works only with red numbers');
38032 this.red._verify2(this, num);
38033 return this.red.mul(this, num);
38034 };
38035
38036 BN.prototype.redIMul = function redIMul (num) {
38037 assert(this.red, 'redMul works only with red numbers');
38038 this.red._verify2(this, num);
38039 return this.red.imul(this, num);
38040 };
38041
38042 BN.prototype.redSqr = function redSqr () {
38043 assert(this.red, 'redSqr works only with red numbers');
38044 this.red._verify1(this);
38045 return this.red.sqr(this);
38046 };
38047
38048 BN.prototype.redISqr = function redISqr () {
38049 assert(this.red, 'redISqr works only with red numbers');
38050 this.red._verify1(this);
38051 return this.red.isqr(this);
38052 };
38053
38054 // Square root over p
38055 BN.prototype.redSqrt = function redSqrt () {
38056 assert(this.red, 'redSqrt works only with red numbers');
38057 this.red._verify1(this);
38058 return this.red.sqrt(this);
38059 };
38060
38061 BN.prototype.redInvm = function redInvm () {
38062 assert(this.red, 'redInvm works only with red numbers');
38063 this.red._verify1(this);
38064 return this.red.invm(this);
38065 };
38066
38067 // Return negative clone of `this` % `red modulo`
38068 BN.prototype.redNeg = function redNeg () {
38069 assert(this.red, 'redNeg works only with red numbers');
38070 this.red._verify1(this);
38071 return this.red.neg(this);
38072 };
38073
38074 BN.prototype.redPow = function redPow (num) {
38075 assert(this.red && !num.red, 'redPow(normalNum)');
38076 this.red._verify1(this);
38077 return this.red.pow(this, num);
38078 };
38079
38080 // Prime numbers with efficient reduction
38081 var primes = {
38082 k256: null,
38083 p224: null,
38084 p192: null,
38085 p25519: null
38086 };
38087
38088 // Pseudo-Mersenne prime
38089 function MPrime (name, p) {
38090 // P = 2 ^ N - K
38091 this.name = name;
38092 this.p = new BN(p, 16);
38093 this.n = this.p.bitLength();
38094 this.k = new BN(1).iushln(this.n).isub(this.p);
38095
38096 this.tmp = this._tmp();
38097 }
38098
38099 MPrime.prototype._tmp = function _tmp () {
38100 var tmp = new BN(null);
38101 tmp.words = new Array(Math.ceil(this.n / 13));
38102 return tmp;
38103 };
38104
38105 MPrime.prototype.ireduce = function ireduce (num) {
38106 // Assumes that `num` is less than `P^2`
38107 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
38108 var r = num;
38109 var rlen;
38110
38111 do {
38112 this.split(r, this.tmp);
38113 r = this.imulK(r);
38114 r = r.iadd(this.tmp);
38115 rlen = r.bitLength();
38116 } while (rlen > this.n);
38117
38118 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
38119 if (cmp === 0) {
38120 r.words[0] = 0;
38121 r.length = 1;
38122 } else if (cmp > 0) {
38123 r.isub(this.p);
38124 } else {
38125 r.strip();
38126 }
38127
38128 return r;
38129 };
38130
38131 MPrime.prototype.split = function split (input, out) {
38132 input.iushrn(this.n, 0, out);
38133 };
38134
38135 MPrime.prototype.imulK = function imulK (num) {
38136 return num.imul(this.k);
38137 };
38138
38139 function K256 () {
38140 MPrime.call(
38141 this,
38142 'k256',
38143 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
38144 }
38145 inherits(K256, MPrime);
38146
38147 K256.prototype.split = function split (input, output) {
38148 // 256 = 9 * 26 + 22
38149 var mask = 0x3fffff;
38150
38151 var outLen = Math.min(input.length, 9);
38152 for (var i = 0; i < outLen; i++) {
38153 output.words[i] = input.words[i];
38154 }
38155 output.length = outLen;
38156
38157 if (input.length <= 9) {
38158 input.words[0] = 0;
38159 input.length = 1;
38160 return;
38161 }
38162
38163 // Shift by 9 limbs
38164 var prev = input.words[9];
38165 output.words[output.length++] = prev & mask;
38166
38167 for (i = 10; i < input.length; i++) {
38168 var next = input.words[i] | 0;
38169 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
38170 prev = next;
38171 }
38172 prev >>>= 22;
38173 input.words[i - 10] = prev;
38174 if (prev === 0 && input.length > 10) {
38175 input.length -= 10;
38176 } else {
38177 input.length -= 9;
38178 }
38179 };
38180
38181 K256.prototype.imulK = function imulK (num) {
38182 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
38183 num.words[num.length] = 0;
38184 num.words[num.length + 1] = 0;
38185 num.length += 2;
38186
38187 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
38188 var lo = 0;
38189 for (var i = 0; i < num.length; i++) {
38190 var w = num.words[i] | 0;
38191 lo += w * 0x3d1;
38192 num.words[i] = lo & 0x3ffffff;
38193 lo = w * 0x40 + ((lo / 0x4000000) | 0);
38194 }
38195
38196 // Fast length reduction
38197 if (num.words[num.length - 1] === 0) {
38198 num.length--;
38199 if (num.words[num.length - 1] === 0) {
38200 num.length--;
38201 }
38202 }
38203 return num;
38204 };
38205
38206 function P224 () {
38207 MPrime.call(
38208 this,
38209 'p224',
38210 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
38211 }
38212 inherits(P224, MPrime);
38213
38214 function P192 () {
38215 MPrime.call(
38216 this,
38217 'p192',
38218 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
38219 }
38220 inherits(P192, MPrime);
38221
38222 function P25519 () {
38223 // 2 ^ 255 - 19
38224 MPrime.call(
38225 this,
38226 '25519',
38227 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
38228 }
38229 inherits(P25519, MPrime);
38230
38231 P25519.prototype.imulK = function imulK (num) {
38232 // K = 0x13
38233 var carry = 0;
38234 for (var i = 0; i < num.length; i++) {
38235 var hi = (num.words[i] | 0) * 0x13 + carry;
38236 var lo = hi & 0x3ffffff;
38237 hi >>>= 26;
38238
38239 num.words[i] = lo;
38240 carry = hi;
38241 }
38242 if (carry !== 0) {
38243 num.words[num.length++] = carry;
38244 }
38245 return num;
38246 };
38247
38248 // Exported mostly for testing purposes, use plain name instead
38249 BN._prime = function prime (name) {
38250 // Cached version of prime
38251 if (primes[name]) return primes[name];
38252
38253 var prime;
38254 if (name === 'k256') {
38255 prime = new K256();
38256 } else if (name === 'p224') {
38257 prime = new P224();
38258 } else if (name === 'p192') {
38259 prime = new P192();
38260 } else if (name === 'p25519') {
38261 prime = new P25519();
38262 } else {
38263 throw new Error('Unknown prime ' + name);
38264 }
38265 primes[name] = prime;
38266
38267 return prime;
38268 };
38269
38270 //
38271 // Base reduction engine
38272 //
38273 function Red (m) {
38274 if (typeof m === 'string') {
38275 var prime = BN._prime(m);
38276 this.m = prime.p;
38277 this.prime = prime;
38278 } else {
38279 assert(m.gtn(1), 'modulus must be greater than 1');
38280 this.m = m;
38281 this.prime = null;
38282 }
38283 }
38284
38285 Red.prototype._verify1 = function _verify1 (a) {
38286 assert(a.negative === 0, 'red works only with positives');
38287 assert(a.red, 'red works only with red numbers');
38288 };
38289
38290 Red.prototype._verify2 = function _verify2 (a, b) {
38291 assert((a.negative | b.negative) === 0, 'red works only with positives');
38292 assert(a.red && a.red === b.red,
38293 'red works only with red numbers');
38294 };
38295
38296 Red.prototype.imod = function imod (a) {
38297 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
38298 return a.umod(this.m)._forceRed(this);
38299 };
38300
38301 Red.prototype.neg = function neg (a) {
38302 if (a.isZero()) {
38303 return a.clone();
38304 }
38305
38306 return this.m.sub(a)._forceRed(this);
38307 };
38308
38309 Red.prototype.add = function add (a, b) {
38310 this._verify2(a, b);
38311
38312 var res = a.add(b);
38313 if (res.cmp(this.m) >= 0) {
38314 res.isub(this.m);
38315 }
38316 return res._forceRed(this);
38317 };
38318
38319 Red.prototype.iadd = function iadd (a, b) {
38320 this._verify2(a, b);
38321
38322 var res = a.iadd(b);
38323 if (res.cmp(this.m) >= 0) {
38324 res.isub(this.m);
38325 }
38326 return res;
38327 };
38328
38329 Red.prototype.sub = function sub (a, b) {
38330 this._verify2(a, b);
38331
38332 var res = a.sub(b);
38333 if (res.cmpn(0) < 0) {
38334 res.iadd(this.m);
38335 }
38336 return res._forceRed(this);
38337 };
38338
38339 Red.prototype.isub = function isub (a, b) {
38340 this._verify2(a, b);
38341
38342 var res = a.isub(b);
38343 if (res.cmpn(0) < 0) {
38344 res.iadd(this.m);
38345 }
38346 return res;
38347 };
38348
38349 Red.prototype.shl = function shl (a, num) {
38350 this._verify1(a);
38351 return this.imod(a.ushln(num));
38352 };
38353
38354 Red.prototype.imul = function imul (a, b) {
38355 this._verify2(a, b);
38356 return this.imod(a.imul(b));
38357 };
38358
38359 Red.prototype.mul = function mul (a, b) {
38360 this._verify2(a, b);
38361 return this.imod(a.mul(b));
38362 };
38363
38364 Red.prototype.isqr = function isqr (a) {
38365 return this.imul(a, a.clone());
38366 };
38367
38368 Red.prototype.sqr = function sqr (a) {
38369 return this.mul(a, a);
38370 };
38371
38372 Red.prototype.sqrt = function sqrt (a) {
38373 if (a.isZero()) return a.clone();
38374
38375 var mod3 = this.m.andln(3);
38376 assert(mod3 % 2 === 1);
38377
38378 // Fast case
38379 if (mod3 === 3) {
38380 var pow = this.m.add(new BN(1)).iushrn(2);
38381 return this.pow(a, pow);
38382 }
38383
38384 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
38385 //
38386 // Find Q and S, that Q * 2 ^ S = (P - 1)
38387 var q = this.m.subn(1);
38388 var s = 0;
38389 while (!q.isZero() && q.andln(1) === 0) {
38390 s++;
38391 q.iushrn(1);
38392 }
38393 assert(!q.isZero());
38394
38395 var one = new BN(1).toRed(this);
38396 var nOne = one.redNeg();
38397
38398 // Find quadratic non-residue
38399 // NOTE: Max is such because of generalized Riemann hypothesis.
38400 var lpow = this.m.subn(1).iushrn(1);
38401 var z = this.m.bitLength();
38402 z = new BN(2 * z * z).toRed(this);
38403
38404 while (this.pow(z, lpow).cmp(nOne) !== 0) {
38405 z.redIAdd(nOne);
38406 }
38407
38408 var c = this.pow(z, q);
38409 var r = this.pow(a, q.addn(1).iushrn(1));
38410 var t = this.pow(a, q);
38411 var m = s;
38412 while (t.cmp(one) !== 0) {
38413 var tmp = t;
38414 for (var i = 0; tmp.cmp(one) !== 0; i++) {
38415 tmp = tmp.redSqr();
38416 }
38417 assert(i < m);
38418 var b = this.pow(c, new BN(1).iushln(m - i - 1));
38419
38420 r = r.redMul(b);
38421 c = b.redSqr();
38422 t = t.redMul(c);
38423 m = i;
38424 }
38425
38426 return r;
38427 };
38428
38429 Red.prototype.invm = function invm (a) {
38430 var inv = a._invmp(this.m);
38431 if (inv.negative !== 0) {
38432 inv.negative = 0;
38433 return this.imod(inv).redNeg();
38434 } else {
38435 return this.imod(inv);
38436 }
38437 };
38438
38439 Red.prototype.pow = function pow (a, num) {
38440 if (num.isZero()) return new BN(1).toRed(this);
38441 if (num.cmpn(1) === 0) return a.clone();
38442
38443 var windowSize = 4;
38444 var wnd = new Array(1 << windowSize);
38445 wnd[0] = new BN(1).toRed(this);
38446 wnd[1] = a;
38447 for (var i = 2; i < wnd.length; i++) {
38448 wnd[i] = this.mul(wnd[i - 1], a);
38449 }
38450
38451 var res = wnd[0];
38452 var current = 0;
38453 var currentLen = 0;
38454 var start = num.bitLength() % 26;
38455 if (start === 0) {
38456 start = 26;
38457 }
38458
38459 for (i = num.length - 1; i >= 0; i--) {
38460 var word = num.words[i];
38461 for (var j = start - 1; j >= 0; j--) {
38462 var bit = (word >> j) & 1;
38463 if (res !== wnd[0]) {
38464 res = this.sqr(res);
38465 }
38466
38467 if (bit === 0 && current === 0) {
38468 currentLen = 0;
38469 continue;
38470 }
38471
38472 current <<= 1;
38473 current |= bit;
38474 currentLen++;
38475 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
38476
38477 res = this.mul(res, wnd[current]);
38478 currentLen = 0;
38479 current = 0;
38480 }
38481 start = 26;
38482 }
38483
38484 return res;
38485 };
38486
38487 Red.prototype.convertTo = function convertTo (num) {
38488 var r = num.umod(this.m);
38489
38490 return r === num ? r.clone() : r;
38491 };
38492
38493 Red.prototype.convertFrom = function convertFrom (num) {
38494 var res = num.clone();
38495 res.red = null;
38496 return res;
38497 };
38498
38499 //
38500 // Montgomery method engine
38501 //
38502
38503 BN.mont = function mont (num) {
38504 return new Mont(num);
38505 };
38506
38507 function Mont (m) {
38508 Red.call(this, m);
38509
38510 this.shift = this.m.bitLength();
38511 if (this.shift % 26 !== 0) {
38512 this.shift += 26 - (this.shift % 26);
38513 }
38514
38515 this.r = new BN(1).iushln(this.shift);
38516 this.r2 = this.imod(this.r.sqr());
38517 this.rinv = this.r._invmp(this.m);
38518
38519 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
38520 this.minv = this.minv.umod(this.r);
38521 this.minv = this.r.sub(this.minv);
38522 }
38523 inherits(Mont, Red);
38524
38525 Mont.prototype.convertTo = function convertTo (num) {
38526 return this.imod(num.ushln(this.shift));
38527 };
38528
38529 Mont.prototype.convertFrom = function convertFrom (num) {
38530 var r = this.imod(num.mul(this.rinv));
38531 r.red = null;
38532 return r;
38533 };
38534
38535 Mont.prototype.imul = function imul (a, b) {
38536 if (a.isZero() || b.isZero()) {
38537 a.words[0] = 0;
38538 a.length = 1;
38539 return a;
38540 }
38541
38542 var t = a.imul(b);
38543 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
38544 var u = t.isub(c).iushrn(this.shift);
38545 var res = u;
38546
38547 if (u.cmp(this.m) >= 0) {
38548 res = u.isub(this.m);
38549 } else if (u.cmpn(0) < 0) {
38550 res = u.iadd(this.m);
38551 }
38552
38553 return res._forceRed(this);
38554 };
38555
38556 Mont.prototype.mul = function mul (a, b) {
38557 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
38558
38559 var t = a.mul(b);
38560 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
38561 var u = t.isub(c).iushrn(this.shift);
38562 var res = u;
38563 if (u.cmp(this.m) >= 0) {
38564 res = u.isub(this.m);
38565 } else if (u.cmpn(0) < 0) {
38566 res = u.iadd(this.m);
38567 }
38568
38569 return res._forceRed(this);
38570 };
38571
38572 Mont.prototype.invm = function invm (a) {
38573 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
38574 var res = this.imod(a._invmp(this.m).mul(this.r2));
38575 return res._forceRed(this);
38576 };
38577 })(module, commonjsGlobal);
38578 });
38579
38580 var bn$1 = /*#__PURE__*/Object.freeze({
38581 __proto__: null,
38582 'default': bn,
38583 __moduleExports: bn
38584 });
38585
38586 /**
38587 * @fileoverview
38588 * BigInteger implementation of basic operations
38589 * Wrapper of bn.js library (wwww.github.com/indutny/bn.js)
38590 * @module biginteger/bn
38591 * @private
38592 */
38593
38594 /**
38595 * @private
38596 */
38597 class BigInteger$1 {
38598 /**
38599 * Get a BigInteger (input must be big endian for strings and arrays)
38600 * @param {Number|String|Uint8Array} n - Value to convert
38601 * @throws {Error} on undefined input
38602 */
38603 constructor(n) {
38604 if (n === undefined) {
38605 throw new Error('Invalid BigInteger input');
38606 }
38607
38608 this.value = new bn(n);
38609 }
38610
38611 clone() {
38612 const clone = new BigInteger$1(null);
38613 this.value.copy(clone.value);
38614 return clone;
38615 }
38616
38617 /**
38618 * BigInteger increment in place
38619 */
38620 iinc() {
38621 this.value.iadd(new bn(1));
38622 return this;
38623 }
38624
38625 /**
38626 * BigInteger increment
38627 * @returns {BigInteger} this + 1.
38628 */
38629 inc() {
38630 return this.clone().iinc();
38631 }
38632
38633 /**
38634 * BigInteger decrement in place
38635 */
38636 idec() {
38637 this.value.isub(new bn(1));
38638 return this;
38639 }
38640
38641 /**
38642 * BigInteger decrement
38643 * @returns {BigInteger} this - 1.
38644 */
38645 dec() {
38646 return this.clone().idec();
38647 }
38648
38649
38650 /**
38651 * BigInteger addition in place
38652 * @param {BigInteger} x - Value to add
38653 */
38654 iadd(x) {
38655 this.value.iadd(x.value);
38656 return this;
38657 }
38658
38659 /**
38660 * BigInteger addition
38661 * @param {BigInteger} x - Value to add
38662 * @returns {BigInteger} this + x.
38663 */
38664 add(x) {
38665 return this.clone().iadd(x);
38666 }
38667
38668 /**
38669 * BigInteger subtraction in place
38670 * @param {BigInteger} x - Value to subtract
38671 */
38672 isub(x) {
38673 this.value.isub(x.value);
38674 return this;
38675 }
38676
38677 /**
38678 * BigInteger subtraction
38679 * @param {BigInteger} x - Value to subtract
38680 * @returns {BigInteger} this - x.
38681 */
38682 sub(x) {
38683 return this.clone().isub(x);
38684 }
38685
38686 /**
38687 * BigInteger multiplication in place
38688 * @param {BigInteger} x - Value to multiply
38689 */
38690 imul(x) {
38691 this.value.imul(x.value);
38692 return this;
38693 }
38694
38695 /**
38696 * BigInteger multiplication
38697 * @param {BigInteger} x - Value to multiply
38698 * @returns {BigInteger} this * x.
38699 */
38700 mul(x) {
38701 return this.clone().imul(x);
38702 }
38703
38704 /**
38705 * Compute value modulo m, in place
38706 * @param {BigInteger} m - Modulo
38707 */
38708 imod(m) {
38709 this.value = this.value.umod(m.value);
38710 return this;
38711 }
38712
38713 /**
38714 * Compute value modulo m
38715 * @param {BigInteger} m - Modulo
38716 * @returns {BigInteger} this mod m.
38717 */
38718 mod(m) {
38719 return this.clone().imod(m);
38720 }
38721
38722 /**
38723 * Compute modular exponentiation
38724 * Much faster than this.exp(e).mod(n)
38725 * @param {BigInteger} e - Exponent
38726 * @param {BigInteger} n - Modulo
38727 * @returns {BigInteger} this ** e mod n.
38728 */
38729 modExp(e, n) {
38730 // We use either Montgomery or normal reduction context
38731 // Montgomery requires coprime n and R (montogmery multiplier)
38732 // bn.js picks R as power of 2, so n must be odd
38733 const nred = n.isEven() ? bn.red(n.value) : bn.mont(n.value);
38734 const x = this.clone();
38735 x.value = x.value.toRed(nred).redPow(e.value).fromRed();
38736 return x;
38737 }
38738
38739 /**
38740 * Compute the inverse of this value modulo n
38741 * Note: this and and n must be relatively prime
38742 * @param {BigInteger} n - Modulo
38743 * @returns {BigInteger} x such that this*x = 1 mod n
38744 * @throws {Error} if the inverse does not exist
38745 */
38746 modInv(n) {
38747 // invm returns a wrong result if the inverse does not exist
38748 if (!this.gcd(n).isOne()) {
38749 throw new Error('Inverse does not exist');
38750 }
38751 return new BigInteger$1(this.value.invm(n.value));
38752 }
38753
38754 /**
38755 * Compute greatest common divisor between this and n
38756 * @param {BigInteger} n - Operand
38757 * @returns {BigInteger} gcd
38758 */
38759 gcd(n) {
38760 return new BigInteger$1(this.value.gcd(n.value));
38761 }
38762
38763 /**
38764 * Shift this to the left by x, in place
38765 * @param {BigInteger} x - Shift value
38766 */
38767 ileftShift(x) {
38768 this.value.ishln(x.value.toNumber());
38769 return this;
38770 }
38771
38772 /**
38773 * Shift this to the left by x
38774 * @param {BigInteger} x - Shift value
38775 * @returns {BigInteger} this << x.
38776 */
38777 leftShift(x) {
38778 return this.clone().ileftShift(x);
38779 }
38780
38781 /**
38782 * Shift this to the right by x, in place
38783 * @param {BigInteger} x - Shift value
38784 */
38785 irightShift(x) {
38786 this.value.ishrn(x.value.toNumber());
38787 return this;
38788 }
38789
38790 /**
38791 * Shift this to the right by x
38792 * @param {BigInteger} x - Shift value
38793 * @returns {BigInteger} this >> x.
38794 */
38795 rightShift(x) {
38796 return this.clone().irightShift(x);
38797 }
38798
38799 /**
38800 * Whether this value is equal to x
38801 * @param {BigInteger} x
38802 * @returns {Boolean}
38803 */
38804 equal(x) {
38805 return this.value.eq(x.value);
38806 }
38807
38808 /**
38809 * Whether this value is less than x
38810 * @param {BigInteger} x
38811 * @returns {Boolean}
38812 */
38813 lt(x) {
38814 return this.value.lt(x.value);
38815 }
38816
38817 /**
38818 * Whether this value is less than or equal to x
38819 * @param {BigInteger} x
38820 * @returns {Boolean}
38821 */
38822 lte(x) {
38823 return this.value.lte(x.value);
38824 }
38825
38826 /**
38827 * Whether this value is greater than x
38828 * @param {BigInteger} x
38829 * @returns {Boolean}
38830 */
38831 gt(x) {
38832 return this.value.gt(x.value);
38833 }
38834
38835 /**
38836 * Whether this value is greater than or equal to x
38837 * @param {BigInteger} x
38838 * @returns {Boolean}
38839 */
38840 gte(x) {
38841 return this.value.gte(x.value);
38842 }
38843
38844 isZero() {
38845 return this.value.isZero();
38846 }
38847
38848 isOne() {
38849 return this.value.eq(new bn(1));
38850 }
38851
38852 isNegative() {
38853 return this.value.isNeg();
38854 }
38855
38856 isEven() {
38857 return this.value.isEven();
38858 }
38859
38860 abs() {
38861 const res = this.clone();
38862 res.value = res.value.abs();
38863 return res;
38864 }
38865
38866 /**
38867 * Get this value as a string
38868 * @returns {String} this value.
38869 */
38870 toString() {
38871 return this.value.toString();
38872 }
38873
38874 /**
38875 * Get this value as an exact Number (max 53 bits)
38876 * Fails if this value is too large
38877 * @returns {Number}
38878 */
38879 toNumber() {
38880 return this.value.toNumber();
38881 }
38882
38883 /**
38884 * Get value of i-th bit
38885 * @param {Number} i - Bit index
38886 * @returns {Number} Bit value.
38887 */
38888 getBit(i) {
38889 return this.value.testn(i) ? 1 : 0;
38890 }
38891
38892 /**
38893 * Compute bit length
38894 * @returns {Number} Bit length.
38895 */
38896 bitLength() {
38897 return this.value.bitLength();
38898 }
38899
38900 /**
38901 * Compute byte length
38902 * @returns {Number} Byte length.
38903 */
38904 byteLength() {
38905 return this.value.byteLength();
38906 }
38907
38908 /**
38909 * Get Uint8Array representation of this number
38910 * @param {String} endian - Endianess of output array (defaults to 'be')
38911 * @param {Number} length - Of output array
38912 * @returns {Uint8Array}
38913 */
38914 toUint8Array(endian = 'be', length) {
38915 return this.value.toArrayLike(Uint8Array, endian, length);
38916 }
38917 }
38918
38919 var bn_interface = /*#__PURE__*/Object.freeze({
38920 __proto__: null,
38921 'default': BigInteger$1
38922 });
38923
38924 var utils_1 = createCommonjsModule(function (module, exports) {
38925
38926 var utils = exports;
38927
38928 function toArray(msg, enc) {
38929 if (Array.isArray(msg))
38930 return msg.slice();
38931 if (!msg)
38932 return [];
38933 var res = [];
38934 if (typeof msg !== 'string') {
38935 for (var i = 0; i < msg.length; i++)
38936 res[i] = msg[i] | 0;
38937 return res;
38938 }
38939 if (enc === 'hex') {
38940 msg = msg.replace(/[^a-z0-9]+/ig, '');
38941 if (msg.length % 2 !== 0)
38942 msg = '0' + msg;
38943 for (var i = 0; i < msg.length; i += 2)
38944 res.push(parseInt(msg[i] + msg[i + 1], 16));
38945 } else {
38946 for (var i = 0; i < msg.length; i++) {
38947 var c = msg.charCodeAt(i);
38948 var hi = c >> 8;
38949 var lo = c & 0xff;
38950 if (hi)
38951 res.push(hi, lo);
38952 else
38953 res.push(lo);
38954 }
38955 }
38956 return res;
38957 }
38958 utils.toArray = toArray;
38959
38960 function zero2(word) {
38961 if (word.length === 1)
38962 return '0' + word;
38963 else
38964 return word;
38965 }
38966 utils.zero2 = zero2;
38967
38968 function toHex(msg) {
38969 var res = '';
38970 for (var i = 0; i < msg.length; i++)
38971 res += zero2(msg[i].toString(16));
38972 return res;
38973 }
38974 utils.toHex = toHex;
38975
38976 utils.encode = function encode(arr, enc) {
38977 if (enc === 'hex')
38978 return toHex(arr);
38979 else
38980 return arr;
38981 };
38982 });
38983
38984 var utils_1$1 = createCommonjsModule(function (module, exports) {
38985
38986 var utils = exports;
38987
38988
38989
38990
38991 utils.assert = minimalisticAssert;
38992 utils.toArray = utils_1.toArray;
38993 utils.zero2 = utils_1.zero2;
38994 utils.toHex = utils_1.toHex;
38995 utils.encode = utils_1.encode;
38996
38997 // Represent num in a w-NAF form
38998 function getNAF(num, w) {
38999 var naf = [];
39000 var ws = 1 << (w + 1);
39001 var k = num.clone();
39002 while (k.cmpn(1) >= 0) {
39003 var z;
39004 if (k.isOdd()) {
39005 var mod = k.andln(ws - 1);
39006 if (mod > (ws >> 1) - 1)
39007 z = (ws >> 1) - mod;
39008 else
39009 z = mod;
39010 k.isubn(z);
39011 } else {
39012 z = 0;
39013 }
39014 naf.push(z);
39015
39016 // Optimization, shift by word if possible
39017 var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
39018 for (var i = 1; i < shift; i++)
39019 naf.push(0);
39020 k.iushrn(shift);
39021 }
39022
39023 return naf;
39024 }
39025 utils.getNAF = getNAF;
39026
39027 // Represent k1, k2 in a Joint Sparse Form
39028 function getJSF(k1, k2) {
39029 var jsf = [
39030 [],
39031 []
39032 ];
39033
39034 k1 = k1.clone();
39035 k2 = k2.clone();
39036 var d1 = 0;
39037 var d2 = 0;
39038 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
39039
39040 // First phase
39041 var m14 = (k1.andln(3) + d1) & 3;
39042 var m24 = (k2.andln(3) + d2) & 3;
39043 if (m14 === 3)
39044 m14 = -1;
39045 if (m24 === 3)
39046 m24 = -1;
39047 var u1;
39048 if ((m14 & 1) === 0) {
39049 u1 = 0;
39050 } else {
39051 var m8 = (k1.andln(7) + d1) & 7;
39052 if ((m8 === 3 || m8 === 5) && m24 === 2)
39053 u1 = -m14;
39054 else
39055 u1 = m14;
39056 }
39057 jsf[0].push(u1);
39058
39059 var u2;
39060 if ((m24 & 1) === 0) {
39061 u2 = 0;
39062 } else {
39063 var m8 = (k2.andln(7) + d2) & 7;
39064 if ((m8 === 3 || m8 === 5) && m14 === 2)
39065 u2 = -m24;
39066 else
39067 u2 = m24;
39068 }
39069 jsf[1].push(u2);
39070
39071 // Second phase
39072 if (2 * d1 === u1 + 1)
39073 d1 = 1 - d1;
39074 if (2 * d2 === u2 + 1)
39075 d2 = 1 - d2;
39076 k1.iushrn(1);
39077 k2.iushrn(1);
39078 }
39079
39080 return jsf;
39081 }
39082 utils.getJSF = getJSF;
39083
39084 function cachedProperty(obj, name, computer) {
39085 var key = '_' + name;
39086 obj.prototype[name] = function cachedProperty() {
39087 return this[key] !== undefined ? this[key] :
39088 this[key] = computer.call(this);
39089 };
39090 }
39091 utils.cachedProperty = cachedProperty;
39092
39093 function parseBytes(bytes) {
39094 return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
39095 bytes;
39096 }
39097 utils.parseBytes = parseBytes;
39098
39099 function intFromLE(bytes) {
39100 return new bn(bytes, 'hex', 'le');
39101 }
39102 utils.intFromLE = intFromLE;
39103 });
39104
39105 var r$1;
39106
39107 var brorand = function rand(len) {
39108 if (!r$1)
39109 r$1 = new Rand(null);
39110
39111 return r$1.generate(len);
39112 };
39113
39114 function Rand(rand) {
39115 this.rand = rand;
39116 }
39117 var Rand_1 = Rand;
39118
39119 Rand.prototype.generate = function generate(len) {
39120 return this._rand(len);
39121 };
39122
39123 // Emulate crypto API using randy
39124 Rand.prototype._rand = function _rand(n) {
39125 if (this.rand.getBytes)
39126 return this.rand.getBytes(n);
39127
39128 var res = new Uint8Array(n);
39129 for (var i = 0; i < res.length; i++)
39130 res[i] = this.rand.getByte();
39131 return res;
39132 };
39133
39134 if (typeof self === 'object') {
39135 if (self.crypto && self.crypto.getRandomValues) {
39136 // Modern browsers
39137 Rand.prototype._rand = function _rand(n) {
39138 var arr = new Uint8Array(n);
39139 self.crypto.getRandomValues(arr);
39140 return arr;
39141 };
39142 } else if (self.msCrypto && self.msCrypto.getRandomValues) {
39143 // IE
39144 Rand.prototype._rand = function _rand(n) {
39145 var arr = new Uint8Array(n);
39146 self.msCrypto.getRandomValues(arr);
39147 return arr;
39148 };
39149
39150 // Safari's WebWorkers do not have `crypto`
39151 } else if (typeof window === 'object') {
39152 // Old junk
39153 Rand.prototype._rand = function() {
39154 throw new Error('Not implemented yet');
39155 };
39156 }
39157 } else {
39158 // Node.js or Web worker with no crypto support
39159 try {
39160 var crypto$2 = void('crypto');
39161 if (typeof crypto$2.randomBytes !== 'function')
39162 throw new Error('Not supported');
39163
39164 Rand.prototype._rand = function _rand(n) {
39165 return crypto$2.randomBytes(n);
39166 };
39167 } catch (e) {
39168 }
39169 }
39170 brorand.Rand = Rand_1;
39171
39172 var getNAF = utils_1$1.getNAF;
39173 var getJSF = utils_1$1.getJSF;
39174 var assert$2 = utils_1$1.assert;
39175
39176 function BaseCurve(type, conf) {
39177 this.type = type;
39178 this.p = new bn(conf.p, 16);
39179
39180 // Use Montgomery, when there is no fast reduction for the prime
39181 this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p);
39182
39183 // Useful for many curves
39184 this.zero = new bn(0).toRed(this.red);
39185 this.one = new bn(1).toRed(this.red);
39186 this.two = new bn(2).toRed(this.red);
39187
39188 // Curve configuration, optional
39189 this.n = conf.n && new bn(conf.n, 16);
39190 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
39191
39192 // Temporary arrays
39193 this._wnafT1 = new Array(4);
39194 this._wnafT2 = new Array(4);
39195 this._wnafT3 = new Array(4);
39196 this._wnafT4 = new Array(4);
39197
39198 // Generalized Greg Maxwell's trick
39199 var adjustCount = this.n && this.p.div(this.n);
39200 if (!adjustCount || adjustCount.cmpn(100) > 0) {
39201 this.redN = null;
39202 } else {
39203 this._maxwellTrick = true;
39204 this.redN = this.n.toRed(this.red);
39205 }
39206 }
39207 var base = BaseCurve;
39208
39209 BaseCurve.prototype.point = function point() {
39210 throw new Error('Not implemented');
39211 };
39212
39213 BaseCurve.prototype.validate = function validate() {
39214 throw new Error('Not implemented');
39215 };
39216
39217 BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
39218 assert$2(p.precomputed);
39219 var doubles = p._getDoubles();
39220
39221 var naf = getNAF(k, 1);
39222 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
39223 I /= 3;
39224
39225 // Translate into more windowed form
39226 var repr = [];
39227 for (var j = 0; j < naf.length; j += doubles.step) {
39228 var nafW = 0;
39229 for (var k = j + doubles.step - 1; k >= j; k--)
39230 nafW = (nafW << 1) + naf[k];
39231 repr.push(nafW);
39232 }
39233
39234 var a = this.jpoint(null, null, null);
39235 var b = this.jpoint(null, null, null);
39236 for (var i = I; i > 0; i--) {
39237 for (var j = 0; j < repr.length; j++) {
39238 var nafW = repr[j];
39239 if (nafW === i)
39240 b = b.mixedAdd(doubles.points[j]);
39241 else if (nafW === -i)
39242 b = b.mixedAdd(doubles.points[j].neg());
39243 }
39244 a = a.add(b);
39245 }
39246 return a.toP();
39247 };
39248
39249 BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
39250 var w = 4;
39251
39252 // Precompute window
39253 var nafPoints = p._getNAFPoints(w);
39254 w = nafPoints.wnd;
39255 var wnd = nafPoints.points;
39256
39257 // Get NAF form
39258 var naf = getNAF(k, w);
39259
39260 // Add `this`*(N+1) for every w-NAF index
39261 var acc = this.jpoint(null, null, null);
39262 for (var i = naf.length - 1; i >= 0; i--) {
39263 // Count zeroes
39264 for (var k = 0; i >= 0 && naf[i] === 0; i--)
39265 k++;
39266 if (i >= 0)
39267 k++;
39268 acc = acc.dblp(k);
39269
39270 if (i < 0)
39271 break;
39272 var z = naf[i];
39273 assert$2(z !== 0);
39274 if (p.type === 'affine') {
39275 // J +- P
39276 if (z > 0)
39277 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
39278 else
39279 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
39280 } else {
39281 // J +- J
39282 if (z > 0)
39283 acc = acc.add(wnd[(z - 1) >> 1]);
39284 else
39285 acc = acc.add(wnd[(-z - 1) >> 1].neg());
39286 }
39287 }
39288 return p.type === 'affine' ? acc.toP() : acc;
39289 };
39290
39291 BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
39292 points,
39293 coeffs,
39294 len,
39295 jacobianResult) {
39296 var wndWidth = this._wnafT1;
39297 var wnd = this._wnafT2;
39298 var naf = this._wnafT3;
39299
39300 // Fill all arrays
39301 var max = 0;
39302 for (var i = 0; i < len; i++) {
39303 var p = points[i];
39304 var nafPoints = p._getNAFPoints(defW);
39305 wndWidth[i] = nafPoints.wnd;
39306 wnd[i] = nafPoints.points;
39307 }
39308
39309 // Comb small window NAFs
39310 for (var i = len - 1; i >= 1; i -= 2) {
39311 var a = i - 1;
39312 var b = i;
39313 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
39314 naf[a] = getNAF(coeffs[a], wndWidth[a]);
39315 naf[b] = getNAF(coeffs[b], wndWidth[b]);
39316 max = Math.max(naf[a].length, max);
39317 max = Math.max(naf[b].length, max);
39318 continue;
39319 }
39320
39321 var comb = [
39322 points[a], /* 1 */
39323 null, /* 3 */
39324 null, /* 5 */
39325 points[b] /* 7 */
39326 ];
39327
39328 // Try to avoid Projective points, if possible
39329 if (points[a].y.cmp(points[b].y) === 0) {
39330 comb[1] = points[a].add(points[b]);
39331 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
39332 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
39333 comb[1] = points[a].toJ().mixedAdd(points[b]);
39334 comb[2] = points[a].add(points[b].neg());
39335 } else {
39336 comb[1] = points[a].toJ().mixedAdd(points[b]);
39337 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
39338 }
39339
39340 var index = [
39341 -3, /* -1 -1 */
39342 -1, /* -1 0 */
39343 -5, /* -1 1 */
39344 -7, /* 0 -1 */
39345 0, /* 0 0 */
39346 7, /* 0 1 */
39347 5, /* 1 -1 */
39348 1, /* 1 0 */
39349 3 /* 1 1 */
39350 ];
39351
39352 var jsf = getJSF(coeffs[a], coeffs[b]);
39353 max = Math.max(jsf[0].length, max);
39354 naf[a] = new Array(max);
39355 naf[b] = new Array(max);
39356 for (var j = 0; j < max; j++) {
39357 var ja = jsf[0][j] | 0;
39358 var jb = jsf[1][j] | 0;
39359
39360 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
39361 naf[b][j] = 0;
39362 wnd[a] = comb;
39363 }
39364 }
39365
39366 var acc = this.jpoint(null, null, null);
39367 var tmp = this._wnafT4;
39368 for (var i = max; i >= 0; i--) {
39369 var k = 0;
39370
39371 while (i >= 0) {
39372 var zero = true;
39373 for (var j = 0; j < len; j++) {
39374 tmp[j] = naf[j][i] | 0;
39375 if (tmp[j] !== 0)
39376 zero = false;
39377 }
39378 if (!zero)
39379 break;
39380 k++;
39381 i--;
39382 }
39383 if (i >= 0)
39384 k++;
39385 acc = acc.dblp(k);
39386 if (i < 0)
39387 break;
39388
39389 for (var j = 0; j < len; j++) {
39390 var z = tmp[j];
39391 var p;
39392 if (z === 0)
39393 continue;
39394 else if (z > 0)
39395 p = wnd[j][(z - 1) >> 1];
39396 else if (z < 0)
39397 p = wnd[j][(-z - 1) >> 1].neg();
39398
39399 if (p.type === 'affine')
39400 acc = acc.mixedAdd(p);
39401 else
39402 acc = acc.add(p);
39403 }
39404 }
39405 // Zeroify references
39406 for (var i = 0; i < len; i++)
39407 wnd[i] = null;
39408
39409 if (jacobianResult)
39410 return acc;
39411 else
39412 return acc.toP();
39413 };
39414
39415 function BasePoint(curve, type) {
39416 this.curve = curve;
39417 this.type = type;
39418 this.precomputed = null;
39419 }
39420 BaseCurve.BasePoint = BasePoint;
39421
39422 BasePoint.prototype.eq = function eq(/*other*/) {
39423 throw new Error('Not implemented');
39424 };
39425
39426 BasePoint.prototype.validate = function validate() {
39427 return this.curve.validate(this);
39428 };
39429
39430 BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
39431 bytes = utils_1$1.toArray(bytes, enc);
39432
39433 var len = this.p.byteLength();
39434
39435 // uncompressed, hybrid-odd, hybrid-even
39436 if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
39437 bytes.length - 1 === 2 * len) {
39438 if (bytes[0] === 0x06)
39439 assert$2(bytes[bytes.length - 1] % 2 === 0);
39440 else if (bytes[0] === 0x07)
39441 assert$2(bytes[bytes.length - 1] % 2 === 1);
39442
39443 var res = this.point(bytes.slice(1, 1 + len),
39444 bytes.slice(1 + len, 1 + 2 * len));
39445
39446 return res;
39447 } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
39448 bytes.length - 1 === len) {
39449 return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
39450 }
39451 throw new Error('Unknown point format');
39452 };
39453
39454 BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
39455 return this.encode(enc, true);
39456 };
39457
39458 BasePoint.prototype._encode = function _encode(compact) {
39459 var len = this.curve.p.byteLength();
39460 var x = this.getX().toArray('be', len);
39461
39462 if (compact)
39463 return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
39464
39465 return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
39466 };
39467
39468 BasePoint.prototype.encode = function encode(enc, compact) {
39469 return utils_1$1.encode(this._encode(compact), enc);
39470 };
39471
39472 BasePoint.prototype.precompute = function precompute(power) {
39473 if (this.precomputed)
39474 return this;
39475
39476 var precomputed = {
39477 doubles: null,
39478 naf: null,
39479 beta: null
39480 };
39481 precomputed.naf = this._getNAFPoints(8);
39482 precomputed.doubles = this._getDoubles(4, power);
39483 precomputed.beta = this._getBeta();
39484 this.precomputed = precomputed;
39485
39486 return this;
39487 };
39488
39489 BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
39490 if (!this.precomputed)
39491 return false;
39492
39493 var doubles = this.precomputed.doubles;
39494 if (!doubles)
39495 return false;
39496
39497 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
39498 };
39499
39500 BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
39501 if (this.precomputed && this.precomputed.doubles)
39502 return this.precomputed.doubles;
39503
39504 var doubles = [ this ];
39505 var acc = this;
39506 for (var i = 0; i < power; i += step) {
39507 for (var j = 0; j < step; j++)
39508 acc = acc.dbl();
39509 doubles.push(acc);
39510 }
39511 return {
39512 step: step,
39513 points: doubles
39514 };
39515 };
39516
39517 BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
39518 if (this.precomputed && this.precomputed.naf)
39519 return this.precomputed.naf;
39520
39521 var res = [ this ];
39522 var max = (1 << wnd) - 1;
39523 var dbl = max === 1 ? null : this.dbl();
39524 for (var i = 1; i < max; i++)
39525 res[i] = res[i - 1].add(dbl);
39526 return {
39527 wnd: wnd,
39528 points: res
39529 };
39530 };
39531
39532 BasePoint.prototype._getBeta = function _getBeta() {
39533 return null;
39534 };
39535
39536 BasePoint.prototype.dblp = function dblp(k) {
39537 var r = this;
39538 for (var i = 0; i < k; i++)
39539 r = r.dbl();
39540 return r;
39541 };
39542
39543 var assert$3 = utils_1$1.assert;
39544
39545 function ShortCurve(conf) {
39546 base.call(this, 'short', conf);
39547
39548 this.a = new bn(conf.a, 16).toRed(this.red);
39549 this.b = new bn(conf.b, 16).toRed(this.red);
39550 this.tinv = this.two.redInvm();
39551
39552 this.zeroA = this.a.fromRed().cmpn(0) === 0;
39553 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
39554
39555 // If the curve is endomorphic, precalculate beta and lambda
39556 this.endo = this._getEndomorphism(conf);
39557 this._endoWnafT1 = new Array(4);
39558 this._endoWnafT2 = new Array(4);
39559 }
39560 inherits_browser(ShortCurve, base);
39561 var short_1 = ShortCurve;
39562
39563 ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
39564 // No efficient endomorphism
39565 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
39566 return;
39567
39568 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
39569 var beta;
39570 var lambda;
39571 if (conf.beta) {
39572 beta = new bn(conf.beta, 16).toRed(this.red);
39573 } else {
39574 var betas = this._getEndoRoots(this.p);
39575 // Choose the smallest beta
39576 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
39577 beta = beta.toRed(this.red);
39578 }
39579 if (conf.lambda) {
39580 lambda = new bn(conf.lambda, 16);
39581 } else {
39582 // Choose the lambda that is matching selected beta
39583 var lambdas = this._getEndoRoots(this.n);
39584 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
39585 lambda = lambdas[0];
39586 } else {
39587 lambda = lambdas[1];
39588 assert$3(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
39589 }
39590 }
39591
39592 // Get basis vectors, used for balanced length-two representation
39593 var basis;
39594 if (conf.basis) {
39595 basis = conf.basis.map(function(vec) {
39596 return {
39597 a: new bn(vec.a, 16),
39598 b: new bn(vec.b, 16)
39599 };
39600 });
39601 } else {
39602 basis = this._getEndoBasis(lambda);
39603 }
39604
39605 return {
39606 beta: beta,
39607 lambda: lambda,
39608 basis: basis
39609 };
39610 };
39611
39612 ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
39613 // Find roots of for x^2 + x + 1 in F
39614 // Root = (-1 +- Sqrt(-3)) / 2
39615 //
39616 var red = num === this.p ? this.red : bn.mont(num);
39617 var tinv = new bn(2).toRed(red).redInvm();
39618 var ntinv = tinv.redNeg();
39619
39620 var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv);
39621
39622 var l1 = ntinv.redAdd(s).fromRed();
39623 var l2 = ntinv.redSub(s).fromRed();
39624 return [ l1, l2 ];
39625 };
39626
39627 ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
39628 // aprxSqrt >= sqrt(this.n)
39629 var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
39630
39631 // 3.74
39632 // Run EGCD, until r(L + 1) < aprxSqrt
39633 var u = lambda;
39634 var v = this.n.clone();
39635 var x1 = new bn(1);
39636 var y1 = new bn(0);
39637 var x2 = new bn(0);
39638 var y2 = new bn(1);
39639
39640 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
39641 var a0;
39642 var b0;
39643 // First vector
39644 var a1;
39645 var b1;
39646 // Second vector
39647 var a2;
39648 var b2;
39649
39650 var prevR;
39651 var i = 0;
39652 var r;
39653 var x;
39654 while (u.cmpn(0) !== 0) {
39655 var q = v.div(u);
39656 r = v.sub(q.mul(u));
39657 x = x2.sub(q.mul(x1));
39658 var y = y2.sub(q.mul(y1));
39659
39660 if (!a1 && r.cmp(aprxSqrt) < 0) {
39661 a0 = prevR.neg();
39662 b0 = x1;
39663 a1 = r.neg();
39664 b1 = x;
39665 } else if (a1 && ++i === 2) {
39666 break;
39667 }
39668 prevR = r;
39669
39670 v = u;
39671 u = r;
39672 x2 = x1;
39673 x1 = x;
39674 y2 = y1;
39675 y1 = y;
39676 }
39677 a2 = r.neg();
39678 b2 = x;
39679
39680 var len1 = a1.sqr().add(b1.sqr());
39681 var len2 = a2.sqr().add(b2.sqr());
39682 if (len2.cmp(len1) >= 0) {
39683 a2 = a0;
39684 b2 = b0;
39685 }
39686
39687 // Normalize signs
39688 if (a1.negative) {
39689 a1 = a1.neg();
39690 b1 = b1.neg();
39691 }
39692 if (a2.negative) {
39693 a2 = a2.neg();
39694 b2 = b2.neg();
39695 }
39696
39697 return [
39698 { a: a1, b: b1 },
39699 { a: a2, b: b2 }
39700 ];
39701 };
39702
39703 ShortCurve.prototype._endoSplit = function _endoSplit(k) {
39704 var basis = this.endo.basis;
39705 var v1 = basis[0];
39706 var v2 = basis[1];
39707
39708 var c1 = v2.b.mul(k).divRound(this.n);
39709 var c2 = v1.b.neg().mul(k).divRound(this.n);
39710
39711 var p1 = c1.mul(v1.a);
39712 var p2 = c2.mul(v2.a);
39713 var q1 = c1.mul(v1.b);
39714 var q2 = c2.mul(v2.b);
39715
39716 // Calculate answer
39717 var k1 = k.sub(p1).sub(p2);
39718 var k2 = q1.add(q2).neg();
39719 return { k1: k1, k2: k2 };
39720 };
39721
39722 ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
39723 x = new bn(x, 16);
39724 if (!x.red)
39725 x = x.toRed(this.red);
39726
39727 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
39728 var y = y2.redSqrt();
39729 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
39730 throw new Error('invalid point');
39731
39732 // XXX Is there any way to tell if the number is odd without converting it
39733 // to non-red form?
39734 var isOdd = y.fromRed().isOdd();
39735 if (odd && !isOdd || !odd && isOdd)
39736 y = y.redNeg();
39737
39738 return this.point(x, y);
39739 };
39740
39741 ShortCurve.prototype.validate = function validate(point) {
39742 if (point.inf)
39743 return true;
39744
39745 var x = point.x;
39746 var y = point.y;
39747
39748 var ax = this.a.redMul(x);
39749 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
39750 return y.redSqr().redISub(rhs).cmpn(0) === 0;
39751 };
39752
39753 ShortCurve.prototype._endoWnafMulAdd =
39754 function _endoWnafMulAdd(points, coeffs, jacobianResult) {
39755 var npoints = this._endoWnafT1;
39756 var ncoeffs = this._endoWnafT2;
39757 for (var i = 0; i < points.length; i++) {
39758 var split = this._endoSplit(coeffs[i]);
39759 var p = points[i];
39760 var beta = p._getBeta();
39761
39762 if (split.k1.negative) {
39763 split.k1.ineg();
39764 p = p.neg(true);
39765 }
39766 if (split.k2.negative) {
39767 split.k2.ineg();
39768 beta = beta.neg(true);
39769 }
39770
39771 npoints[i * 2] = p;
39772 npoints[i * 2 + 1] = beta;
39773 ncoeffs[i * 2] = split.k1;
39774 ncoeffs[i * 2 + 1] = split.k2;
39775 }
39776 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
39777
39778 // Clean-up references to points and coefficients
39779 for (var j = 0; j < i * 2; j++) {
39780 npoints[j] = null;
39781 ncoeffs[j] = null;
39782 }
39783 return res;
39784 };
39785
39786 function Point(curve, x, y, isRed) {
39787 base.BasePoint.call(this, curve, 'affine');
39788 if (x === null && y === null) {
39789 this.x = null;
39790 this.y = null;
39791 this.inf = true;
39792 } else {
39793 this.x = new bn(x, 16);
39794 this.y = new bn(y, 16);
39795 // Force redgomery representation when loading from JSON
39796 if (isRed) {
39797 this.x.forceRed(this.curve.red);
39798 this.y.forceRed(this.curve.red);
39799 }
39800 if (!this.x.red)
39801 this.x = this.x.toRed(this.curve.red);
39802 if (!this.y.red)
39803 this.y = this.y.toRed(this.curve.red);
39804 this.inf = false;
39805 }
39806 }
39807 inherits_browser(Point, base.BasePoint);
39808
39809 ShortCurve.prototype.point = function point(x, y, isRed) {
39810 return new Point(this, x, y, isRed);
39811 };
39812
39813 ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
39814 return Point.fromJSON(this, obj, red);
39815 };
39816
39817 Point.prototype._getBeta = function _getBeta() {
39818 if (!this.curve.endo)
39819 return;
39820
39821 var pre = this.precomputed;
39822 if (pre && pre.beta)
39823 return pre.beta;
39824
39825 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
39826 if (pre) {
39827 var curve = this.curve;
39828 var endoMul = function(p) {
39829 return curve.point(p.x.redMul(curve.endo.beta), p.y);
39830 };
39831 pre.beta = beta;
39832 beta.precomputed = {
39833 beta: null,
39834 naf: pre.naf && {
39835 wnd: pre.naf.wnd,
39836 points: pre.naf.points.map(endoMul)
39837 },
39838 doubles: pre.doubles && {
39839 step: pre.doubles.step,
39840 points: pre.doubles.points.map(endoMul)
39841 }
39842 };
39843 }
39844 return beta;
39845 };
39846
39847 Point.prototype.toJSON = function toJSON() {
39848 if (!this.precomputed)
39849 return [ this.x, this.y ];
39850
39851 return [ this.x, this.y, this.precomputed && {
39852 doubles: this.precomputed.doubles && {
39853 step: this.precomputed.doubles.step,
39854 points: this.precomputed.doubles.points.slice(1)
39855 },
39856 naf: this.precomputed.naf && {
39857 wnd: this.precomputed.naf.wnd,
39858 points: this.precomputed.naf.points.slice(1)
39859 }
39860 } ];
39861 };
39862
39863 Point.fromJSON = function fromJSON(curve, obj, red) {
39864 if (typeof obj === 'string')
39865 obj = JSON.parse(obj);
39866 var res = curve.point(obj[0], obj[1], red);
39867 if (!obj[2])
39868 return res;
39869
39870 function obj2point(obj) {
39871 return curve.point(obj[0], obj[1], red);
39872 }
39873
39874 var pre = obj[2];
39875 res.precomputed = {
39876 beta: null,
39877 doubles: pre.doubles && {
39878 step: pre.doubles.step,
39879 points: [ res ].concat(pre.doubles.points.map(obj2point))
39880 },
39881 naf: pre.naf && {
39882 wnd: pre.naf.wnd,
39883 points: [ res ].concat(pre.naf.points.map(obj2point))
39884 }
39885 };
39886 return res;
39887 };
39888
39889 Point.prototype.inspect = function inspect() {
39890 if (this.isInfinity())
39891 return '<EC Point Infinity>';
39892 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
39893 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
39894 };
39895
39896 Point.prototype.isInfinity = function isInfinity() {
39897 return this.inf;
39898 };
39899
39900 Point.prototype.add = function add(p) {
39901 // O + P = P
39902 if (this.inf)
39903 return p;
39904
39905 // P + O = P
39906 if (p.inf)
39907 return this;
39908
39909 // P + P = 2P
39910 if (this.eq(p))
39911 return this.dbl();
39912
39913 // P + (-P) = O
39914 if (this.neg().eq(p))
39915 return this.curve.point(null, null);
39916
39917 // P + Q = O
39918 if (this.x.cmp(p.x) === 0)
39919 return this.curve.point(null, null);
39920
39921 var c = this.y.redSub(p.y);
39922 if (c.cmpn(0) !== 0)
39923 c = c.redMul(this.x.redSub(p.x).redInvm());
39924 var nx = c.redSqr().redISub(this.x).redISub(p.x);
39925 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
39926 return this.curve.point(nx, ny);
39927 };
39928
39929 Point.prototype.dbl = function dbl() {
39930 if (this.inf)
39931 return this;
39932
39933 // 2P = O
39934 var ys1 = this.y.redAdd(this.y);
39935 if (ys1.cmpn(0) === 0)
39936 return this.curve.point(null, null);
39937
39938 var a = this.curve.a;
39939
39940 var x2 = this.x.redSqr();
39941 var dyinv = ys1.redInvm();
39942 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
39943
39944 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
39945 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
39946 return this.curve.point(nx, ny);
39947 };
39948
39949 Point.prototype.getX = function getX() {
39950 return this.x.fromRed();
39951 };
39952
39953 Point.prototype.getY = function getY() {
39954 return this.y.fromRed();
39955 };
39956
39957 Point.prototype.mul = function mul(k) {
39958 k = new bn(k, 16);
39959 if (this.isInfinity())
39960 return this;
39961 else if (this._hasDoubles(k))
39962 return this.curve._fixedNafMul(this, k);
39963 else if (this.curve.endo)
39964 return this.curve._endoWnafMulAdd([ this ], [ k ]);
39965 else
39966 return this.curve._wnafMul(this, k);
39967 };
39968
39969 Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
39970 var points = [ this, p2 ];
39971 var coeffs = [ k1, k2 ];
39972 if (this.curve.endo)
39973 return this.curve._endoWnafMulAdd(points, coeffs);
39974 else
39975 return this.curve._wnafMulAdd(1, points, coeffs, 2);
39976 };
39977
39978 Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
39979 var points = [ this, p2 ];
39980 var coeffs = [ k1, k2 ];
39981 if (this.curve.endo)
39982 return this.curve._endoWnafMulAdd(points, coeffs, true);
39983 else
39984 return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
39985 };
39986
39987 Point.prototype.eq = function eq(p) {
39988 return this === p ||
39989 this.inf === p.inf &&
39990 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
39991 };
39992
39993 Point.prototype.neg = function neg(_precompute) {
39994 if (this.inf)
39995 return this;
39996
39997 var res = this.curve.point(this.x, this.y.redNeg());
39998 if (_precompute && this.precomputed) {
39999 var pre = this.precomputed;
40000 var negate = function(p) {
40001 return p.neg();
40002 };
40003 res.precomputed = {
40004 naf: pre.naf && {
40005 wnd: pre.naf.wnd,
40006 points: pre.naf.points.map(negate)
40007 },
40008 doubles: pre.doubles && {
40009 step: pre.doubles.step,
40010 points: pre.doubles.points.map(negate)
40011 }
40012 };
40013 }
40014 return res;
40015 };
40016
40017 Point.prototype.toJ = function toJ() {
40018 if (this.inf)
40019 return this.curve.jpoint(null, null, null);
40020
40021 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
40022 return res;
40023 };
40024
40025 function JPoint(curve, x, y, z) {
40026 base.BasePoint.call(this, curve, 'jacobian');
40027 if (x === null && y === null && z === null) {
40028 this.x = this.curve.one;
40029 this.y = this.curve.one;
40030 this.z = new bn(0);
40031 } else {
40032 this.x = new bn(x, 16);
40033 this.y = new bn(y, 16);
40034 this.z = new bn(z, 16);
40035 }
40036 if (!this.x.red)
40037 this.x = this.x.toRed(this.curve.red);
40038 if (!this.y.red)
40039 this.y = this.y.toRed(this.curve.red);
40040 if (!this.z.red)
40041 this.z = this.z.toRed(this.curve.red);
40042
40043 this.zOne = this.z === this.curve.one;
40044 }
40045 inherits_browser(JPoint, base.BasePoint);
40046
40047 ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
40048 return new JPoint(this, x, y, z);
40049 };
40050
40051 JPoint.prototype.toP = function toP() {
40052 if (this.isInfinity())
40053 return this.curve.point(null, null);
40054
40055 var zinv = this.z.redInvm();
40056 var zinv2 = zinv.redSqr();
40057 var ax = this.x.redMul(zinv2);
40058 var ay = this.y.redMul(zinv2).redMul(zinv);
40059
40060 return this.curve.point(ax, ay);
40061 };
40062
40063 JPoint.prototype.neg = function neg() {
40064 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
40065 };
40066
40067 JPoint.prototype.add = function add(p) {
40068 // O + P = P
40069 if (this.isInfinity())
40070 return p;
40071
40072 // P + O = P
40073 if (p.isInfinity())
40074 return this;
40075
40076 // 12M + 4S + 7A
40077 var pz2 = p.z.redSqr();
40078 var z2 = this.z.redSqr();
40079 var u1 = this.x.redMul(pz2);
40080 var u2 = p.x.redMul(z2);
40081 var s1 = this.y.redMul(pz2.redMul(p.z));
40082 var s2 = p.y.redMul(z2.redMul(this.z));
40083
40084 var h = u1.redSub(u2);
40085 var r = s1.redSub(s2);
40086 if (h.cmpn(0) === 0) {
40087 if (r.cmpn(0) !== 0)
40088 return this.curve.jpoint(null, null, null);
40089 else
40090 return this.dbl();
40091 }
40092
40093 var h2 = h.redSqr();
40094 var h3 = h2.redMul(h);
40095 var v = u1.redMul(h2);
40096
40097 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
40098 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
40099 var nz = this.z.redMul(p.z).redMul(h);
40100
40101 return this.curve.jpoint(nx, ny, nz);
40102 };
40103
40104 JPoint.prototype.mixedAdd = function mixedAdd(p) {
40105 // O + P = P
40106 if (this.isInfinity())
40107 return p.toJ();
40108
40109 // P + O = P
40110 if (p.isInfinity())
40111 return this;
40112
40113 // 8M + 3S + 7A
40114 var z2 = this.z.redSqr();
40115 var u1 = this.x;
40116 var u2 = p.x.redMul(z2);
40117 var s1 = this.y;
40118 var s2 = p.y.redMul(z2).redMul(this.z);
40119
40120 var h = u1.redSub(u2);
40121 var r = s1.redSub(s2);
40122 if (h.cmpn(0) === 0) {
40123 if (r.cmpn(0) !== 0)
40124 return this.curve.jpoint(null, null, null);
40125 else
40126 return this.dbl();
40127 }
40128
40129 var h2 = h.redSqr();
40130 var h3 = h2.redMul(h);
40131 var v = u1.redMul(h2);
40132
40133 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
40134 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
40135 var nz = this.z.redMul(h);
40136
40137 return this.curve.jpoint(nx, ny, nz);
40138 };
40139
40140 JPoint.prototype.dblp = function dblp(pow) {
40141 if (pow === 0)
40142 return this;
40143 if (this.isInfinity())
40144 return this;
40145 if (!pow)
40146 return this.dbl();
40147
40148 if (this.curve.zeroA || this.curve.threeA) {
40149 var r = this;
40150 for (var i = 0; i < pow; i++)
40151 r = r.dbl();
40152 return r;
40153 }
40154
40155 // 1M + 2S + 1A + N * (4S + 5M + 8A)
40156 // N = 1 => 6M + 6S + 9A
40157 var a = this.curve.a;
40158 var tinv = this.curve.tinv;
40159
40160 var jx = this.x;
40161 var jy = this.y;
40162 var jz = this.z;
40163 var jz4 = jz.redSqr().redSqr();
40164
40165 // Reuse results
40166 var jyd = jy.redAdd(jy);
40167 for (var i = 0; i < pow; i++) {
40168 var jx2 = jx.redSqr();
40169 var jyd2 = jyd.redSqr();
40170 var jyd4 = jyd2.redSqr();
40171 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
40172
40173 var t1 = jx.redMul(jyd2);
40174 var nx = c.redSqr().redISub(t1.redAdd(t1));
40175 var t2 = t1.redISub(nx);
40176 var dny = c.redMul(t2);
40177 dny = dny.redIAdd(dny).redISub(jyd4);
40178 var nz = jyd.redMul(jz);
40179 if (i + 1 < pow)
40180 jz4 = jz4.redMul(jyd4);
40181
40182 jx = nx;
40183 jz = nz;
40184 jyd = dny;
40185 }
40186
40187 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
40188 };
40189
40190 JPoint.prototype.dbl = function dbl() {
40191 if (this.isInfinity())
40192 return this;
40193
40194 if (this.curve.zeroA)
40195 return this._zeroDbl();
40196 else if (this.curve.threeA)
40197 return this._threeDbl();
40198 else
40199 return this._dbl();
40200 };
40201
40202 JPoint.prototype._zeroDbl = function _zeroDbl() {
40203 var nx;
40204 var ny;
40205 var nz;
40206 // Z = 1
40207 if (this.zOne) {
40208 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
40209 // #doubling-mdbl-2007-bl
40210 // 1M + 5S + 14A
40211
40212 // XX = X1^2
40213 var xx = this.x.redSqr();
40214 // YY = Y1^2
40215 var yy = this.y.redSqr();
40216 // YYYY = YY^2
40217 var yyyy = yy.redSqr();
40218 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
40219 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
40220 s = s.redIAdd(s);
40221 // M = 3 * XX + a; a = 0
40222 var m = xx.redAdd(xx).redIAdd(xx);
40223 // T = M ^ 2 - 2*S
40224 var t = m.redSqr().redISub(s).redISub(s);
40225
40226 // 8 * YYYY
40227 var yyyy8 = yyyy.redIAdd(yyyy);
40228 yyyy8 = yyyy8.redIAdd(yyyy8);
40229 yyyy8 = yyyy8.redIAdd(yyyy8);
40230
40231 // X3 = T
40232 nx = t;
40233 // Y3 = M * (S - T) - 8 * YYYY
40234 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
40235 // Z3 = 2*Y1
40236 nz = this.y.redAdd(this.y);
40237 } else {
40238 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
40239 // #doubling-dbl-2009-l
40240 // 2M + 5S + 13A
40241
40242 // A = X1^2
40243 var a = this.x.redSqr();
40244 // B = Y1^2
40245 var b = this.y.redSqr();
40246 // C = B^2
40247 var c = b.redSqr();
40248 // D = 2 * ((X1 + B)^2 - A - C)
40249 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
40250 d = d.redIAdd(d);
40251 // E = 3 * A
40252 var e = a.redAdd(a).redIAdd(a);
40253 // F = E^2
40254 var f = e.redSqr();
40255
40256 // 8 * C
40257 var c8 = c.redIAdd(c);
40258 c8 = c8.redIAdd(c8);
40259 c8 = c8.redIAdd(c8);
40260
40261 // X3 = F - 2 * D
40262 nx = f.redISub(d).redISub(d);
40263 // Y3 = E * (D - X3) - 8 * C
40264 ny = e.redMul(d.redISub(nx)).redISub(c8);
40265 // Z3 = 2 * Y1 * Z1
40266 nz = this.y.redMul(this.z);
40267 nz = nz.redIAdd(nz);
40268 }
40269
40270 return this.curve.jpoint(nx, ny, nz);
40271 };
40272
40273 JPoint.prototype._threeDbl = function _threeDbl() {
40274 var nx;
40275 var ny;
40276 var nz;
40277 // Z = 1
40278 if (this.zOne) {
40279 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
40280 // #doubling-mdbl-2007-bl
40281 // 1M + 5S + 15A
40282
40283 // XX = X1^2
40284 var xx = this.x.redSqr();
40285 // YY = Y1^2
40286 var yy = this.y.redSqr();
40287 // YYYY = YY^2
40288 var yyyy = yy.redSqr();
40289 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
40290 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
40291 s = s.redIAdd(s);
40292 // M = 3 * XX + a
40293 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
40294 // T = M^2 - 2 * S
40295 var t = m.redSqr().redISub(s).redISub(s);
40296 // X3 = T
40297 nx = t;
40298 // Y3 = M * (S - T) - 8 * YYYY
40299 var yyyy8 = yyyy.redIAdd(yyyy);
40300 yyyy8 = yyyy8.redIAdd(yyyy8);
40301 yyyy8 = yyyy8.redIAdd(yyyy8);
40302 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
40303 // Z3 = 2 * Y1
40304 nz = this.y.redAdd(this.y);
40305 } else {
40306 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
40307 // 3M + 5S
40308
40309 // delta = Z1^2
40310 var delta = this.z.redSqr();
40311 // gamma = Y1^2
40312 var gamma = this.y.redSqr();
40313 // beta = X1 * gamma
40314 var beta = this.x.redMul(gamma);
40315 // alpha = 3 * (X1 - delta) * (X1 + delta)
40316 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
40317 alpha = alpha.redAdd(alpha).redIAdd(alpha);
40318 // X3 = alpha^2 - 8 * beta
40319 var beta4 = beta.redIAdd(beta);
40320 beta4 = beta4.redIAdd(beta4);
40321 var beta8 = beta4.redAdd(beta4);
40322 nx = alpha.redSqr().redISub(beta8);
40323 // Z3 = (Y1 + Z1)^2 - gamma - delta
40324 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
40325 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
40326 var ggamma8 = gamma.redSqr();
40327 ggamma8 = ggamma8.redIAdd(ggamma8);
40328 ggamma8 = ggamma8.redIAdd(ggamma8);
40329 ggamma8 = ggamma8.redIAdd(ggamma8);
40330 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
40331 }
40332
40333 return this.curve.jpoint(nx, ny, nz);
40334 };
40335
40336 JPoint.prototype._dbl = function _dbl() {
40337 var a = this.curve.a;
40338
40339 // 4M + 6S + 10A
40340 var jx = this.x;
40341 var jy = this.y;
40342 var jz = this.z;
40343 var jz4 = jz.redSqr().redSqr();
40344
40345 var jx2 = jx.redSqr();
40346 var jy2 = jy.redSqr();
40347
40348 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
40349
40350 var jxd4 = jx.redAdd(jx);
40351 jxd4 = jxd4.redIAdd(jxd4);
40352 var t1 = jxd4.redMul(jy2);
40353 var nx = c.redSqr().redISub(t1.redAdd(t1));
40354 var t2 = t1.redISub(nx);
40355
40356 var jyd8 = jy2.redSqr();
40357 jyd8 = jyd8.redIAdd(jyd8);
40358 jyd8 = jyd8.redIAdd(jyd8);
40359 jyd8 = jyd8.redIAdd(jyd8);
40360 var ny = c.redMul(t2).redISub(jyd8);
40361 var nz = jy.redAdd(jy).redMul(jz);
40362
40363 return this.curve.jpoint(nx, ny, nz);
40364 };
40365
40366 JPoint.prototype.trpl = function trpl() {
40367 if (!this.curve.zeroA)
40368 return this.dbl().add(this);
40369
40370 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
40371 // 5M + 10S + ...
40372
40373 // XX = X1^2
40374 var xx = this.x.redSqr();
40375 // YY = Y1^2
40376 var yy = this.y.redSqr();
40377 // ZZ = Z1^2
40378 var zz = this.z.redSqr();
40379 // YYYY = YY^2
40380 var yyyy = yy.redSqr();
40381 // M = 3 * XX + a * ZZ2; a = 0
40382 var m = xx.redAdd(xx).redIAdd(xx);
40383 // MM = M^2
40384 var mm = m.redSqr();
40385 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
40386 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
40387 e = e.redIAdd(e);
40388 e = e.redAdd(e).redIAdd(e);
40389 e = e.redISub(mm);
40390 // EE = E^2
40391 var ee = e.redSqr();
40392 // T = 16*YYYY
40393 var t = yyyy.redIAdd(yyyy);
40394 t = t.redIAdd(t);
40395 t = t.redIAdd(t);
40396 t = t.redIAdd(t);
40397 // U = (M + E)^2 - MM - EE - T
40398 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
40399 // X3 = 4 * (X1 * EE - 4 * YY * U)
40400 var yyu4 = yy.redMul(u);
40401 yyu4 = yyu4.redIAdd(yyu4);
40402 yyu4 = yyu4.redIAdd(yyu4);
40403 var nx = this.x.redMul(ee).redISub(yyu4);
40404 nx = nx.redIAdd(nx);
40405 nx = nx.redIAdd(nx);
40406 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
40407 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
40408 ny = ny.redIAdd(ny);
40409 ny = ny.redIAdd(ny);
40410 ny = ny.redIAdd(ny);
40411 // Z3 = (Z1 + E)^2 - ZZ - EE
40412 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
40413
40414 return this.curve.jpoint(nx, ny, nz);
40415 };
40416
40417 JPoint.prototype.mul = function mul(k, kbase) {
40418 k = new bn(k, kbase);
40419
40420 return this.curve._wnafMul(this, k);
40421 };
40422
40423 JPoint.prototype.eq = function eq(p) {
40424 if (p.type === 'affine')
40425 return this.eq(p.toJ());
40426
40427 if (this === p)
40428 return true;
40429
40430 // x1 * z2^2 == x2 * z1^2
40431 var z2 = this.z.redSqr();
40432 var pz2 = p.z.redSqr();
40433 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
40434 return false;
40435
40436 // y1 * z2^3 == y2 * z1^3
40437 var z3 = z2.redMul(this.z);
40438 var pz3 = pz2.redMul(p.z);
40439 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
40440 };
40441
40442 JPoint.prototype.eqXToP = function eqXToP(x) {
40443 var zs = this.z.redSqr();
40444 var rx = x.toRed(this.curve.red).redMul(zs);
40445 if (this.x.cmp(rx) === 0)
40446 return true;
40447
40448 var xc = x.clone();
40449 var t = this.curve.redN.redMul(zs);
40450 for (;;) {
40451 xc.iadd(this.curve.n);
40452 if (xc.cmp(this.curve.p) >= 0)
40453 return false;
40454
40455 rx.redIAdd(t);
40456 if (this.x.cmp(rx) === 0)
40457 return true;
40458 }
40459 };
40460
40461 JPoint.prototype.inspect = function inspect() {
40462 if (this.isInfinity())
40463 return '<EC JPoint Infinity>';
40464 return '<EC JPoint x: ' + this.x.toString(16, 2) +
40465 ' y: ' + this.y.toString(16, 2) +
40466 ' z: ' + this.z.toString(16, 2) + '>';
40467 };
40468
40469 JPoint.prototype.isInfinity = function isInfinity() {
40470 // XXX This code assumes that zero is always zero in red
40471 return this.z.cmpn(0) === 0;
40472 };
40473
40474 function MontCurve(conf) {
40475 base.call(this, 'mont', conf);
40476
40477 this.a = new bn(conf.a, 16).toRed(this.red);
40478 this.b = new bn(conf.b, 16).toRed(this.red);
40479 this.i4 = new bn(4).toRed(this.red).redInvm();
40480 this.two = new bn(2).toRed(this.red);
40481 // Note: this implementation is according to the original paper
40482 // by P. Montgomery, NOT the one by D. J. Bernstein.
40483 this.a24 = this.i4.redMul(this.a.redAdd(this.two));
40484 }
40485 inherits_browser(MontCurve, base);
40486 var mont = MontCurve;
40487
40488 MontCurve.prototype.validate = function validate(point) {
40489 var x = point.normalize().x;
40490 var x2 = x.redSqr();
40491 var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
40492 var y = rhs.redSqrt();
40493
40494 return y.redSqr().cmp(rhs) === 0;
40495 };
40496
40497 function Point$1(curve, x, z) {
40498 base.BasePoint.call(this, curve, 'projective');
40499 if (x === null && z === null) {
40500 this.x = this.curve.one;
40501 this.z = this.curve.zero;
40502 } else {
40503 this.x = new bn(x, 16);
40504 this.z = new bn(z, 16);
40505 if (!this.x.red)
40506 this.x = this.x.toRed(this.curve.red);
40507 if (!this.z.red)
40508 this.z = this.z.toRed(this.curve.red);
40509 }
40510 }
40511 inherits_browser(Point$1, base.BasePoint);
40512
40513 MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
40514 var bytes = utils_1$1.toArray(bytes, enc);
40515
40516 // TODO Curve448
40517 // Montgomery curve points must be represented in the compressed format
40518 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
40519 if (bytes.length === 33 && bytes[0] === 0x40)
40520 bytes = bytes.slice(1, 33).reverse(); // point must be little-endian
40521 if (bytes.length !== 32)
40522 throw new Error('Unknown point compression format');
40523 return this.point(bytes, 1);
40524 };
40525
40526 MontCurve.prototype.point = function point(x, z) {
40527 return new Point$1(this, x, z);
40528 };
40529
40530 MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
40531 return Point$1.fromJSON(this, obj);
40532 };
40533
40534 Point$1.prototype.precompute = function precompute() {
40535 // No-op
40536 };
40537
40538 Point$1.prototype._encode = function _encode(compact) {
40539 var len = this.curve.p.byteLength();
40540
40541 // Note: the output should always be little-endian
40542 // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
40543 if (compact) {
40544 return [ 0x40 ].concat(this.getX().toArray('le', len));
40545 } else {
40546 return this.getX().toArray('be', len);
40547 }
40548 };
40549
40550 Point$1.fromJSON = function fromJSON(curve, obj) {
40551 return new Point$1(curve, obj[0], obj[1] || curve.one);
40552 };
40553
40554 Point$1.prototype.inspect = function inspect() {
40555 if (this.isInfinity())
40556 return '<EC Point Infinity>';
40557 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
40558 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
40559 };
40560
40561 Point$1.prototype.isInfinity = function isInfinity() {
40562 // XXX This code assumes that zero is always zero in red
40563 return this.z.cmpn(0) === 0;
40564 };
40565
40566 Point$1.prototype.dbl = function dbl() {
40567 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
40568 // 2M + 2S + 4A
40569
40570 // A = X1 + Z1
40571 var a = this.x.redAdd(this.z);
40572 // AA = A^2
40573 var aa = a.redSqr();
40574 // B = X1 - Z1
40575 var b = this.x.redSub(this.z);
40576 // BB = B^2
40577 var bb = b.redSqr();
40578 // C = AA - BB
40579 var c = aa.redSub(bb);
40580 // X3 = AA * BB
40581 var nx = aa.redMul(bb);
40582 // Z3 = C * (BB + A24 * C)
40583 var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
40584 return this.curve.point(nx, nz);
40585 };
40586
40587 Point$1.prototype.add = function add() {
40588 throw new Error('Not supported on Montgomery curve');
40589 };
40590
40591 Point$1.prototype.diffAdd = function diffAdd(p, diff) {
40592 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
40593 // 4M + 2S + 6A
40594
40595 // A = X2 + Z2
40596 var a = this.x.redAdd(this.z);
40597 // B = X2 - Z2
40598 var b = this.x.redSub(this.z);
40599 // C = X3 + Z3
40600 var c = p.x.redAdd(p.z);
40601 // D = X3 - Z3
40602 var d = p.x.redSub(p.z);
40603 // DA = D * A
40604 var da = d.redMul(a);
40605 // CB = C * B
40606 var cb = c.redMul(b);
40607 // X5 = Z1 * (DA + CB)^2
40608 var nx = diff.z.redMul(da.redAdd(cb).redSqr());
40609 // Z5 = X1 * (DA - CB)^2
40610 var nz = diff.x.redMul(da.redISub(cb).redSqr());
40611 return this.curve.point(nx, nz);
40612 };
40613
40614 Point$1.prototype.mul = function mul(k) {
40615 k = new bn(k, 16);
40616
40617 var t = k.clone();
40618 var a = this; // (N / 2) * Q + Q
40619 var b = this.curve.point(null, null); // (N / 2) * Q
40620 var c = this; // Q
40621
40622 for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
40623 bits.push(t.andln(1));
40624
40625 for (var i = bits.length - 1; i >= 0; i--) {
40626 if (bits[i] === 0) {
40627 // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
40628 a = a.diffAdd(b, c);
40629 // N * Q = 2 * ((N / 2) * Q + Q))
40630 b = b.dbl();
40631 } else {
40632 // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
40633 b = a.diffAdd(b, c);
40634 // N * Q + Q = 2 * ((N / 2) * Q + Q)
40635 a = a.dbl();
40636 }
40637 }
40638 return b;
40639 };
40640
40641 Point$1.prototype.mulAdd = function mulAdd() {
40642 throw new Error('Not supported on Montgomery curve');
40643 };
40644
40645 Point$1.prototype.jumlAdd = function jumlAdd() {
40646 throw new Error('Not supported on Montgomery curve');
40647 };
40648
40649 Point$1.prototype.eq = function eq(other) {
40650 return this.getX().cmp(other.getX()) === 0;
40651 };
40652
40653 Point$1.prototype.normalize = function normalize() {
40654 this.x = this.x.redMul(this.z.redInvm());
40655 this.z = this.curve.one;
40656 return this;
40657 };
40658
40659 Point$1.prototype.getX = function getX() {
40660 // Normalize coordinates
40661 this.normalize();
40662
40663 return this.x.fromRed();
40664 };
40665
40666 var assert$4 = utils_1$1.assert;
40667
40668 function EdwardsCurve(conf) {
40669 // NOTE: Important as we are creating point in Base.call()
40670 this.twisted = (conf.a | 0) !== 1;
40671 this.mOneA = this.twisted && (conf.a | 0) === -1;
40672 this.extended = this.mOneA;
40673
40674 base.call(this, 'edwards', conf);
40675
40676 this.a = new bn(conf.a, 16).umod(this.red.m);
40677 this.a = this.a.toRed(this.red);
40678 this.c = new bn(conf.c, 16).toRed(this.red);
40679 this.c2 = this.c.redSqr();
40680 this.d = new bn(conf.d, 16).toRed(this.red);
40681 this.dd = this.d.redAdd(this.d);
40682
40683 assert$4(!this.twisted || this.c.fromRed().cmpn(1) === 0);
40684 this.oneC = (conf.c | 0) === 1;
40685 }
40686 inherits_browser(EdwardsCurve, base);
40687 var edwards = EdwardsCurve;
40688
40689 EdwardsCurve.prototype._mulA = function _mulA(num) {
40690 if (this.mOneA)
40691 return num.redNeg();
40692 else
40693 return this.a.redMul(num);
40694 };
40695
40696 EdwardsCurve.prototype._mulC = function _mulC(num) {
40697 if (this.oneC)
40698 return num;
40699 else
40700 return this.c.redMul(num);
40701 };
40702
40703 // Just for compatibility with Short curve
40704 EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
40705 return this.point(x, y, z, t);
40706 };
40707
40708 EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
40709 x = new bn(x, 16);
40710 if (!x.red)
40711 x = x.toRed(this.red);
40712
40713 var x2 = x.redSqr();
40714 var rhs = this.c2.redSub(this.a.redMul(x2));
40715 var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
40716
40717 var y2 = rhs.redMul(lhs.redInvm());
40718 var y = y2.redSqrt();
40719 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
40720 throw new Error('invalid point');
40721
40722 var isOdd = y.fromRed().isOdd();
40723 if (odd && !isOdd || !odd && isOdd)
40724 y = y.redNeg();
40725
40726 return this.point(x, y);
40727 };
40728
40729 EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
40730 y = new bn(y, 16);
40731 if (!y.red)
40732 y = y.toRed(this.red);
40733
40734 // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
40735 var y2 = y.redSqr();
40736 var lhs = y2.redSub(this.c2);
40737 var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
40738 var x2 = lhs.redMul(rhs.redInvm());
40739
40740 if (x2.cmp(this.zero) === 0) {
40741 if (odd)
40742 throw new Error('invalid point');
40743 else
40744 return this.point(this.zero, y);
40745 }
40746
40747 var x = x2.redSqrt();
40748 if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
40749 throw new Error('invalid point');
40750
40751 if (x.fromRed().isOdd() !== odd)
40752 x = x.redNeg();
40753
40754 return this.point(x, y);
40755 };
40756
40757 EdwardsCurve.prototype.validate = function validate(point) {
40758 if (point.isInfinity())
40759 return true;
40760
40761 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
40762 point.normalize();
40763
40764 var x2 = point.x.redSqr();
40765 var y2 = point.y.redSqr();
40766 var lhs = x2.redMul(this.a).redAdd(y2);
40767 var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
40768
40769 return lhs.cmp(rhs) === 0;
40770 };
40771
40772 function Point$2(curve, x, y, z, t) {
40773 base.BasePoint.call(this, curve, 'projective');
40774 if (x === null && y === null && z === null) {
40775 this.x = this.curve.zero;
40776 this.y = this.curve.one;
40777 this.z = this.curve.one;
40778 this.t = this.curve.zero;
40779 this.zOne = true;
40780 } else {
40781 this.x = new bn(x, 16);
40782 this.y = new bn(y, 16);
40783 this.z = z ? new bn(z, 16) : this.curve.one;
40784 this.t = t && new bn(t, 16);
40785 if (!this.x.red)
40786 this.x = this.x.toRed(this.curve.red);
40787 if (!this.y.red)
40788 this.y = this.y.toRed(this.curve.red);
40789 if (!this.z.red)
40790 this.z = this.z.toRed(this.curve.red);
40791 if (this.t && !this.t.red)
40792 this.t = this.t.toRed(this.curve.red);
40793 this.zOne = this.z === this.curve.one;
40794
40795 // Use extended coordinates
40796 if (this.curve.extended && !this.t) {
40797 this.t = this.x.redMul(this.y);
40798 if (!this.zOne)
40799 this.t = this.t.redMul(this.z.redInvm());
40800 }
40801 }
40802 }
40803 inherits_browser(Point$2, base.BasePoint);
40804
40805 EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
40806 return Point$2.fromJSON(this, obj);
40807 };
40808
40809 EdwardsCurve.prototype.point = function point(x, y, z, t) {
40810 return new Point$2(this, x, y, z, t);
40811 };
40812
40813 Point$2.fromJSON = function fromJSON(curve, obj) {
40814 return new Point$2(curve, obj[0], obj[1], obj[2]);
40815 };
40816
40817 Point$2.prototype.inspect = function inspect() {
40818 if (this.isInfinity())
40819 return '<EC Point Infinity>';
40820 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
40821 ' y: ' + this.y.fromRed().toString(16, 2) +
40822 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
40823 };
40824
40825 Point$2.prototype.isInfinity = function isInfinity() {
40826 // XXX This code assumes that zero is always zero in red
40827 return this.x.cmpn(0) === 0 &&
40828 (this.y.cmp(this.z) === 0 ||
40829 (this.zOne && this.y.cmp(this.curve.c) === 0));
40830 };
40831
40832 Point$2.prototype._extDbl = function _extDbl() {
40833 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
40834 // #doubling-dbl-2008-hwcd
40835 // 4M + 4S
40836
40837 // A = X1^2
40838 var a = this.x.redSqr();
40839 // B = Y1^2
40840 var b = this.y.redSqr();
40841 // C = 2 * Z1^2
40842 var c = this.z.redSqr();
40843 c = c.redIAdd(c);
40844 // D = a * A
40845 var d = this.curve._mulA(a);
40846 // E = (X1 + Y1)^2 - A - B
40847 var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
40848 // G = D + B
40849 var g = d.redAdd(b);
40850 // F = G - C
40851 var f = g.redSub(c);
40852 // H = D - B
40853 var h = d.redSub(b);
40854 // X3 = E * F
40855 var nx = e.redMul(f);
40856 // Y3 = G * H
40857 var ny = g.redMul(h);
40858 // T3 = E * H
40859 var nt = e.redMul(h);
40860 // Z3 = F * G
40861 var nz = f.redMul(g);
40862 return this.curve.point(nx, ny, nz, nt);
40863 };
40864
40865 Point$2.prototype._projDbl = function _projDbl() {
40866 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
40867 // #doubling-dbl-2008-bbjlp
40868 // #doubling-dbl-2007-bl
40869 // and others
40870 // Generally 3M + 4S or 2M + 4S
40871
40872 // B = (X1 + Y1)^2
40873 var b = this.x.redAdd(this.y).redSqr();
40874 // C = X1^2
40875 var c = this.x.redSqr();
40876 // D = Y1^2
40877 var d = this.y.redSqr();
40878
40879 var nx;
40880 var ny;
40881 var nz;
40882 if (this.curve.twisted) {
40883 // E = a * C
40884 var e = this.curve._mulA(c);
40885 // F = E + D
40886 var f = e.redAdd(d);
40887 if (this.zOne) {
40888 // X3 = (B - C - D) * (F - 2)
40889 nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
40890 // Y3 = F * (E - D)
40891 ny = f.redMul(e.redSub(d));
40892 // Z3 = F^2 - 2 * F
40893 nz = f.redSqr().redSub(f).redSub(f);
40894 } else {
40895 // H = Z1^2
40896 var h = this.z.redSqr();
40897 // J = F - 2 * H
40898 var j = f.redSub(h).redISub(h);
40899 // X3 = (B-C-D)*J
40900 nx = b.redSub(c).redISub(d).redMul(j);
40901 // Y3 = F * (E - D)
40902 ny = f.redMul(e.redSub(d));
40903 // Z3 = F * J
40904 nz = f.redMul(j);
40905 }
40906 } else {
40907 // E = C + D
40908 var e = c.redAdd(d);
40909 // H = (c * Z1)^2
40910 var h = this.curve._mulC(this.z).redSqr();
40911 // J = E - 2 * H
40912 var j = e.redSub(h).redSub(h);
40913 // X3 = c * (B - E) * J
40914 nx = this.curve._mulC(b.redISub(e)).redMul(j);
40915 // Y3 = c * E * (C - D)
40916 ny = this.curve._mulC(e).redMul(c.redISub(d));
40917 // Z3 = E * J
40918 nz = e.redMul(j);
40919 }
40920 return this.curve.point(nx, ny, nz);
40921 };
40922
40923 Point$2.prototype.dbl = function dbl() {
40924 if (this.isInfinity())
40925 return this;
40926
40927 // Double in extended coordinates
40928 if (this.curve.extended)
40929 return this._extDbl();
40930 else
40931 return this._projDbl();
40932 };
40933
40934 Point$2.prototype._extAdd = function _extAdd(p) {
40935 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
40936 // #addition-add-2008-hwcd-3
40937 // 8M
40938
40939 // A = (Y1 - X1) * (Y2 - X2)
40940 var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
40941 // B = (Y1 + X1) * (Y2 + X2)
40942 var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
40943 // C = T1 * k * T2
40944 var c = this.t.redMul(this.curve.dd).redMul(p.t);
40945 // D = Z1 * 2 * Z2
40946 var d = this.z.redMul(p.z.redAdd(p.z));
40947 // E = B - A
40948 var e = b.redSub(a);
40949 // F = D - C
40950 var f = d.redSub(c);
40951 // G = D + C
40952 var g = d.redAdd(c);
40953 // H = B + A
40954 var h = b.redAdd(a);
40955 // X3 = E * F
40956 var nx = e.redMul(f);
40957 // Y3 = G * H
40958 var ny = g.redMul(h);
40959 // T3 = E * H
40960 var nt = e.redMul(h);
40961 // Z3 = F * G
40962 var nz = f.redMul(g);
40963 return this.curve.point(nx, ny, nz, nt);
40964 };
40965
40966 Point$2.prototype._projAdd = function _projAdd(p) {
40967 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
40968 // #addition-add-2008-bbjlp
40969 // #addition-add-2007-bl
40970 // 10M + 1S
40971
40972 // A = Z1 * Z2
40973 var a = this.z.redMul(p.z);
40974 // B = A^2
40975 var b = a.redSqr();
40976 // C = X1 * X2
40977 var c = this.x.redMul(p.x);
40978 // D = Y1 * Y2
40979 var d = this.y.redMul(p.y);
40980 // E = d * C * D
40981 var e = this.curve.d.redMul(c).redMul(d);
40982 // F = B - E
40983 var f = b.redSub(e);
40984 // G = B + E
40985 var g = b.redAdd(e);
40986 // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
40987 var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
40988 var nx = a.redMul(f).redMul(tmp);
40989 var ny;
40990 var nz;
40991 if (this.curve.twisted) {
40992 // Y3 = A * G * (D - a * C)
40993 ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
40994 // Z3 = F * G
40995 nz = f.redMul(g);
40996 } else {
40997 // Y3 = A * G * (D - C)
40998 ny = a.redMul(g).redMul(d.redSub(c));
40999 // Z3 = c * F * G
41000 nz = this.curve._mulC(f).redMul(g);
41001 }
41002 return this.curve.point(nx, ny, nz);
41003 };
41004
41005 Point$2.prototype.add = function add(p) {
41006 if (this.isInfinity())
41007 return p;
41008 if (p.isInfinity())
41009 return this;
41010
41011 if (this.curve.extended)
41012 return this._extAdd(p);
41013 else
41014 return this._projAdd(p);
41015 };
41016
41017 Point$2.prototype.mul = function mul(k) {
41018 if (this._hasDoubles(k))
41019 return this.curve._fixedNafMul(this, k);
41020 else
41021 return this.curve._wnafMul(this, k);
41022 };
41023
41024 Point$2.prototype.mulAdd = function mulAdd(k1, p, k2) {
41025 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
41026 };
41027
41028 Point$2.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
41029 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
41030 };
41031
41032 Point$2.prototype.normalize = function normalize() {
41033 if (this.zOne)
41034 return this;
41035
41036 // Normalize coordinates
41037 var zi = this.z.redInvm();
41038 this.x = this.x.redMul(zi);
41039 this.y = this.y.redMul(zi);
41040 if (this.t)
41041 this.t = this.t.redMul(zi);
41042 this.z = this.curve.one;
41043 this.zOne = true;
41044 return this;
41045 };
41046
41047 Point$2.prototype.neg = function neg() {
41048 return this.curve.point(this.x.redNeg(),
41049 this.y,
41050 this.z,
41051 this.t && this.t.redNeg());
41052 };
41053
41054 Point$2.prototype.getX = function getX() {
41055 this.normalize();
41056 return this.x.fromRed();
41057 };
41058
41059 Point$2.prototype.getY = function getY() {
41060 this.normalize();
41061 return this.y.fromRed();
41062 };
41063
41064 Point$2.prototype.eq = function eq(other) {
41065 return this === other ||
41066 this.getX().cmp(other.getX()) === 0 &&
41067 this.getY().cmp(other.getY()) === 0;
41068 };
41069
41070 Point$2.prototype.eqXToP = function eqXToP(x) {
41071 var rx = x.toRed(this.curve.red).redMul(this.z);
41072 if (this.x.cmp(rx) === 0)
41073 return true;
41074
41075 var xc = x.clone();
41076 var t = this.curve.redN.redMul(this.z);
41077 for (;;) {
41078 xc.iadd(this.curve.n);
41079 if (xc.cmp(this.curve.p) >= 0)
41080 return false;
41081
41082 rx.redIAdd(t);
41083 if (this.x.cmp(rx) === 0)
41084 return true;
41085 }
41086 };
41087
41088 // Compatibility with BaseCurve
41089 Point$2.prototype.toP = Point$2.prototype.normalize;
41090 Point$2.prototype.mixedAdd = Point$2.prototype.add;
41091
41092 var curve_1 = createCommonjsModule(function (module, exports) {
41093
41094 var curve = exports;
41095
41096 curve.base = base;
41097 curve.short = short_1;
41098 curve.mont = mont;
41099 curve.edwards = edwards;
41100 });
41101
41102 var rotl32$2 = utils.rotl32;
41103 var sum32$3 = utils.sum32;
41104 var sum32_5$2 = utils.sum32_5;
41105 var ft_1$1 = common$1.ft_1;
41106 var BlockHash$4 = common.BlockHash;
41107
41108 var sha1_K = [
41109 0x5A827999, 0x6ED9EBA1,
41110 0x8F1BBCDC, 0xCA62C1D6
41111 ];
41112
41113 function SHA1() {
41114 if (!(this instanceof SHA1))
41115 return new SHA1();
41116
41117 BlockHash$4.call(this);
41118 this.h = [
41119 0x67452301, 0xefcdab89, 0x98badcfe,
41120 0x10325476, 0xc3d2e1f0 ];
41121 this.W = new Array(80);
41122 }
41123
41124 utils.inherits(SHA1, BlockHash$4);
41125 var _1 = SHA1;
41126
41127 SHA1.blockSize = 512;
41128 SHA1.outSize = 160;
41129 SHA1.hmacStrength = 80;
41130 SHA1.padLength = 64;
41131
41132 SHA1.prototype._update = function _update(msg, start) {
41133 var W = this.W;
41134
41135 for (var i = 0; i < 16; i++)
41136 W[i] = msg[start + i];
41137
41138 for(; i < W.length; i++)
41139 W[i] = rotl32$2(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
41140
41141 var a = this.h[0];
41142 var b = this.h[1];
41143 var c = this.h[2];
41144 var d = this.h[3];
41145 var e = this.h[4];
41146
41147 for (i = 0; i < W.length; i++) {
41148 var s = ~~(i / 20);
41149 var t = sum32_5$2(rotl32$2(a, 5), ft_1$1(s, b, c, d), e, W[i], sha1_K[s]);
41150 e = d;
41151 d = c;
41152 c = rotl32$2(b, 30);
41153 b = a;
41154 a = t;
41155 }
41156
41157 this.h[0] = sum32$3(this.h[0], a);
41158 this.h[1] = sum32$3(this.h[1], b);
41159 this.h[2] = sum32$3(this.h[2], c);
41160 this.h[3] = sum32$3(this.h[3], d);
41161 this.h[4] = sum32$3(this.h[4], e);
41162 };
41163
41164 SHA1.prototype._digest = function digest(enc) {
41165 if (enc === 'hex')
41166 return utils.toHex32(this.h, 'big');
41167 else
41168 return utils.split32(this.h, 'big');
41169 };
41170
41171 var sha1 = _1;
41172 var sha224 = _224;
41173 var sha256 = _256;
41174 var sha384 = _384;
41175 var sha512 = _512;
41176
41177 var sha = {
41178 sha1: sha1,
41179 sha224: sha224,
41180 sha256: sha256,
41181 sha384: sha384,
41182 sha512: sha512
41183 };
41184
41185 function Hmac(hash, key, enc) {
41186 if (!(this instanceof Hmac))
41187 return new Hmac(hash, key, enc);
41188 this.Hash = hash;
41189 this.blockSize = hash.blockSize / 8;
41190 this.outSize = hash.outSize / 8;
41191 this.inner = null;
41192 this.outer = null;
41193
41194 this._init(utils.toArray(key, enc));
41195 }
41196 var hmac = Hmac;
41197
41198 Hmac.prototype._init = function init(key) {
41199 // Shorten key, if needed
41200 if (key.length > this.blockSize)
41201 key = new this.Hash().update(key).digest();
41202 minimalisticAssert(key.length <= this.blockSize);
41203
41204 // Add padding to key
41205 for (var i = key.length; i < this.blockSize; i++)
41206 key.push(0);
41207
41208 for (i = 0; i < key.length; i++)
41209 key[i] ^= 0x36;
41210 this.inner = new this.Hash().update(key);
41211
41212 // 0x36 ^ 0x5c = 0x6a
41213 for (i = 0; i < key.length; i++)
41214 key[i] ^= 0x6a;
41215 this.outer = new this.Hash().update(key);
41216 };
41217
41218 Hmac.prototype.update = function update(msg, enc) {
41219 this.inner.update(msg, enc);
41220 return this;
41221 };
41222
41223 Hmac.prototype.digest = function digest(enc) {
41224 this.outer.update(this.inner.digest());
41225 return this.outer.digest(enc);
41226 };
41227
41228 var hash_1 = createCommonjsModule(function (module, exports) {
41229 var hash = exports;
41230
41231 hash.utils = utils;
41232 hash.common = common;
41233 hash.sha = sha;
41234 hash.ripemd = ripemd;
41235 hash.hmac = hmac;
41236
41237 // Proxy hash functions to the main object
41238 hash.sha1 = hash.sha.sha1;
41239 hash.sha256 = hash.sha.sha256;
41240 hash.sha224 = hash.sha.sha224;
41241 hash.sha384 = hash.sha.sha384;
41242 hash.sha512 = hash.sha.sha512;
41243 hash.ripemd160 = hash.ripemd.ripemd160;
41244 });
41245
41246 var secp256k1 = {
41247 doubles: {
41248 step: 4,
41249 points: [
41250 [
41251 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
41252 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
41253 ],
41254 [
41255 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
41256 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
41257 ],
41258 [
41259 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
41260 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
41261 ],
41262 [
41263 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
41264 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
41265 ],
41266 [
41267 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
41268 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
41269 ],
41270 [
41271 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
41272 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
41273 ],
41274 [
41275 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
41276 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
41277 ],
41278 [
41279 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
41280 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
41281 ],
41282 [
41283 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
41284 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
41285 ],
41286 [
41287 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
41288 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
41289 ],
41290 [
41291 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
41292 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
41293 ],
41294 [
41295 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
41296 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
41297 ],
41298 [
41299 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
41300 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
41301 ],
41302 [
41303 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
41304 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
41305 ],
41306 [
41307 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
41308 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
41309 ],
41310 [
41311 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
41312 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
41313 ],
41314 [
41315 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
41316 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
41317 ],
41318 [
41319 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
41320 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
41321 ],
41322 [
41323 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
41324 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
41325 ],
41326 [
41327 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
41328 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
41329 ],
41330 [
41331 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
41332 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
41333 ],
41334 [
41335 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
41336 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
41337 ],
41338 [
41339 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
41340 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
41341 ],
41342 [
41343 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
41344 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
41345 ],
41346 [
41347 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
41348 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
41349 ],
41350 [
41351 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
41352 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
41353 ],
41354 [
41355 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
41356 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
41357 ],
41358 [
41359 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
41360 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
41361 ],
41362 [
41363 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
41364 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
41365 ],
41366 [
41367 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
41368 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
41369 ],
41370 [
41371 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
41372 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
41373 ],
41374 [
41375 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
41376 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
41377 ],
41378 [
41379 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
41380 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
41381 ],
41382 [
41383 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
41384 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
41385 ],
41386 [
41387 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
41388 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
41389 ],
41390 [
41391 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
41392 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
41393 ],
41394 [
41395 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
41396 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
41397 ],
41398 [
41399 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
41400 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
41401 ],
41402 [
41403 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
41404 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
41405 ],
41406 [
41407 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
41408 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
41409 ],
41410 [
41411 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
41412 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
41413 ],
41414 [
41415 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
41416 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
41417 ],
41418 [
41419 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
41420 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
41421 ],
41422 [
41423 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
41424 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
41425 ],
41426 [
41427 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
41428 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
41429 ],
41430 [
41431 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
41432 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
41433 ],
41434 [
41435 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
41436 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
41437 ],
41438 [
41439 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
41440 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
41441 ],
41442 [
41443 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
41444 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
41445 ],
41446 [
41447 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
41448 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
41449 ],
41450 [
41451 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
41452 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
41453 ],
41454 [
41455 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
41456 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
41457 ],
41458 [
41459 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
41460 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
41461 ],
41462 [
41463 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
41464 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
41465 ],
41466 [
41467 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
41468 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
41469 ],
41470 [
41471 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
41472 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
41473 ],
41474 [
41475 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
41476 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
41477 ],
41478 [
41479 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
41480 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
41481 ],
41482 [
41483 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
41484 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
41485 ],
41486 [
41487 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
41488 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
41489 ],
41490 [
41491 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
41492 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
41493 ],
41494 [
41495 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
41496 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
41497 ],
41498 [
41499 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
41500 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
41501 ],
41502 [
41503 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
41504 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
41505 ],
41506 [
41507 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
41508 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
41509 ]
41510 ]
41511 },
41512 naf: {
41513 wnd: 7,
41514 points: [
41515 [
41516 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
41517 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
41518 ],
41519 [
41520 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
41521 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
41522 ],
41523 [
41524 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
41525 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
41526 ],
41527 [
41528 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
41529 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
41530 ],
41531 [
41532 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
41533 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
41534 ],
41535 [
41536 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
41537 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
41538 ],
41539 [
41540 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
41541 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
41542 ],
41543 [
41544 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
41545 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
41546 ],
41547 [
41548 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
41549 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
41550 ],
41551 [
41552 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
41553 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
41554 ],
41555 [
41556 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
41557 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
41558 ],
41559 [
41560 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
41561 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
41562 ],
41563 [
41564 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
41565 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
41566 ],
41567 [
41568 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
41569 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
41570 ],
41571 [
41572 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
41573 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
41574 ],
41575 [
41576 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
41577 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
41578 ],
41579 [
41580 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
41581 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
41582 ],
41583 [
41584 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
41585 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
41586 ],
41587 [
41588 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
41589 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
41590 ],
41591 [
41592 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
41593 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
41594 ],
41595 [
41596 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
41597 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
41598 ],
41599 [
41600 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
41601 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
41602 ],
41603 [
41604 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
41605 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
41606 ],
41607 [
41608 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
41609 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
41610 ],
41611 [
41612 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
41613 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
41614 ],
41615 [
41616 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
41617 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
41618 ],
41619 [
41620 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
41621 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
41622 ],
41623 [
41624 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
41625 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
41626 ],
41627 [
41628 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
41629 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
41630 ],
41631 [
41632 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
41633 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
41634 ],
41635 [
41636 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
41637 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
41638 ],
41639 [
41640 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
41641 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
41642 ],
41643 [
41644 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
41645 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
41646 ],
41647 [
41648 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
41649 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
41650 ],
41651 [
41652 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
41653 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
41654 ],
41655 [
41656 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
41657 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
41658 ],
41659 [
41660 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
41661 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
41662 ],
41663 [
41664 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
41665 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
41666 ],
41667 [
41668 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
41669 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
41670 ],
41671 [
41672 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
41673 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
41674 ],
41675 [
41676 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
41677 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
41678 ],
41679 [
41680 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
41681 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
41682 ],
41683 [
41684 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
41685 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
41686 ],
41687 [
41688 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
41689 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
41690 ],
41691 [
41692 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
41693 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
41694 ],
41695 [
41696 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
41697 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
41698 ],
41699 [
41700 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
41701 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
41702 ],
41703 [
41704 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
41705 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
41706 ],
41707 [
41708 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
41709 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
41710 ],
41711 [
41712 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
41713 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
41714 ],
41715 [
41716 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
41717 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
41718 ],
41719 [
41720 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
41721 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
41722 ],
41723 [
41724 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
41725 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
41726 ],
41727 [
41728 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
41729 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
41730 ],
41731 [
41732 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
41733 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
41734 ],
41735 [
41736 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
41737 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
41738 ],
41739 [
41740 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
41741 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
41742 ],
41743 [
41744 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
41745 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
41746 ],
41747 [
41748 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
41749 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
41750 ],
41751 [
41752 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
41753 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
41754 ],
41755 [
41756 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
41757 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
41758 ],
41759 [
41760 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
41761 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
41762 ],
41763 [
41764 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
41765 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
41766 ],
41767 [
41768 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
41769 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
41770 ],
41771 [
41772 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
41773 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
41774 ],
41775 [
41776 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
41777 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
41778 ],
41779 [
41780 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
41781 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
41782 ],
41783 [
41784 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
41785 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
41786 ],
41787 [
41788 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
41789 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
41790 ],
41791 [
41792 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
41793 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
41794 ],
41795 [
41796 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
41797 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
41798 ],
41799 [
41800 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
41801 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
41802 ],
41803 [
41804 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
41805 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
41806 ],
41807 [
41808 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
41809 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
41810 ],
41811 [
41812 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
41813 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
41814 ],
41815 [
41816 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
41817 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
41818 ],
41819 [
41820 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
41821 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
41822 ],
41823 [
41824 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
41825 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
41826 ],
41827 [
41828 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
41829 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
41830 ],
41831 [
41832 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
41833 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
41834 ],
41835 [
41836 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
41837 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
41838 ],
41839 [
41840 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
41841 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
41842 ],
41843 [
41844 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
41845 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
41846 ],
41847 [
41848 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
41849 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
41850 ],
41851 [
41852 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
41853 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
41854 ],
41855 [
41856 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
41857 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
41858 ],
41859 [
41860 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
41861 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
41862 ],
41863 [
41864 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
41865 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
41866 ],
41867 [
41868 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
41869 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
41870 ],
41871 [
41872 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
41873 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
41874 ],
41875 [
41876 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
41877 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
41878 ],
41879 [
41880 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
41881 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
41882 ],
41883 [
41884 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
41885 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
41886 ],
41887 [
41888 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
41889 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
41890 ],
41891 [
41892 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
41893 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
41894 ],
41895 [
41896 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
41897 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
41898 ],
41899 [
41900 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
41901 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
41902 ],
41903 [
41904 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
41905 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
41906 ],
41907 [
41908 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
41909 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
41910 ],
41911 [
41912 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
41913 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
41914 ],
41915 [
41916 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
41917 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
41918 ],
41919 [
41920 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
41921 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
41922 ],
41923 [
41924 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
41925 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
41926 ],
41927 [
41928 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
41929 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
41930 ],
41931 [
41932 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
41933 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
41934 ],
41935 [
41936 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
41937 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
41938 ],
41939 [
41940 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
41941 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
41942 ],
41943 [
41944 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
41945 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
41946 ],
41947 [
41948 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
41949 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
41950 ],
41951 [
41952 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
41953 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
41954 ],
41955 [
41956 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
41957 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
41958 ],
41959 [
41960 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
41961 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
41962 ],
41963 [
41964 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
41965 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
41966 ],
41967 [
41968 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
41969 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
41970 ],
41971 [
41972 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
41973 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
41974 ],
41975 [
41976 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
41977 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
41978 ],
41979 [
41980 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
41981 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
41982 ],
41983 [
41984 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
41985 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
41986 ],
41987 [
41988 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
41989 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
41990 ],
41991 [
41992 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
41993 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
41994 ],
41995 [
41996 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
41997 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
41998 ],
41999 [
42000 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
42001 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
42002 ],
42003 [
42004 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
42005 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
42006 ],
42007 [
42008 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
42009 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
42010 ],
42011 [
42012 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
42013 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
42014 ],
42015 [
42016 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
42017 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
42018 ],
42019 [
42020 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
42021 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
42022 ]
42023 ]
42024 }
42025 };
42026
42027 var curves_1 = createCommonjsModule(function (module, exports) {
42028
42029 var curves = exports;
42030
42031
42032
42033
42034
42035 var assert = utils_1$1.assert;
42036
42037 function PresetCurve(options) {
42038 if (options.type === 'short')
42039 this.curve = new curve_1.short(options);
42040 else if (options.type === 'edwards')
42041 this.curve = new curve_1.edwards(options);
42042 else if (options.type === 'mont')
42043 this.curve = new curve_1.mont(options);
42044 else throw new Error('Unknown curve type.');
42045 this.g = this.curve.g;
42046 this.n = this.curve.n;
42047 this.hash = options.hash;
42048
42049 assert(this.g.validate(), 'Invalid curve');
42050 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O');
42051 }
42052 curves.PresetCurve = PresetCurve;
42053
42054 function defineCurve(name, options) {
42055 Object.defineProperty(curves, name, {
42056 configurable: true,
42057 enumerable: true,
42058 get: function() {
42059 var curve = new PresetCurve(options);
42060 Object.defineProperty(curves, name, {
42061 configurable: true,
42062 enumerable: true,
42063 value: curve
42064 });
42065 return curve;
42066 }
42067 });
42068 }
42069
42070 defineCurve('p192', {
42071 type: 'short',
42072 prime: 'p192',
42073 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
42074 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
42075 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
42076 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
42077 hash: hash_1.sha256,
42078 gRed: false,
42079 g: [
42080 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
42081 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
42082 ]
42083 });
42084
42085 defineCurve('p224', {
42086 type: 'short',
42087 prime: 'p224',
42088 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
42089 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
42090 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
42091 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
42092 hash: hash_1.sha256,
42093 gRed: false,
42094 g: [
42095 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
42096 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
42097 ]
42098 });
42099
42100 defineCurve('p256', {
42101 type: 'short',
42102 prime: null,
42103 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
42104 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
42105 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
42106 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
42107 hash: hash_1.sha256,
42108 gRed: false,
42109 g: [
42110 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
42111 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
42112 ]
42113 });
42114
42115 defineCurve('p384', {
42116 type: 'short',
42117 prime: null,
42118 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42119 'fffffffe ffffffff 00000000 00000000 ffffffff',
42120 a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42121 'fffffffe ffffffff 00000000 00000000 fffffffc',
42122 b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
42123 '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
42124 n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
42125 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
42126 hash: hash_1.sha384,
42127 gRed: false,
42128 g: [
42129 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
42130 '5502f25d bf55296c 3a545e38 72760ab7',
42131 '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
42132 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
42133 ]
42134 });
42135
42136 defineCurve('p521', {
42137 type: 'short',
42138 prime: null,
42139 p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42140 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42141 'ffffffff ffffffff ffffffff ffffffff ffffffff',
42142 a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42143 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42144 'ffffffff ffffffff ffffffff ffffffff fffffffc',
42145 b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
42146 '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
42147 '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
42148 n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
42149 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
42150 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
42151 hash: hash_1.sha512,
42152 gRed: false,
42153 g: [
42154 '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
42155 '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
42156 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
42157 '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
42158 '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
42159 '3fad0761 353c7086 a272c240 88be9476 9fd16650'
42160 ]
42161 });
42162
42163 // https://tools.ietf.org/html/rfc7748#section-4.1
42164 defineCurve('curve25519', {
42165 type: 'mont',
42166 prime: 'p25519',
42167 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
42168 a: '76d06',
42169 b: '1',
42170 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
42171 cofactor: '8',
42172 hash: hash_1.sha256,
42173 gRed: false,
42174 g: [
42175 '9'
42176 ]
42177 });
42178
42179 defineCurve('ed25519', {
42180 type: 'edwards',
42181 prime: 'p25519',
42182 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
42183 a: '-1',
42184 c: '1',
42185 // -121665 * (121666^(-1)) (mod P)
42186 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
42187 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
42188 cofactor: '8',
42189 hash: hash_1.sha256,
42190 gRed: false,
42191 g: [
42192 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
42193 // 4/5
42194 '6666666666666666666666666666666666666666666666666666666666666658'
42195 ]
42196 });
42197
42198 // https://tools.ietf.org/html/rfc5639#section-3.4
42199 defineCurve('brainpoolP256r1', {
42200 type: 'short',
42201 prime: null,
42202 p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377',
42203 a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9',
42204 b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6',
42205 n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7',
42206 hash: hash_1.sha256, // or 384, or 512
42207 gRed: false,
42208 g: [
42209 '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262',
42210 '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997'
42211 ]
42212 });
42213
42214 // https://tools.ietf.org/html/rfc5639#section-3.6
42215 defineCurve('brainpoolP384r1', {
42216 type: 'short',
42217 prime: null,
42218 p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' +
42219 'ACD3A729 901D1A71 87470013 3107EC53',
42220 a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' +
42221 '8AA5814A 503AD4EB 04A8C7DD 22CE2826',
42222 b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' +
42223 '7CB43902 95DBC994 3AB78696 FA504C11',
42224 n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' +
42225 'CF3AB6AF 6B7FC310 3B883202 E9046565',
42226 hash: hash_1.sha384, // or 512
42227 gRed: false,
42228 g: [
42229 '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' +
42230 'E8E826E03436D646AAEF87B2E247D4AF1E',
42231 '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' +
42232 '280E4646217791811142820341263C5315'
42233 ]
42234 });
42235
42236 // https://tools.ietf.org/html/rfc5639#section-3.7
42237 defineCurve('brainpoolP512r1', {
42238 type: 'short',
42239 prime: null,
42240 p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' +
42241 '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3',
42242 a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' +
42243 '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA',
42244 b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' +
42245 '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723',
42246 n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' +
42247 '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069',
42248 hash: hash_1.sha512,
42249 gRed: false,
42250 g: [
42251 '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' +
42252 '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822',
42253 '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' +
42254 '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892'
42255 ]
42256 });
42257
42258 // https://en.bitcoin.it/wiki/Secp256k1
42259 var pre;
42260 try {
42261 pre = secp256k1;
42262 } catch (e) {
42263 pre = undefined;
42264 }
42265
42266 defineCurve('secp256k1', {
42267 type: 'short',
42268 prime: 'k256',
42269 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
42270 a: '0',
42271 b: '7',
42272 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
42273 h: '1',
42274 hash: hash_1.sha256,
42275
42276 // Precomputed endomorphism
42277 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
42278 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
42279 basis: [
42280 {
42281 a: '3086d221a7d46bcde86c90e49284eb15',
42282 b: '-e4437ed6010e88286f547fa90abfe4c3'
42283 },
42284 {
42285 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
42286 b: '3086d221a7d46bcde86c90e49284eb15'
42287 }
42288 ],
42289
42290 gRed: false,
42291 g: [
42292 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
42293 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
42294 pre
42295 ]
42296 });
42297 });
42298
42299 function HmacDRBG(options) {
42300 if (!(this instanceof HmacDRBG))
42301 return new HmacDRBG(options);
42302 this.hash = options.hash;
42303 this.predResist = !!options.predResist;
42304
42305 this.outLen = this.hash.outSize;
42306 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
42307
42308 this._reseed = null;
42309 this.reseedInterval = null;
42310 this.K = null;
42311 this.V = null;
42312
42313 var entropy = utils_1.toArray(options.entropy, options.entropyEnc || 'hex');
42314 var nonce = utils_1.toArray(options.nonce, options.nonceEnc || 'hex');
42315 var pers = utils_1.toArray(options.pers, options.persEnc || 'hex');
42316 minimalisticAssert(entropy.length >= (this.minEntropy / 8),
42317 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
42318 this._init(entropy, nonce, pers);
42319 }
42320 var hmacDrbg = HmacDRBG;
42321
42322 HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
42323 var seed = entropy.concat(nonce).concat(pers);
42324
42325 this.K = new Array(this.outLen / 8);
42326 this.V = new Array(this.outLen / 8);
42327 for (var i = 0; i < this.V.length; i++) {
42328 this.K[i] = 0x00;
42329 this.V[i] = 0x01;
42330 }
42331
42332 this._update(seed);
42333 this._reseed = 1;
42334 this.reseedInterval = 0x1000000000000; // 2^48
42335 };
42336
42337 HmacDRBG.prototype._hmac = function hmac() {
42338 return new hash_1.hmac(this.hash, this.K);
42339 };
42340
42341 HmacDRBG.prototype._update = function update(seed) {
42342 var kmac = this._hmac()
42343 .update(this.V)
42344 .update([ 0x00 ]);
42345 if (seed)
42346 kmac = kmac.update(seed);
42347 this.K = kmac.digest();
42348 this.V = this._hmac().update(this.V).digest();
42349 if (!seed)
42350 return;
42351
42352 this.K = this._hmac()
42353 .update(this.V)
42354 .update([ 0x01 ])
42355 .update(seed)
42356 .digest();
42357 this.V = this._hmac().update(this.V).digest();
42358 };
42359
42360 HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
42361 // Optional entropy enc
42362 if (typeof entropyEnc !== 'string') {
42363 addEnc = add;
42364 add = entropyEnc;
42365 entropyEnc = null;
42366 }
42367
42368 entropy = utils_1.toArray(entropy, entropyEnc);
42369 add = utils_1.toArray(add, addEnc);
42370
42371 minimalisticAssert(entropy.length >= (this.minEntropy / 8),
42372 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
42373
42374 this._update(entropy.concat(add || []));
42375 this._reseed = 1;
42376 };
42377
42378 HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
42379 if (this._reseed > this.reseedInterval)
42380 throw new Error('Reseed is required');
42381
42382 // Optional encoding
42383 if (typeof enc !== 'string') {
42384 addEnc = add;
42385 add = enc;
42386 enc = null;
42387 }
42388
42389 // Optional additional data
42390 if (add) {
42391 add = utils_1.toArray(add, addEnc || 'hex');
42392 this._update(add);
42393 }
42394
42395 var temp = [];
42396 while (temp.length < len) {
42397 this.V = this._hmac().update(this.V).digest();
42398 temp = temp.concat(this.V);
42399 }
42400
42401 var res = temp.slice(0, len);
42402 this._update(add);
42403 this._reseed++;
42404 return utils_1.encode(res, enc);
42405 };
42406
42407 var assert$5 = utils_1$1.assert;
42408
42409 function KeyPair(ec, options) {
42410 this.ec = ec;
42411 this.priv = null;
42412 this.pub = null;
42413
42414 // KeyPair(ec, { priv: ..., pub: ... })
42415 if (options.priv)
42416 this._importPrivate(options.priv, options.privEnc);
42417 if (options.pub)
42418 this._importPublic(options.pub, options.pubEnc);
42419 }
42420 var key = KeyPair;
42421
42422 KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
42423 if (pub instanceof KeyPair)
42424 return pub;
42425
42426 return new KeyPair(ec, {
42427 pub: pub,
42428 pubEnc: enc
42429 });
42430 };
42431
42432 KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
42433 if (priv instanceof KeyPair)
42434 return priv;
42435
42436 return new KeyPair(ec, {
42437 priv: priv,
42438 privEnc: enc
42439 });
42440 };
42441
42442 // TODO: should not validate for X25519
42443 KeyPair.prototype.validate = function validate() {
42444 var pub = this.getPublic();
42445
42446 if (pub.isInfinity())
42447 return { result: false, reason: 'Invalid public key' };
42448 if (!pub.validate())
42449 return { result: false, reason: 'Public key is not a point' };
42450 if (!pub.mul(this.ec.curve.n).isInfinity())
42451 return { result: false, reason: 'Public key * N != O' };
42452
42453 return { result: true, reason: null };
42454 };
42455
42456 KeyPair.prototype.getPublic = function getPublic(enc, compact) {
42457 if (!this.pub)
42458 this.pub = this.ec.g.mul(this.priv);
42459
42460 if (!enc)
42461 return this.pub;
42462
42463 return this.pub.encode(enc, compact);
42464 };
42465
42466 KeyPair.prototype.getPrivate = function getPrivate(enc) {
42467 if (enc === 'hex')
42468 return this.priv.toString(16, 2);
42469 else
42470 return this.priv;
42471 };
42472
42473 KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
42474 this.priv = new bn(key, enc || 16);
42475
42476 // For Curve25519/Curve448 we have a specific procedure.
42477 // TODO Curve448
42478 if (this.ec.curve.type === 'mont') {
42479 var one = this.ec.curve.one;
42480 var mask = one.ushln(255 - 3).sub(one).ushln(3);
42481 this.priv = this.priv.or(one.ushln(255 - 1));
42482 this.priv = this.priv.and(mask);
42483 } else
42484 // Ensure that the priv won't be bigger than n, otherwise we may fail
42485 // in fixed multiplication method
42486 this.priv = this.priv.umod(this.ec.curve.n);
42487 };
42488
42489 KeyPair.prototype._importPublic = function _importPublic(key, enc) {
42490 if (key.x || key.y) {
42491 // Montgomery points only have an `x` coordinate.
42492 // Weierstrass/Edwards points on the other hand have both `x` and
42493 // `y` coordinates.
42494 if (this.ec.curve.type === 'mont') {
42495 assert$5(key.x, 'Need x coordinate');
42496 } else if (this.ec.curve.type === 'short' ||
42497 this.ec.curve.type === 'edwards') {
42498 assert$5(key.x && key.y, 'Need both x and y coordinate');
42499 }
42500 this.pub = this.ec.curve.point(key.x, key.y);
42501 return;
42502 }
42503 this.pub = this.ec.curve.decodePoint(key, enc);
42504 };
42505
42506 // ECDH
42507 KeyPair.prototype.derive = function derive(pub) {
42508 return pub.mul(this.priv).getX();
42509 };
42510
42511 // ECDSA
42512 KeyPair.prototype.sign = function sign(msg, enc, options) {
42513 return this.ec.sign(msg, this, enc, options);
42514 };
42515
42516 KeyPair.prototype.verify = function verify(msg, signature) {
42517 return this.ec.verify(msg, signature, this);
42518 };
42519
42520 KeyPair.prototype.inspect = function inspect() {
42521 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
42522 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
42523 };
42524
42525 var assert$6 = utils_1$1.assert;
42526
42527 function Signature$1(options, enc) {
42528 if (options instanceof Signature$1)
42529 return options;
42530
42531 if (this._importDER(options, enc))
42532 return;
42533
42534 assert$6(options.r && options.s, 'Signature without r or s');
42535 this.r = new bn(options.r, 16);
42536 this.s = new bn(options.s, 16);
42537 if (options.recoveryParam === undefined)
42538 this.recoveryParam = null;
42539 else
42540 this.recoveryParam = options.recoveryParam;
42541 }
42542 var signature$1 = Signature$1;
42543
42544 function Position() {
42545 this.place = 0;
42546 }
42547
42548 function getLength(buf, p) {
42549 var initial = buf[p.place++];
42550 if (!(initial & 0x80)) {
42551 return initial;
42552 }
42553 var octetLen = initial & 0xf;
42554 var val = 0;
42555 for (var i = 0, off = p.place; i < octetLen; i++, off++) {
42556 val <<= 8;
42557 val |= buf[off];
42558 }
42559 p.place = off;
42560 return val;
42561 }
42562
42563 function rmPadding(buf) {
42564 var i = 0;
42565 var len = buf.length - 1;
42566 while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
42567 i++;
42568 }
42569 if (i === 0) {
42570 return buf;
42571 }
42572 return buf.slice(i);
42573 }
42574
42575 Signature$1.prototype._importDER = function _importDER(data, enc) {
42576 data = utils_1$1.toArray(data, enc);
42577 var p = new Position();
42578 if (data[p.place++] !== 0x30) {
42579 return false;
42580 }
42581 var len = getLength(data, p);
42582 if ((len + p.place) !== data.length) {
42583 return false;
42584 }
42585 if (data[p.place++] !== 0x02) {
42586 return false;
42587 }
42588 var rlen = getLength(data, p);
42589 var r = data.slice(p.place, rlen + p.place);
42590 p.place += rlen;
42591 if (data[p.place++] !== 0x02) {
42592 return false;
42593 }
42594 var slen = getLength(data, p);
42595 if (data.length !== slen + p.place) {
42596 return false;
42597 }
42598 var s = data.slice(p.place, slen + p.place);
42599 if (r[0] === 0 && (r[1] & 0x80)) {
42600 r = r.slice(1);
42601 }
42602 if (s[0] === 0 && (s[1] & 0x80)) {
42603 s = s.slice(1);
42604 }
42605
42606 this.r = new bn(r);
42607 this.s = new bn(s);
42608 this.recoveryParam = null;
42609
42610 return true;
42611 };
42612
42613 function constructLength(arr, len) {
42614 if (len < 0x80) {
42615 arr.push(len);
42616 return;
42617 }
42618 var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
42619 arr.push(octets | 0x80);
42620 while (--octets) {
42621 arr.push((len >>> (octets << 3)) & 0xff);
42622 }
42623 arr.push(len);
42624 }
42625
42626 Signature$1.prototype.toDER = function toDER(enc) {
42627 var r = this.r.toArray();
42628 var s = this.s.toArray();
42629
42630 // Pad values
42631 if (r[0] & 0x80)
42632 r = [ 0 ].concat(r);
42633 // Pad values
42634 if (s[0] & 0x80)
42635 s = [ 0 ].concat(s);
42636
42637 r = rmPadding(r);
42638 s = rmPadding(s);
42639
42640 while (!s[0] && !(s[1] & 0x80)) {
42641 s = s.slice(1);
42642 }
42643 var arr = [ 0x02 ];
42644 constructLength(arr, r.length);
42645 arr = arr.concat(r);
42646 arr.push(0x02);
42647 constructLength(arr, s.length);
42648 var backHalf = arr.concat(s);
42649 var res = [ 0x30 ];
42650 constructLength(res, backHalf.length);
42651 res = res.concat(backHalf);
42652 return utils_1$1.encode(res, enc);
42653 };
42654
42655 var assert$7 = utils_1$1.assert;
42656
42657
42658
42659
42660 function EC(options) {
42661 if (!(this instanceof EC))
42662 return new EC(options);
42663
42664 // Shortcut `elliptic.ec(curve-name)`
42665 if (typeof options === 'string') {
42666 assert$7(curves_1.hasOwnProperty(options), 'Unknown curve ' + options);
42667
42668 options = curves_1[options];
42669 }
42670
42671 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
42672 if (options instanceof curves_1.PresetCurve)
42673 options = { curve: options };
42674
42675 this.curve = options.curve.curve;
42676 this.n = this.curve.n;
42677 this.nh = this.n.ushrn(1);
42678 this.g = this.curve.g;
42679
42680 // Point on curve
42681 this.g = options.curve.g;
42682 this.g.precompute(options.curve.n.bitLength() + 1);
42683
42684 // Hash function for DRBG
42685 this.hash = options.hash || options.curve.hash;
42686 }
42687 var ec = EC;
42688
42689 EC.prototype.keyPair = function keyPair(options) {
42690 return new key(this, options);
42691 };
42692
42693 EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
42694 return key.fromPrivate(this, priv, enc);
42695 };
42696
42697 EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
42698 return key.fromPublic(this, pub, enc);
42699 };
42700
42701 EC.prototype.genKeyPair = function genKeyPair(options) {
42702 if (!options)
42703 options = {};
42704
42705 // Instantiate Hmac_DRBG
42706 var drbg = new hmacDrbg({
42707 hash: this.hash,
42708 pers: options.pers,
42709 persEnc: options.persEnc || 'utf8',
42710 entropy: options.entropy || brorand(this.hash.hmacStrength),
42711 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
42712 nonce: this.n.toArray()
42713 });
42714
42715 // Key generation for curve25519 is simpler
42716 if (this.curve.type === 'mont') {
42717 var priv = new bn(drbg.generate(32));
42718 return this.keyFromPrivate(priv);
42719 }
42720
42721 var bytes = this.n.byteLength();
42722 var ns2 = this.n.sub(new bn(2));
42723 do {
42724 var priv = new bn(drbg.generate(bytes));
42725 if (priv.cmp(ns2) > 0)
42726 continue;
42727
42728 priv.iaddn(1);
42729 return this.keyFromPrivate(priv);
42730 } while (true);
42731 };
42732
42733 EC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) {
42734 bitSize = bitSize || msg.byteLength() * 8;
42735 var delta = bitSize - this.n.bitLength();
42736 if (delta > 0)
42737 msg = msg.ushrn(delta);
42738 if (!truncOnly && msg.cmp(this.n) >= 0)
42739 return msg.sub(this.n);
42740 else
42741 return msg;
42742 };
42743
42744 EC.prototype.truncateMsg = function truncateMSG(msg) {
42745 // Bit size is only determined correctly for Uint8Arrays and hex strings
42746 var bitSize;
42747 if (msg instanceof Uint8Array) {
42748 bitSize = msg.byteLength * 8;
42749 msg = this._truncateToN(new bn(msg, 16), false, bitSize);
42750 } else if (typeof msg === 'string') {
42751 bitSize = msg.length * 4;
42752 msg = this._truncateToN(new bn(msg, 16), false, bitSize);
42753 } else {
42754 msg = this._truncateToN(new bn(msg, 16));
42755 }
42756 return msg;
42757 };
42758
42759 EC.prototype.sign = function sign(msg, key, enc, options) {
42760 if (typeof enc === 'object') {
42761 options = enc;
42762 enc = null;
42763 }
42764 if (!options)
42765 options = {};
42766
42767 key = this.keyFromPrivate(key, enc);
42768 msg = this.truncateMsg(msg);
42769
42770 // Zero-extend key to provide enough entropy
42771 var bytes = this.n.byteLength();
42772 var bkey = key.getPrivate().toArray('be', bytes);
42773
42774 // Zero-extend nonce to have the same byte size as N
42775 var nonce = msg.toArray('be', bytes);
42776
42777 // Instantiate Hmac_DRBG
42778 var drbg = new hmacDrbg({
42779 hash: this.hash,
42780 entropy: bkey,
42781 nonce: nonce,
42782 pers: options.pers,
42783 persEnc: options.persEnc || 'utf8'
42784 });
42785
42786 // Number of bytes to generate
42787 var ns1 = this.n.sub(new bn(1));
42788
42789 for (var iter = 0; true; iter++) {
42790 var k = options.k ?
42791 options.k(iter) :
42792 new bn(drbg.generate(this.n.byteLength()));
42793 k = this._truncateToN(k, true);
42794 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
42795 continue;
42796
42797 var kp = this.g.mul(k);
42798 if (kp.isInfinity())
42799 continue;
42800
42801 var kpX = kp.getX();
42802 var r = kpX.umod(this.n);
42803 if (r.cmpn(0) === 0)
42804 continue;
42805
42806 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
42807 s = s.umod(this.n);
42808 if (s.cmpn(0) === 0)
42809 continue;
42810
42811 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
42812 (kpX.cmp(r) !== 0 ? 2 : 0);
42813
42814 // Use complement of `s`, if it is > `n / 2`
42815 if (options.canonical && s.cmp(this.nh) > 0) {
42816 s = this.n.sub(s);
42817 recoveryParam ^= 1;
42818 }
42819
42820 return new signature$1({ r: r, s: s, recoveryParam: recoveryParam });
42821 }
42822 };
42823
42824 EC.prototype.verify = function verify(msg, signature, key, enc) {
42825 key = this.keyFromPublic(key, enc);
42826 signature = new signature$1(signature, 'hex');
42827 // Fallback to the old code
42828 var ret = this._verify(this.truncateMsg(msg), signature, key) ||
42829 this._verify(this._truncateToN(new bn(msg, 16)), signature, key);
42830 return ret;
42831 };
42832
42833 EC.prototype._verify = function _verify(msg, signature, key) {
42834 // Perform primitive values validation
42835 var r = signature.r;
42836 var s = signature.s;
42837 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
42838 return false;
42839 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
42840 return false;
42841
42842 // Validate signature
42843 var sinv = s.invm(this.n);
42844 var u1 = sinv.mul(msg).umod(this.n);
42845 var u2 = sinv.mul(r).umod(this.n);
42846
42847 if (!this.curve._maxwellTrick) {
42848 var p = this.g.mulAdd(u1, key.getPublic(), u2);
42849 if (p.isInfinity())
42850 return false;
42851
42852 return p.getX().umod(this.n).cmp(r) === 0;
42853 }
42854
42855 // NOTE: Greg Maxwell's trick, inspired by:
42856 // https://git.io/vad3K
42857
42858 var p = this.g.jmulAdd(u1, key.getPublic(), u2);
42859 if (p.isInfinity())
42860 return false;
42861
42862 // Compare `p.x` of Jacobian point with `r`,
42863 // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
42864 // inverse of `p.z^2`
42865 return p.eqXToP(r);
42866 };
42867
42868 EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
42869 assert$7((3 & j) === j, 'The recovery param is more than two bits');
42870 signature = new signature$1(signature, enc);
42871
42872 var n = this.n;
42873 var e = new bn(msg);
42874 var r = signature.r;
42875 var s = signature.s;
42876
42877 // A set LSB signifies that the y-coordinate is odd
42878 var isYOdd = j & 1;
42879 var isSecondKey = j >> 1;
42880 if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
42881 throw new Error('Unable to find sencond key candinate');
42882
42883 // 1.1. Let x = r + jn.
42884 if (isSecondKey)
42885 r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
42886 else
42887 r = this.curve.pointFromX(r, isYOdd);
42888
42889 var rInv = signature.r.invm(n);
42890 var s1 = n.sub(e).mul(rInv).umod(n);
42891 var s2 = s.mul(rInv).umod(n);
42892
42893 // 1.6.1 Compute Q = r^-1 (sR - eG)
42894 // Q = r^-1 (sR + -eG)
42895 return this.g.mulAdd(s1, r, s2);
42896 };
42897
42898 EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
42899 signature = new signature$1(signature, enc);
42900 if (signature.recoveryParam !== null)
42901 return signature.recoveryParam;
42902
42903 for (var i = 0; i < 4; i++) {
42904 var Qprime;
42905 try {
42906 Qprime = this.recoverPubKey(e, signature, i);
42907 } catch (e) {
42908 continue;
42909 }
42910
42911 if (Qprime.eq(Q))
42912 return i;
42913 }
42914 throw new Error('Unable to find valid recovery factor');
42915 };
42916
42917 var assert$8 = utils_1$1.assert;
42918 var parseBytes = utils_1$1.parseBytes;
42919 var cachedProperty = utils_1$1.cachedProperty;
42920
42921 /**
42922 * @param {EDDSA} eddsa - instance
42923 * @param {Object} params - public/private key parameters
42924 *
42925 * @param {Array<Byte>} [params.secret] - secret seed bytes
42926 * @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
42927 * @param {Array<Byte>} [params.pub] - public key point encoded as bytes
42928 *
42929 */
42930 function KeyPair$1(eddsa, params) {
42931 this.eddsa = eddsa;
42932 if (params.hasOwnProperty('secret'))
42933 this._secret = parseBytes(params.secret);
42934 if (eddsa.isPoint(params.pub))
42935 this._pub = params.pub;
42936 else {
42937 this._pubBytes = parseBytes(params.pub);
42938 if (this._pubBytes && this._pubBytes.length === 33 &&
42939 this._pubBytes[0] === 0x40)
42940 this._pubBytes = this._pubBytes.slice(1, 33);
42941 if (this._pubBytes && this._pubBytes.length !== 32)
42942 throw new Error('Unknown point compression format');
42943 }
42944 }
42945
42946 KeyPair$1.fromPublic = function fromPublic(eddsa, pub) {
42947 if (pub instanceof KeyPair$1)
42948 return pub;
42949 return new KeyPair$1(eddsa, { pub: pub });
42950 };
42951
42952 KeyPair$1.fromSecret = function fromSecret(eddsa, secret) {
42953 if (secret instanceof KeyPair$1)
42954 return secret;
42955 return new KeyPair$1(eddsa, { secret: secret });
42956 };
42957
42958 KeyPair$1.prototype.secret = function secret() {
42959 return this._secret;
42960 };
42961
42962 cachedProperty(KeyPair$1, 'pubBytes', function pubBytes() {
42963 return this.eddsa.encodePoint(this.pub());
42964 });
42965
42966 cachedProperty(KeyPair$1, 'pub', function pub() {
42967 if (this._pubBytes)
42968 return this.eddsa.decodePoint(this._pubBytes);
42969 return this.eddsa.g.mul(this.priv());
42970 });
42971
42972 cachedProperty(KeyPair$1, 'privBytes', function privBytes() {
42973 var eddsa = this.eddsa;
42974 var hash = this.hash();
42975 var lastIx = eddsa.encodingLength - 1;
42976
42977 // https://tools.ietf.org/html/rfc8032#section-5.1.5
42978 var a = hash.slice(0, eddsa.encodingLength);
42979 a[0] &= 248;
42980 a[lastIx] &= 127;
42981 a[lastIx] |= 64;
42982
42983 return a;
42984 });
42985
42986 cachedProperty(KeyPair$1, 'priv', function priv() {
42987 return this.eddsa.decodeInt(this.privBytes());
42988 });
42989
42990 cachedProperty(KeyPair$1, 'hash', function hash() {
42991 return this.eddsa.hash().update(this.secret()).digest();
42992 });
42993
42994 cachedProperty(KeyPair$1, 'messagePrefix', function messagePrefix() {
42995 return this.hash().slice(this.eddsa.encodingLength);
42996 });
42997
42998 KeyPair$1.prototype.sign = function sign(message) {
42999 assert$8(this._secret, 'KeyPair can only verify');
43000 return this.eddsa.sign(message, this);
43001 };
43002
43003 KeyPair$1.prototype.verify = function verify(message, sig) {
43004 return this.eddsa.verify(message, sig, this);
43005 };
43006
43007 KeyPair$1.prototype.getSecret = function getSecret(enc) {
43008 assert$8(this._secret, 'KeyPair is public only');
43009 return utils_1$1.encode(this.secret(), enc);
43010 };
43011
43012 KeyPair$1.prototype.getPublic = function getPublic(enc, compact) {
43013 return utils_1$1.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc);
43014 };
43015
43016 var key$1 = KeyPair$1;
43017
43018 var assert$9 = utils_1$1.assert;
43019 var cachedProperty$1 = utils_1$1.cachedProperty;
43020 var parseBytes$1 = utils_1$1.parseBytes;
43021
43022 /**
43023 * @param {EDDSA} eddsa - eddsa instance
43024 * @param {Array<Bytes>|Object} sig -
43025 * @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
43026 * @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
43027 * @param {Array<Bytes>} [sig.Rencoded] - R point encoded
43028 * @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
43029 */
43030 function Signature$2(eddsa, sig) {
43031 this.eddsa = eddsa;
43032
43033 if (typeof sig !== 'object')
43034 sig = parseBytes$1(sig);
43035
43036 if (Array.isArray(sig)) {
43037 sig = {
43038 R: sig.slice(0, eddsa.encodingLength),
43039 S: sig.slice(eddsa.encodingLength)
43040 };
43041 }
43042
43043 assert$9(sig.R && sig.S, 'Signature without R or S');
43044
43045 if (eddsa.isPoint(sig.R))
43046 this._R = sig.R;
43047 if (sig.S instanceof bn)
43048 this._S = sig.S;
43049
43050 this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
43051 this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
43052 }
43053
43054 cachedProperty$1(Signature$2, 'S', function S() {
43055 return this.eddsa.decodeInt(this.Sencoded());
43056 });
43057
43058 cachedProperty$1(Signature$2, 'R', function R() {
43059 return this.eddsa.decodePoint(this.Rencoded());
43060 });
43061
43062 cachedProperty$1(Signature$2, 'Rencoded', function Rencoded() {
43063 return this.eddsa.encodePoint(this.R());
43064 });
43065
43066 cachedProperty$1(Signature$2, 'Sencoded', function Sencoded() {
43067 return this.eddsa.encodeInt(this.S());
43068 });
43069
43070 Signature$2.prototype.toBytes = function toBytes() {
43071 return this.Rencoded().concat(this.Sencoded());
43072 };
43073
43074 Signature$2.prototype.toHex = function toHex() {
43075 return utils_1$1.encode(this.toBytes(), 'hex').toUpperCase();
43076 };
43077
43078 var signature$2 = Signature$2;
43079
43080 var assert$a = utils_1$1.assert;
43081 var parseBytes$2 = utils_1$1.parseBytes;
43082
43083
43084
43085 function EDDSA(curve) {
43086 assert$a(curve === 'ed25519', 'only tested with ed25519 so far');
43087
43088 if (!(this instanceof EDDSA))
43089 return new EDDSA(curve);
43090
43091 var curve = curves_1[curve].curve;
43092 this.curve = curve;
43093 this.g = curve.g;
43094 this.g.precompute(curve.n.bitLength() + 1);
43095
43096 this.pointClass = curve.point().constructor;
43097 this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
43098 this.hash = hash_1.sha512;
43099 }
43100
43101 var eddsa$1 = EDDSA;
43102
43103 /**
43104 * @param {Array|String} message - message bytes
43105 * @param {Array|String|KeyPair} secret - secret bytes or a keypair
43106 * @returns {Signature} - signature
43107 */
43108 EDDSA.prototype.sign = function sign(message, secret) {
43109 message = parseBytes$2(message);
43110 var key = this.keyFromSecret(secret);
43111 var r = this.hashInt(key.messagePrefix(), message);
43112 var R = this.g.mul(r);
43113 var Rencoded = this.encodePoint(R);
43114 var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
43115 .mul(key.priv());
43116 var S = r.add(s_).umod(this.curve.n);
43117 return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
43118 };
43119
43120 /**
43121 * @param {Array} message - message bytes
43122 * @param {Array|String|Signature} sig - sig bytes
43123 * @param {Array|String|Point|KeyPair} pub - public key
43124 * @returns {Boolean} - true if public key matches sig of message
43125 */
43126 EDDSA.prototype.verify = function verify(message, sig, pub) {
43127 message = parseBytes$2(message);
43128 sig = this.makeSignature(sig);
43129 var key = this.keyFromPublic(pub);
43130 var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
43131 var SG = this.g.mul(sig.S());
43132 var RplusAh = sig.R().add(key.pub().mul(h));
43133 return RplusAh.eq(SG);
43134 };
43135
43136 EDDSA.prototype.hashInt = function hashInt() {
43137 var hash = this.hash();
43138 for (var i = 0; i < arguments.length; i++)
43139 hash.update(arguments[i]);
43140 return utils_1$1.intFromLE(hash.digest()).umod(this.curve.n);
43141 };
43142
43143 EDDSA.prototype.keyPair = function keyPair(options) {
43144 return new key$1(this, options);
43145 };
43146
43147 EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
43148 return key$1.fromPublic(this, pub);
43149 };
43150
43151 EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
43152 return key$1.fromSecret(this, secret);
43153 };
43154
43155 EDDSA.prototype.genKeyPair = function genKeyPair(options) {
43156 if (!options)
43157 options = {};
43158
43159 // Instantiate Hmac_DRBG
43160 var drbg = new hmacDrbg({
43161 hash: this.hash,
43162 pers: options.pers,
43163 persEnc: options.persEnc || 'utf8',
43164 entropy: options.entropy || brorand(this.hash.hmacStrength),
43165 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
43166 nonce: this.curve.n.toArray()
43167 });
43168
43169 return this.keyFromSecret(drbg.generate(32));
43170 };
43171
43172 EDDSA.prototype.makeSignature = function makeSignature(sig) {
43173 if (sig instanceof signature$2)
43174 return sig;
43175 return new signature$2(this, sig);
43176 };
43177
43178 /**
43179 * * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
43180 *
43181 * EDDSA defines methods for encoding and decoding points and integers. These are
43182 * helper convenience methods, that pass along to utility functions implied
43183 * parameters.
43184 *
43185 */
43186 EDDSA.prototype.encodePoint = function encodePoint(point) {
43187 var enc = point.getY().toArray('le', this.encodingLength);
43188 enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
43189 return enc;
43190 };
43191
43192 EDDSA.prototype.decodePoint = function decodePoint(bytes) {
43193 bytes = utils_1$1.parseBytes(bytes);
43194
43195 var lastIx = bytes.length - 1;
43196 var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
43197 var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
43198
43199 var y = utils_1$1.intFromLE(normed);
43200 return this.curve.pointFromY(y, xIsOdd);
43201 };
43202
43203 EDDSA.prototype.encodeInt = function encodeInt(num) {
43204 return num.toArray('le', this.encodingLength);
43205 };
43206
43207 EDDSA.prototype.decodeInt = function decodeInt(bytes) {
43208 return utils_1$1.intFromLE(bytes);
43209 };
43210
43211 EDDSA.prototype.isPoint = function isPoint(val) {
43212 return val instanceof this.pointClass;
43213 };
43214
43215 var elliptic_1 = createCommonjsModule(function (module, exports) {
43216
43217 var elliptic = exports;
43218
43219 elliptic.utils = utils_1$1;
43220 elliptic.rand = brorand;
43221 elliptic.curve = curve_1;
43222 elliptic.curves = curves_1;
43223
43224 // Protocols
43225 elliptic.ec = ec;
43226 elliptic.eddsa = eddsa$1;
43227 });
43228
43229 var elliptic$1 = /*#__PURE__*/Object.freeze({
43230 __proto__: null,
43231 'default': elliptic_1,
43232 __moduleExports: elliptic_1
43233 });
43234
43235 exports.AEADEncryptedDataPacket = AEADEncryptedDataPacket;
43236 exports.CleartextMessage = CleartextMessage;
43237 exports.CompressedDataPacket = CompressedDataPacket;
43238 exports.LiteralDataPacket = LiteralDataPacket;
43239 exports.MarkerPacket = MarkerPacket;
43240 exports.Message = Message;
43241 exports.OnePassSignaturePacket = OnePassSignaturePacket;
43242 exports.PacketList = PacketList;
43243 exports.PrivateKey = PrivateKey;
43244 exports.PublicKey = PublicKey;
43245 exports.PublicKeyEncryptedSessionKeyPacket = PublicKeyEncryptedSessionKeyPacket;
43246 exports.PublicKeyPacket = PublicKeyPacket;
43247 exports.PublicSubkeyPacket = PublicSubkeyPacket;
43248 exports.SecretKeyPacket = SecretKeyPacket;
43249 exports.SecretSubkeyPacket = SecretSubkeyPacket;
43250 exports.Signature = Signature;
43251 exports.SignaturePacket = SignaturePacket;
43252 exports.Subkey = Subkey;
43253 exports.SymEncryptedIntegrityProtectedDataPacket = SymEncryptedIntegrityProtectedDataPacket;
43254 exports.SymEncryptedSessionKeyPacket = SymEncryptedSessionKeyPacket;
43255 exports.SymmetricallyEncryptedDataPacket = SymmetricallyEncryptedDataPacket;
43256 exports.TrustPacket = TrustPacket;
43257 exports.UserAttributePacket = UserAttributePacket;
43258 exports.UserIDPacket = UserIDPacket;
43259 exports.armor = armor;
43260 exports.config = defaultConfig;
43261 exports.createCleartextMessage = createCleartextMessage;
43262 exports.createMessage = createMessage;
43263 exports.decrypt = decrypt$4;
43264 exports.decryptKey = decryptKey;
43265 exports.decryptSessionKeys = decryptSessionKeys;
43266 exports.encrypt = encrypt$4;
43267 exports.encryptKey = encryptKey;
43268 exports.encryptSessionKey = encryptSessionKey;
43269 exports.enums = enums;
43270 exports.generateKey = generateKey;
43271 exports.generateSessionKey = generateSessionKey$1;
43272 exports.readCleartextMessage = readCleartextMessage;
43273 exports.readKey = readKey;
43274 exports.readKeys = readKeys;
43275 exports.readMessage = readMessage;
43276 exports.readPrivateKey = readPrivateKey;
43277 exports.readPrivateKeys = readPrivateKeys;
43278 exports.readSignature = readSignature;
43279 exports.reformatKey = reformatKey;
43280 exports.revokeKey = revokeKey;
43281 exports.sign = sign$5;
43282 exports.unarmor = unarmor;
43283 exports.verify = verify$5;
43284
43285 Object.defineProperty(exports, '__esModule', { value: true });
43286
43287 return exports;
43288
43289}({}));